tlshand.c 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318
  1. #include <u.h>
  2. #include <libc.h>
  3. #include <bio.h>
  4. #include <auth.h>
  5. #include <mp.h>
  6. #include <libsec.h>
  7. // The main groups of functions are:
  8. // client/server - main handshake protocol definition
  9. // message functions - formating handshake messages
  10. // cipher choices - catalog of digest and encrypt algorithms
  11. // security functions - PKCS#1, sslHMAC, session keygen
  12. // general utility functions - malloc, serialization
  13. // The handshake protocol builds on the TLS/SSL3 record layer protocol,
  14. // which is implemented in kernel device #a. See also /lib/rfc/rfc2246.
  15. enum {
  16. TLSFinishedLen = 12,
  17. SSL3FinishedLen = MD5dlen+SHA1dlen,
  18. MaxKeyData = 104, // amount of secret we may need
  19. MaxChunk = 1<<14,
  20. RandomSize = 32,
  21. SidSize = 32,
  22. MasterSecretSize = 48,
  23. AQueue = 0,
  24. AFlush = 1,
  25. };
  26. typedef struct TlsSec TlsSec;
  27. typedef struct Bytes{
  28. int len;
  29. uchar data[1]; // [len]
  30. } Bytes;
  31. typedef struct Ints{
  32. int len;
  33. int data[1]; // [len]
  34. } Ints;
  35. typedef struct Algs{
  36. char *enc;
  37. char *digest;
  38. int nsecret;
  39. int tlsid;
  40. int ok;
  41. } Algs;
  42. typedef struct Finished{
  43. uchar verify[SSL3FinishedLen];
  44. int n;
  45. } Finished;
  46. typedef struct TlsConnection{
  47. TlsSec *sec; // security management goo
  48. int hand, ctl; // record layer file descriptors
  49. int erred; // set when tlsError called
  50. int (*trace)(char*fmt, ...); // for debugging
  51. int version; // protocol we are speaking
  52. int verset; // version has been set
  53. int ver2hi; // server got a version 2 hello
  54. int isClient; // is this the client or server?
  55. Bytes *sid; // SessionID
  56. Bytes *cert; // only last - no chain
  57. Lock statelk;
  58. int state; // must be set using setstate
  59. // input buffer for handshake messages
  60. uchar buf[MaxChunk+2048];
  61. uchar *rp, *ep;
  62. uchar crandom[RandomSize]; // client random
  63. uchar srandom[RandomSize]; // server random
  64. int clientVersion; // version in ClientHello
  65. char *digest; // name of digest algorithm to use
  66. char *enc; // name of encryption algorithm to use
  67. int nsecret; // amount of secret data to init keys
  68. // for finished messages
  69. MD5state hsmd5; // handshake hash
  70. SHAstate hssha1; // handshake hash
  71. Finished finished;
  72. } TlsConnection;
  73. typedef struct Msg{
  74. int tag;
  75. union {
  76. struct {
  77. int version;
  78. uchar random[RandomSize];
  79. Bytes* sid;
  80. Ints* ciphers;
  81. Bytes* compressors;
  82. } clientHello;
  83. struct {
  84. int version;
  85. uchar random[RandomSize];
  86. Bytes* sid;
  87. int cipher;
  88. int compressor;
  89. } serverHello;
  90. struct {
  91. int ncert;
  92. Bytes **certs;
  93. } certificate;
  94. struct {
  95. Bytes *types;
  96. int nca;
  97. Bytes **cas;
  98. } certificateRequest;
  99. struct {
  100. Bytes *key;
  101. } clientKeyExchange;
  102. Finished finished;
  103. } u;
  104. } Msg;
  105. typedef struct TlsSec{
  106. char *server; // name of remote; nil for server
  107. int ok; // <0 killed; == 0 in progress; >0 reusable
  108. RSApub *rsapub;
  109. AuthRpc *rpc; // factotum for rsa private key
  110. uchar sec[MasterSecretSize]; // master secret
  111. uchar crandom[RandomSize]; // client random
  112. uchar srandom[RandomSize]; // server random
  113. int clientVers; // version in ClientHello
  114. int vers; // final version
  115. // byte generation and handshake checksum
  116. void (*prf)(uchar*, int, uchar*, int, char*, uchar*, int, uchar*, int);
  117. void (*setFinished)(TlsSec*, MD5state, SHAstate, uchar*, int);
  118. int nfin;
  119. } TlsSec;
  120. enum {
  121. TLSVersion = 0x0301,
  122. SSL3Version = 0x0300,
  123. ProtocolVersion = 0x0301, // maximum version we speak
  124. MinProtoVersion = 0x0300, // limits on version we accept
  125. MaxProtoVersion = 0x03ff,
  126. };
  127. // handshake type
  128. enum {
  129. HHelloRequest,
  130. HClientHello,
  131. HServerHello,
  132. HSSL2ClientHello = 9, /* local convention; see devtls.c */
  133. HCertificate = 11,
  134. HServerKeyExchange,
  135. HCertificateRequest,
  136. HServerHelloDone,
  137. HCertificateVerify,
  138. HClientKeyExchange,
  139. HFinished = 20,
  140. HMax
  141. };
  142. // alerts
  143. enum {
  144. ECloseNotify = 0,
  145. EUnexpectedMessage = 10,
  146. EBadRecordMac = 20,
  147. EDecryptionFailed = 21,
  148. ERecordOverflow = 22,
  149. EDecompressionFailure = 30,
  150. EHandshakeFailure = 40,
  151. ENoCertificate = 41,
  152. EBadCertificate = 42,
  153. EUnsupportedCertificate = 43,
  154. ECertificateRevoked = 44,
  155. ECertificateExpired = 45,
  156. ECertificateUnknown = 46,
  157. EIllegalParameter = 47,
  158. EUnknownCa = 48,
  159. EAccessDenied = 49,
  160. EDecodeError = 50,
  161. EDecryptError = 51,
  162. EExportRestriction = 60,
  163. EProtocolVersion = 70,
  164. EInsufficientSecurity = 71,
  165. EInternalError = 80,
  166. EUserCanceled = 90,
  167. ENoRenegotiation = 100,
  168. EMax = 256
  169. };
  170. // cipher suites
  171. enum {
  172. TLS_NULL_WITH_NULL_NULL = 0x0000,
  173. TLS_RSA_WITH_NULL_MD5 = 0x0001,
  174. TLS_RSA_WITH_NULL_SHA = 0x0002,
  175. TLS_RSA_EXPORT_WITH_RC4_40_MD5 = 0x0003,
  176. TLS_RSA_WITH_RC4_128_MD5 = 0x0004,
  177. TLS_RSA_WITH_RC4_128_SHA = 0x0005,
  178. TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 = 0X0006,
  179. TLS_RSA_WITH_IDEA_CBC_SHA = 0X0007,
  180. TLS_RSA_EXPORT_WITH_DES40_CBC_SHA = 0X0008,
  181. TLS_RSA_WITH_DES_CBC_SHA = 0X0009,
  182. TLS_RSA_WITH_3DES_EDE_CBC_SHA = 0X000A,
  183. TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA = 0X000B,
  184. TLS_DH_DSS_WITH_DES_CBC_SHA = 0X000C,
  185. TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA = 0X000D,
  186. TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA = 0X000E,
  187. TLS_DH_RSA_WITH_DES_CBC_SHA = 0X000F,
  188. TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA = 0X0010,
  189. TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA = 0X0011,
  190. TLS_DHE_DSS_WITH_DES_CBC_SHA = 0X0012,
  191. TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA = 0X0013, // ZZZ must be implemented for tls1.0 compliance
  192. TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA = 0X0014,
  193. TLS_DHE_RSA_WITH_DES_CBC_SHA = 0X0015,
  194. TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA = 0X0016,
  195. TLS_DH_anon_EXPORT_WITH_RC4_40_MD5 = 0x0017,
  196. TLS_DH_anon_WITH_RC4_128_MD5 = 0x0018,
  197. TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA = 0X0019,
  198. TLS_DH_anon_WITH_DES_CBC_SHA = 0X001A,
  199. TLS_DH_anon_WITH_3DES_EDE_CBC_SHA = 0X001B,
  200. TLS_RSA_WITH_AES_128_CBC_SHA = 0X002f, // aes, aka rijndael with 128 bit blocks
  201. TLS_DH_DSS_WITH_AES_128_CBC_SHA = 0X0030,
  202. TLS_DH_RSA_WITH_AES_128_CBC_SHA = 0X0031,
  203. TLS_DHE_DSS_WITH_AES_128_CBC_SHA = 0X0032,
  204. TLS_DHE_RSA_WITH_AES_128_CBC_SHA = 0X0033,
  205. TLS_DH_anon_WITH_AES_128_CBC_SHA = 0X0034,
  206. TLS_RSA_WITH_AES_256_CBC_SHA = 0X0035,
  207. TLS_DH_DSS_WITH_AES_256_CBC_SHA = 0X0036,
  208. TLS_DH_RSA_WITH_AES_256_CBC_SHA = 0X0037,
  209. TLS_DHE_DSS_WITH_AES_256_CBC_SHA = 0X0038,
  210. TLS_DHE_RSA_WITH_AES_256_CBC_SHA = 0X0039,
  211. TLS_DH_anon_WITH_AES_256_CBC_SHA = 0X003A,
  212. CipherMax
  213. };
  214. // compression methods
  215. enum {
  216. CompressionNull = 0,
  217. CompressionMax
  218. };
  219. static Algs cipherAlgs[] = {
  220. {"rc4_128", "md5", 2 * (16 + MD5dlen), TLS_RSA_WITH_RC4_128_MD5},
  221. {"rc4_128", "sha1", 2 * (16 + SHA1dlen), TLS_RSA_WITH_RC4_128_SHA},
  222. {"3des_ede_cbc","sha1",2*(4*8+SHA1dlen), TLS_RSA_WITH_3DES_EDE_CBC_SHA},
  223. };
  224. static uchar compressors[] = {
  225. CompressionNull,
  226. };
  227. static TlsConnection *tlsServer2(int ctl, int hand, uchar *cert, int ncert, int (*trace)(char*fmt, ...), PEMChain *chain);
  228. static TlsConnection *tlsClient2(int ctl, int hand, uchar *csid, int ncsid, int (*trace)(char*fmt, ...));
  229. static void msgClear(Msg *m);
  230. static char* msgPrint(char *buf, int n, Msg *m);
  231. static int msgRecv(TlsConnection *c, Msg *m);
  232. static int msgSend(TlsConnection *c, Msg *m, int act);
  233. static void tlsError(TlsConnection *c, int err, char *msg, ...);
  234. #pragma varargck argpos tlsError 3
  235. static int setVersion(TlsConnection *c, int version);
  236. static int finishedMatch(TlsConnection *c, Finished *f);
  237. static void tlsConnectionFree(TlsConnection *c);
  238. static int setAlgs(TlsConnection *c, int a);
  239. static int okCipher(Ints *cv);
  240. static int okCompression(Bytes *cv);
  241. static int initCiphers(void);
  242. static Ints* makeciphers(void);
  243. static TlsSec* tlsSecInits(int cvers, uchar *csid, int ncsid, uchar *crandom, uchar *ssid, int *nssid, uchar *srandom);
  244. static int tlsSecSecrets(TlsSec *sec, int vers, uchar *epm, int nepm, uchar *kd, int nkd);
  245. static TlsSec* tlsSecInitc(int cvers, uchar *crandom);
  246. static int tlsSecSecretc(TlsSec *sec, uchar *sid, int nsid, uchar *srandom, uchar *cert, int ncert, int vers, uchar **epm, int *nepm, uchar *kd, int nkd);
  247. static int tlsSecFinished(TlsSec *sec, MD5state md5, SHAstate sha1, uchar *fin, int nfin, int isclient);
  248. static void tlsSecOk(TlsSec *sec);
  249. static void tlsSecKill(TlsSec *sec);
  250. static void tlsSecClose(TlsSec *sec);
  251. static void setMasterSecret(TlsSec *sec, Bytes *pm);
  252. static void serverMasterSecret(TlsSec *sec, uchar *epm, int nepm);
  253. static void setSecrets(TlsSec *sec, uchar *kd, int nkd);
  254. static int clientMasterSecret(TlsSec *sec, RSApub *pub, uchar **epm, int *nepm);
  255. static Bytes *pkcs1_encrypt(Bytes* data, RSApub* key, int blocktype);
  256. static Bytes *pkcs1_decrypt(TlsSec *sec, uchar *epm, int nepm);
  257. static void tlsSetFinished(TlsSec *sec, MD5state hsmd5, SHAstate hssha1, uchar *finished, int isClient);
  258. static void sslSetFinished(TlsSec *sec, MD5state hsmd5, SHAstate hssha1, uchar *finished, int isClient);
  259. static void sslPRF(uchar *buf, int nbuf, uchar *key, int nkey, char *label,
  260. uchar *seed0, int nseed0, uchar *seed1, int nseed1);
  261. static int setVers(TlsSec *sec, int version);
  262. static AuthRpc* factotum_rsa_open(uchar *cert, int certlen);
  263. static mpint* factotum_rsa_decrypt(AuthRpc *rpc, mpint *cipher);
  264. static void factotum_rsa_close(AuthRpc*rpc);
  265. static void* emalloc(int);
  266. static void* erealloc(void*, int);
  267. static void put32(uchar *p, u32int);
  268. static void put24(uchar *p, int);
  269. static void put16(uchar *p, int);
  270. static u32int get32(uchar *p);
  271. static int get24(uchar *p);
  272. static int get16(uchar *p);
  273. static Bytes* newbytes(int len);
  274. static Bytes* makebytes(uchar* buf, int len);
  275. static void freebytes(Bytes* b);
  276. static Ints* newints(int len);
  277. static Ints* makeints(int* buf, int len);
  278. static void freeints(Ints* b);
  279. //================= client/server ========================
  280. // push TLS onto fd, returning new (application) file descriptor
  281. // or -1 if error.
  282. int
  283. tlsServer(int fd, TLSconn *conn)
  284. {
  285. char buf[8];
  286. char dname[64];
  287. int n, data, ctl, hand;
  288. TlsConnection *tls;
  289. if(conn == nil)
  290. return -1;
  291. ctl = open("#a/tls/clone", ORDWR);
  292. if(ctl < 0)
  293. return -1;
  294. n = read(ctl, buf, sizeof(buf)-1);
  295. if(n < 0){
  296. close(ctl);
  297. return -1;
  298. }
  299. buf[n] = 0;
  300. sprint(conn->dir, "#a/tls/%s", buf);
  301. sprint(dname, "#a/tls/%s/hand", buf);
  302. hand = open(dname, ORDWR);
  303. if(hand < 0){
  304. close(ctl);
  305. return -1;
  306. }
  307. fprint(ctl, "fd %d 0x%x", fd, ProtocolVersion);
  308. tls = tlsServer2(ctl, hand, conn->cert, conn->certlen, conn->trace, conn->chain);
  309. sprint(dname, "#a/tls/%s/data", buf);
  310. data = open(dname, ORDWR);
  311. close(fd);
  312. close(hand);
  313. close(ctl);
  314. if(data < 0){
  315. return -1;
  316. }
  317. if(tls == nil){
  318. close(data);
  319. return -1;
  320. }
  321. if(conn->cert)
  322. free(conn->cert);
  323. conn->cert = 0; // client certificates are not yet implemented
  324. conn->certlen = 0;
  325. conn->sessionIDlen = tls->sid->len;
  326. conn->sessionID = emalloc(conn->sessionIDlen);
  327. memcpy(conn->sessionID, tls->sid->data, conn->sessionIDlen);
  328. if(conn->sessionKey != nil && conn->sessionType != nil && strcmp(conn->sessionType, "ttls") == 0)
  329. tls->sec->prf(conn->sessionKey, conn->sessionKeylen, tls->sec->sec, MasterSecretSize, conn->sessionConst, tls->sec->crandom, RandomSize, tls->sec->srandom, RandomSize);
  330. tlsConnectionFree(tls);
  331. return data;
  332. }
  333. // push TLS onto fd, returning new (application) file descriptor
  334. // or -1 if error.
  335. int
  336. tlsClient(int fd, TLSconn *conn)
  337. {
  338. char buf[8];
  339. char dname[64];
  340. int n, data, ctl, hand;
  341. TlsConnection *tls;
  342. if(!conn)
  343. return -1;
  344. ctl = open("#a/tls/clone", ORDWR);
  345. if(ctl < 0)
  346. return -1;
  347. n = read(ctl, buf, sizeof(buf)-1);
  348. if(n < 0){
  349. close(ctl);
  350. return -1;
  351. }
  352. buf[n] = 0;
  353. sprint(conn->dir, "#a/tls/%s", buf);
  354. sprint(dname, "#a/tls/%s/hand", buf);
  355. hand = open(dname, ORDWR);
  356. if(hand < 0){
  357. close(ctl);
  358. return -1;
  359. }
  360. sprint(dname, "#a/tls/%s/data", buf);
  361. data = open(dname, ORDWR);
  362. if(data < 0)
  363. return -1;
  364. fprint(ctl, "fd %d 0x%x", fd, ProtocolVersion);
  365. tls = tlsClient2(ctl, hand, conn->sessionID, conn->sessionIDlen, conn->trace);
  366. close(fd);
  367. close(hand);
  368. close(ctl);
  369. if(tls == nil){
  370. close(data);
  371. return -1;
  372. }
  373. conn->certlen = tls->cert->len;
  374. conn->cert = emalloc(conn->certlen);
  375. memcpy(conn->cert, tls->cert->data, conn->certlen);
  376. conn->sessionIDlen = tls->sid->len;
  377. conn->sessionID = emalloc(conn->sessionIDlen);
  378. memcpy(conn->sessionID, tls->sid->data, conn->sessionIDlen);
  379. if(conn->sessionKey != nil && conn->sessionType != nil && strcmp(conn->sessionType, "ttls") == 0)
  380. tls->sec->prf(conn->sessionKey, conn->sessionKeylen, tls->sec->sec, MasterSecretSize, conn->sessionConst, tls->sec->crandom, RandomSize, tls->sec->srandom, RandomSize);
  381. tlsConnectionFree(tls);
  382. return data;
  383. }
  384. static int
  385. countchain(PEMChain *p)
  386. {
  387. int i = 0;
  388. while (p) {
  389. i++;
  390. p = p->next;
  391. }
  392. return i;
  393. }
  394. static TlsConnection *
  395. tlsServer2(int ctl, int hand, uchar *cert, int ncert, int (*trace)(char*fmt, ...), PEMChain *chp)
  396. {
  397. TlsConnection *c;
  398. Msg m;
  399. Bytes *csid;
  400. uchar sid[SidSize], kd[MaxKeyData];
  401. char *secrets;
  402. int cipher, compressor, nsid, rv, numcerts, i;
  403. if(trace)
  404. trace("tlsServer2\n");
  405. if(!initCiphers())
  406. return nil;
  407. c = emalloc(sizeof(TlsConnection));
  408. c->ctl = ctl;
  409. c->hand = hand;
  410. c->trace = trace;
  411. c->version = ProtocolVersion;
  412. memset(&m, 0, sizeof(m));
  413. if(!msgRecv(c, &m)){
  414. if(trace)
  415. trace("initial msgRecv failed\n");
  416. goto Err;
  417. }
  418. if(m.tag != HClientHello) {
  419. tlsError(c, EUnexpectedMessage, "expected a client hello");
  420. goto Err;
  421. }
  422. c->clientVersion = m.u.clientHello.version;
  423. if(trace)
  424. trace("ClientHello version %x\n", c->clientVersion);
  425. if(setVersion(c, m.u.clientHello.version) < 0) {
  426. tlsError(c, EIllegalParameter, "incompatible version");
  427. goto Err;
  428. }
  429. memmove(c->crandom, m.u.clientHello.random, RandomSize);
  430. cipher = okCipher(m.u.clientHello.ciphers);
  431. if(cipher < 0) {
  432. // reply with EInsufficientSecurity if we know that's the case
  433. if(cipher == -2)
  434. tlsError(c, EInsufficientSecurity, "cipher suites too weak");
  435. else
  436. tlsError(c, EHandshakeFailure, "no matching cipher suite");
  437. goto Err;
  438. }
  439. if(!setAlgs(c, cipher)){
  440. tlsError(c, EHandshakeFailure, "no matching cipher suite");
  441. goto Err;
  442. }
  443. compressor = okCompression(m.u.clientHello.compressors);
  444. if(compressor < 0) {
  445. tlsError(c, EHandshakeFailure, "no matching compressor");
  446. goto Err;
  447. }
  448. csid = m.u.clientHello.sid;
  449. if(trace)
  450. trace(" cipher %d, compressor %d, csidlen %d\n", cipher, compressor, csid->len);
  451. c->sec = tlsSecInits(c->clientVersion, csid->data, csid->len, c->crandom, sid, &nsid, c->srandom);
  452. if(c->sec == nil){
  453. tlsError(c, EHandshakeFailure, "can't initialize security: %r");
  454. goto Err;
  455. }
  456. c->sec->rpc = factotum_rsa_open(cert, ncert);
  457. if(c->sec->rpc == nil){
  458. tlsError(c, EHandshakeFailure, "factotum_rsa_open: %r");
  459. goto Err;
  460. }
  461. c->sec->rsapub = X509toRSApub(cert, ncert, nil, 0);
  462. msgClear(&m);
  463. m.tag = HServerHello;
  464. m.u.serverHello.version = c->version;
  465. memmove(m.u.serverHello.random, c->srandom, RandomSize);
  466. m.u.serverHello.cipher = cipher;
  467. m.u.serverHello.compressor = compressor;
  468. c->sid = makebytes(sid, nsid);
  469. m.u.serverHello.sid = makebytes(c->sid->data, c->sid->len);
  470. if(!msgSend(c, &m, AQueue))
  471. goto Err;
  472. msgClear(&m);
  473. m.tag = HCertificate;
  474. numcerts = countchain(chp);
  475. m.u.certificate.ncert = 1 + numcerts;
  476. m.u.certificate.certs = emalloc(m.u.certificate.ncert * sizeof(Bytes));
  477. m.u.certificate.certs[0] = makebytes(cert, ncert);
  478. for (i = 0; i < numcerts && chp; i++, chp = chp->next)
  479. m.u.certificate.certs[i+1] = makebytes(chp->pem, chp->pemlen);
  480. if(!msgSend(c, &m, AQueue))
  481. goto Err;
  482. msgClear(&m);
  483. m.tag = HServerHelloDone;
  484. if(!msgSend(c, &m, AFlush))
  485. goto Err;
  486. msgClear(&m);
  487. if(!msgRecv(c, &m))
  488. goto Err;
  489. if(m.tag != HClientKeyExchange) {
  490. tlsError(c, EUnexpectedMessage, "expected a client key exchange");
  491. goto Err;
  492. }
  493. if(tlsSecSecrets(c->sec, c->version, m.u.clientKeyExchange.key->data, m.u.clientKeyExchange.key->len, kd, c->nsecret) < 0){
  494. tlsError(c, EHandshakeFailure, "couldn't set secrets: %r");
  495. goto Err;
  496. }
  497. if(trace)
  498. trace("tls secrets\n");
  499. secrets = (char*)emalloc(2*c->nsecret);
  500. enc64(secrets, 2*c->nsecret, kd, c->nsecret);
  501. rv = fprint(c->ctl, "secret %s %s 0 %s", c->digest, c->enc, secrets);
  502. memset(secrets, 0, 2*c->nsecret);
  503. free(secrets);
  504. memset(kd, 0, c->nsecret);
  505. if(rv < 0){
  506. tlsError(c, EHandshakeFailure, "can't set keys: %r");
  507. goto Err;
  508. }
  509. msgClear(&m);
  510. /* no CertificateVerify; skip to Finished */
  511. if(tlsSecFinished(c->sec, c->hsmd5, c->hssha1, c->finished.verify, c->finished.n, 1) < 0){
  512. tlsError(c, EInternalError, "can't set finished: %r");
  513. goto Err;
  514. }
  515. if(!msgRecv(c, &m))
  516. goto Err;
  517. if(m.tag != HFinished) {
  518. tlsError(c, EUnexpectedMessage, "expected a finished");
  519. goto Err;
  520. }
  521. if(!finishedMatch(c, &m.u.finished)) {
  522. tlsError(c, EHandshakeFailure, "finished verification failed");
  523. goto Err;
  524. }
  525. msgClear(&m);
  526. /* change cipher spec */
  527. if(fprint(c->ctl, "changecipher") < 0){
  528. tlsError(c, EInternalError, "can't enable cipher: %r");
  529. goto Err;
  530. }
  531. if(tlsSecFinished(c->sec, c->hsmd5, c->hssha1, c->finished.verify, c->finished.n, 0) < 0){
  532. tlsError(c, EInternalError, "can't set finished: %r");
  533. goto Err;
  534. }
  535. m.tag = HFinished;
  536. m.u.finished = c->finished;
  537. if(!msgSend(c, &m, AFlush))
  538. goto Err;
  539. msgClear(&m);
  540. if(trace)
  541. trace("tls finished\n");
  542. if(fprint(c->ctl, "opened") < 0)
  543. goto Err;
  544. tlsSecOk(c->sec);
  545. return c;
  546. Err:
  547. msgClear(&m);
  548. tlsConnectionFree(c);
  549. return 0;
  550. }
  551. static TlsConnection *
  552. tlsClient2(int ctl, int hand, uchar *csid, int ncsid, int (*trace)(char*fmt, ...))
  553. {
  554. TlsConnection *c;
  555. Msg m;
  556. uchar kd[MaxKeyData], *epm;
  557. char *secrets;
  558. int creq, nepm, rv;
  559. if(!initCiphers())
  560. return nil;
  561. epm = nil;
  562. c = emalloc(sizeof(TlsConnection));
  563. c->version = ProtocolVersion;
  564. c->ctl = ctl;
  565. c->hand = hand;
  566. c->trace = trace;
  567. c->isClient = 1;
  568. c->clientVersion = c->version;
  569. c->sec = tlsSecInitc(c->clientVersion, c->crandom);
  570. if(c->sec == nil)
  571. goto Err;
  572. /* client hello */
  573. memset(&m, 0, sizeof(m));
  574. m.tag = HClientHello;
  575. m.u.clientHello.version = c->clientVersion;
  576. memmove(m.u.clientHello.random, c->crandom, RandomSize);
  577. m.u.clientHello.sid = makebytes(csid, ncsid);
  578. m.u.clientHello.ciphers = makeciphers();
  579. m.u.clientHello.compressors = makebytes(compressors,sizeof(compressors));
  580. if(!msgSend(c, &m, AFlush))
  581. goto Err;
  582. msgClear(&m);
  583. /* server hello */
  584. if(!msgRecv(c, &m))
  585. goto Err;
  586. if(m.tag != HServerHello) {
  587. tlsError(c, EUnexpectedMessage, "expected a server hello");
  588. goto Err;
  589. }
  590. if(setVersion(c, m.u.serverHello.version) < 0) {
  591. tlsError(c, EIllegalParameter, "incompatible version %r");
  592. goto Err;
  593. }
  594. memmove(c->srandom, m.u.serverHello.random, RandomSize);
  595. c->sid = makebytes(m.u.serverHello.sid->data, m.u.serverHello.sid->len);
  596. if(c->sid->len != 0 && c->sid->len != SidSize) {
  597. tlsError(c, EIllegalParameter, "invalid server session identifier");
  598. goto Err;
  599. }
  600. if(!setAlgs(c, m.u.serverHello.cipher)) {
  601. tlsError(c, EIllegalParameter, "invalid cipher suite");
  602. goto Err;
  603. }
  604. if(m.u.serverHello.compressor != CompressionNull) {
  605. tlsError(c, EIllegalParameter, "invalid compression");
  606. goto Err;
  607. }
  608. msgClear(&m);
  609. /* certificate */
  610. if(!msgRecv(c, &m) || m.tag != HCertificate) {
  611. tlsError(c, EUnexpectedMessage, "expected a certificate");
  612. goto Err;
  613. }
  614. if(m.u.certificate.ncert < 1) {
  615. tlsError(c, EIllegalParameter, "runt certificate");
  616. goto Err;
  617. }
  618. c->cert = makebytes(m.u.certificate.certs[0]->data, m.u.certificate.certs[0]->len);
  619. msgClear(&m);
  620. /* server key exchange (optional) */
  621. if(!msgRecv(c, &m))
  622. goto Err;
  623. if(m.tag == HServerKeyExchange) {
  624. tlsError(c, EUnexpectedMessage, "got an server key exchange");
  625. goto Err;
  626. // If implementing this later, watch out for rollback attack
  627. // described in Wagner Schneier 1996, section 4.4.
  628. }
  629. /* certificate request (optional) */
  630. creq = 0;
  631. if(m.tag == HCertificateRequest) {
  632. creq = 1;
  633. msgClear(&m);
  634. if(!msgRecv(c, &m))
  635. goto Err;
  636. }
  637. if(m.tag != HServerHelloDone) {
  638. tlsError(c, EUnexpectedMessage, "expected a server hello done");
  639. goto Err;
  640. }
  641. msgClear(&m);
  642. if(tlsSecSecretc(c->sec, c->sid->data, c->sid->len, c->srandom,
  643. c->cert->data, c->cert->len, c->version, &epm, &nepm,
  644. kd, c->nsecret) < 0){
  645. tlsError(c, EBadCertificate, "invalid x509/rsa certificate");
  646. goto Err;
  647. }
  648. secrets = (char*)emalloc(2*c->nsecret);
  649. enc64(secrets, 2*c->nsecret, kd, c->nsecret);
  650. rv = fprint(c->ctl, "secret %s %s 1 %s", c->digest, c->enc, secrets);
  651. memset(secrets, 0, 2*c->nsecret);
  652. free(secrets);
  653. memset(kd, 0, c->nsecret);
  654. if(rv < 0){
  655. tlsError(c, EHandshakeFailure, "can't set keys: %r");
  656. goto Err;
  657. }
  658. if(creq) {
  659. /* send a zero length certificate */
  660. m.tag = HCertificate;
  661. if(!msgSend(c, &m, AFlush))
  662. goto Err;
  663. msgClear(&m);
  664. }
  665. /* client key exchange */
  666. m.tag = HClientKeyExchange;
  667. m.u.clientKeyExchange.key = makebytes(epm, nepm);
  668. free(epm);
  669. epm = nil;
  670. if(m.u.clientKeyExchange.key == nil) {
  671. tlsError(c, EHandshakeFailure, "can't set secret: %r");
  672. goto Err;
  673. }
  674. if(!msgSend(c, &m, AFlush))
  675. goto Err;
  676. msgClear(&m);
  677. /* change cipher spec */
  678. if(fprint(c->ctl, "changecipher") < 0){
  679. tlsError(c, EInternalError, "can't enable cipher: %r");
  680. goto Err;
  681. }
  682. // Cipherchange must occur immediately before Finished to avoid
  683. // potential hole; see section 4.3 of Wagner Schneier 1996.
  684. if(tlsSecFinished(c->sec, c->hsmd5, c->hssha1, c->finished.verify, c->finished.n, 1) < 0){
  685. tlsError(c, EInternalError, "can't set finished 1: %r");
  686. goto Err;
  687. }
  688. m.tag = HFinished;
  689. m.u.finished = c->finished;
  690. if(!msgSend(c, &m, AFlush)) {
  691. fprint(2, "tlsClient nepm=%d\n", nepm);
  692. tlsError(c, EInternalError, "can't flush after client Finished: %r");
  693. goto Err;
  694. }
  695. msgClear(&m);
  696. if(tlsSecFinished(c->sec, c->hsmd5, c->hssha1, c->finished.verify, c->finished.n, 0) < 0){
  697. fprint(2, "tlsClient nepm=%d\n", nepm);
  698. tlsError(c, EInternalError, "can't set finished 0: %r");
  699. goto Err;
  700. }
  701. if(!msgRecv(c, &m)) {
  702. fprint(2, "tlsClient nepm=%d\n", nepm);
  703. tlsError(c, EInternalError, "can't read server Finished: %r");
  704. goto Err;
  705. }
  706. if(m.tag != HFinished) {
  707. fprint(2, "tlsClient nepm=%d\n", nepm);
  708. tlsError(c, EUnexpectedMessage, "expected a Finished msg from server");
  709. goto Err;
  710. }
  711. if(!finishedMatch(c, &m.u.finished)) {
  712. tlsError(c, EHandshakeFailure, "finished verification failed");
  713. goto Err;
  714. }
  715. msgClear(&m);
  716. if(fprint(c->ctl, "opened") < 0){
  717. if(trace)
  718. trace("unable to do final open: %r\n");
  719. goto Err;
  720. }
  721. tlsSecOk(c->sec);
  722. return c;
  723. Err:
  724. free(epm);
  725. msgClear(&m);
  726. tlsConnectionFree(c);
  727. return 0;
  728. }
  729. //================= message functions ========================
  730. static uchar sendbuf[9000], *sendp;
  731. static int
  732. msgSend(TlsConnection *c, Msg *m, int act)
  733. {
  734. uchar *p; // sendp = start of new message; p = write pointer
  735. int nn, n, i;
  736. if(sendp == nil)
  737. sendp = sendbuf;
  738. p = sendp;
  739. if(c->trace)
  740. c->trace("send %s", msgPrint((char*)p, (sizeof sendbuf) - (p-sendbuf), m));
  741. p[0] = m->tag; // header - fill in size later
  742. p += 4;
  743. switch(m->tag) {
  744. default:
  745. tlsError(c, EInternalError, "can't encode a %d", m->tag);
  746. goto Err;
  747. case HClientHello:
  748. // version
  749. put16(p, m->u.clientHello.version);
  750. p += 2;
  751. // random
  752. memmove(p, m->u.clientHello.random, RandomSize);
  753. p += RandomSize;
  754. // sid
  755. n = m->u.clientHello.sid->len;
  756. assert(n < 256);
  757. p[0] = n;
  758. memmove(p+1, m->u.clientHello.sid->data, n);
  759. p += n+1;
  760. n = m->u.clientHello.ciphers->len;
  761. assert(n > 0 && n < 200);
  762. put16(p, n*2);
  763. p += 2;
  764. for(i=0; i<n; i++) {
  765. put16(p, m->u.clientHello.ciphers->data[i]);
  766. p += 2;
  767. }
  768. n = m->u.clientHello.compressors->len;
  769. assert(n > 0);
  770. p[0] = n;
  771. memmove(p+1, m->u.clientHello.compressors->data, n);
  772. p += n+1;
  773. break;
  774. case HServerHello:
  775. put16(p, m->u.serverHello.version);
  776. p += 2;
  777. // random
  778. memmove(p, m->u.serverHello.random, RandomSize);
  779. p += RandomSize;
  780. // sid
  781. n = m->u.serverHello.sid->len;
  782. assert(n < 256);
  783. p[0] = n;
  784. memmove(p+1, m->u.serverHello.sid->data, n);
  785. p += n+1;
  786. put16(p, m->u.serverHello.cipher);
  787. p += 2;
  788. p[0] = m->u.serverHello.compressor;
  789. p += 1;
  790. break;
  791. case HServerHelloDone:
  792. break;
  793. case HCertificate:
  794. nn = 0;
  795. for(i = 0; i < m->u.certificate.ncert; i++)
  796. nn += 3 + m->u.certificate.certs[i]->len;
  797. if(p + 3 + nn - sendbuf > sizeof(sendbuf)) {
  798. tlsError(c, EInternalError, "output buffer too small for certificate");
  799. goto Err;
  800. }
  801. put24(p, nn);
  802. p += 3;
  803. for(i = 0; i < m->u.certificate.ncert; i++){
  804. put24(p, m->u.certificate.certs[i]->len);
  805. p += 3;
  806. memmove(p, m->u.certificate.certs[i]->data, m->u.certificate.certs[i]->len);
  807. p += m->u.certificate.certs[i]->len;
  808. }
  809. break;
  810. case HClientKeyExchange:
  811. n = m->u.clientKeyExchange.key->len;
  812. if(c->version != SSL3Version){
  813. put16(p, n);
  814. p += 2;
  815. }
  816. memmove(p, m->u.clientKeyExchange.key->data, n);
  817. p += n;
  818. break;
  819. case HFinished:
  820. memmove(p, m->u.finished.verify, m->u.finished.n);
  821. p += m->u.finished.n;
  822. break;
  823. }
  824. // go back and fill in size
  825. n = p-sendp;
  826. assert(p <= sendbuf+sizeof(sendbuf));
  827. put24(sendp+1, n-4);
  828. // remember hash of Handshake messages
  829. if(m->tag != HHelloRequest) {
  830. md5(sendp, n, 0, &c->hsmd5);
  831. sha1(sendp, n, 0, &c->hssha1);
  832. }
  833. sendp = p;
  834. if(act == AFlush){
  835. sendp = sendbuf;
  836. if(write(c->hand, sendbuf, p-sendbuf) < 0){
  837. fprint(2, "write error: %r\n");
  838. goto Err;
  839. }
  840. }
  841. msgClear(m);
  842. return 1;
  843. Err:
  844. msgClear(m);
  845. return 0;
  846. }
  847. static uchar*
  848. tlsReadN(TlsConnection *c, int n)
  849. {
  850. uchar *p;
  851. int nn, nr;
  852. nn = c->ep - c->rp;
  853. if(nn < n){
  854. if(c->rp != c->buf){
  855. memmove(c->buf, c->rp, nn);
  856. c->rp = c->buf;
  857. c->ep = &c->buf[nn];
  858. }
  859. for(; nn < n; nn += nr) {
  860. nr = read(c->hand, &c->rp[nn], n - nn);
  861. if(nr <= 0)
  862. return nil;
  863. c->ep += nr;
  864. }
  865. }
  866. p = c->rp;
  867. c->rp += n;
  868. return p;
  869. }
  870. static int
  871. msgRecv(TlsConnection *c, Msg *m)
  872. {
  873. uchar *p;
  874. int type, n, nn, i, nsid, nrandom, nciph;
  875. for(;;) {
  876. p = tlsReadN(c, 4);
  877. if(p == nil)
  878. return 0;
  879. type = p[0];
  880. n = get24(p+1);
  881. if(type != HHelloRequest)
  882. break;
  883. if(n != 0) {
  884. tlsError(c, EDecodeError, "invalid hello request during handshake");
  885. return 0;
  886. }
  887. }
  888. if(n > sizeof(c->buf)) {
  889. tlsError(c, EDecodeError, "handshake message too long %d %d", n, sizeof(c->buf));
  890. return 0;
  891. }
  892. if(type == HSSL2ClientHello){
  893. /* Cope with an SSL3 ClientHello expressed in SSL2 record format.
  894. This is sent by some clients that we must interoperate
  895. with, such as Java's JSSE and Microsoft's Internet Explorer. */
  896. p = tlsReadN(c, n);
  897. if(p == nil)
  898. return 0;
  899. md5(p, n, 0, &c->hsmd5);
  900. sha1(p, n, 0, &c->hssha1);
  901. m->tag = HClientHello;
  902. if(n < 22)
  903. goto Short;
  904. m->u.clientHello.version = get16(p+1);
  905. p += 3;
  906. n -= 3;
  907. nn = get16(p); /* cipher_spec_len */
  908. nsid = get16(p + 2);
  909. nrandom = get16(p + 4);
  910. p += 6;
  911. n -= 6;
  912. if(nsid != 0 /* no sid's, since shouldn't restart using ssl2 header */
  913. || nrandom < 16 || nn % 3)
  914. goto Err;
  915. if(c->trace && (n - nrandom != nn))
  916. c->trace("n-nrandom!=nn: n=%d nrandom=%d nn=%d\n", n, nrandom, nn);
  917. /* ignore ssl2 ciphers and look for {0x00, ssl3 cipher} */
  918. nciph = 0;
  919. for(i = 0; i < nn; i += 3)
  920. if(p[i] == 0)
  921. nciph++;
  922. m->u.clientHello.ciphers = newints(nciph);
  923. nciph = 0;
  924. for(i = 0; i < nn; i += 3)
  925. if(p[i] == 0)
  926. m->u.clientHello.ciphers->data[nciph++] = get16(&p[i + 1]);
  927. p += nn;
  928. m->u.clientHello.sid = makebytes(nil, 0);
  929. if(nrandom > RandomSize)
  930. nrandom = RandomSize;
  931. memset(m->u.clientHello.random, 0, RandomSize - nrandom);
  932. memmove(&m->u.clientHello.random[RandomSize - nrandom], p, nrandom);
  933. m->u.clientHello.compressors = newbytes(1);
  934. m->u.clientHello.compressors->data[0] = CompressionNull;
  935. goto Ok;
  936. }
  937. md5(p, 4, 0, &c->hsmd5);
  938. sha1(p, 4, 0, &c->hssha1);
  939. p = tlsReadN(c, n);
  940. if(p == nil)
  941. return 0;
  942. md5(p, n, 0, &c->hsmd5);
  943. sha1(p, n, 0, &c->hssha1);
  944. m->tag = type;
  945. switch(type) {
  946. default:
  947. tlsError(c, EUnexpectedMessage, "can't decode a %d", type);
  948. goto Err;
  949. case HClientHello:
  950. if(n < 2)
  951. goto Short;
  952. m->u.clientHello.version = get16(p);
  953. p += 2;
  954. n -= 2;
  955. if(n < RandomSize)
  956. goto Short;
  957. memmove(m->u.clientHello.random, p, RandomSize);
  958. p += RandomSize;
  959. n -= RandomSize;
  960. if(n < 1 || n < p[0]+1)
  961. goto Short;
  962. m->u.clientHello.sid = makebytes(p+1, p[0]);
  963. p += m->u.clientHello.sid->len+1;
  964. n -= m->u.clientHello.sid->len+1;
  965. if(n < 2)
  966. goto Short;
  967. nn = get16(p);
  968. p += 2;
  969. n -= 2;
  970. if((nn & 1) || n < nn || nn < 2)
  971. goto Short;
  972. m->u.clientHello.ciphers = newints(nn >> 1);
  973. for(i = 0; i < nn; i += 2)
  974. m->u.clientHello.ciphers->data[i >> 1] = get16(&p[i]);
  975. p += nn;
  976. n -= nn;
  977. if(n < 1 || n < p[0]+1 || p[0] == 0)
  978. goto Short;
  979. nn = p[0];
  980. m->u.clientHello.compressors = newbytes(nn);
  981. memmove(m->u.clientHello.compressors->data, p+1, nn);
  982. n -= nn + 1;
  983. break;
  984. case HServerHello:
  985. if(n < 2)
  986. goto Short;
  987. m->u.serverHello.version = get16(p);
  988. p += 2;
  989. n -= 2;
  990. if(n < RandomSize)
  991. goto Short;
  992. memmove(m->u.serverHello.random, p, RandomSize);
  993. p += RandomSize;
  994. n -= RandomSize;
  995. if(n < 1 || n < p[0]+1)
  996. goto Short;
  997. m->u.serverHello.sid = makebytes(p+1, p[0]);
  998. p += m->u.serverHello.sid->len+1;
  999. n -= m->u.serverHello.sid->len+1;
  1000. if(n < 3)
  1001. goto Short;
  1002. m->u.serverHello.cipher = get16(p);
  1003. m->u.serverHello.compressor = p[2];
  1004. n -= 3;
  1005. break;
  1006. case HCertificate:
  1007. if(n < 3)
  1008. goto Short;
  1009. nn = get24(p);
  1010. p += 3;
  1011. n -= 3;
  1012. if(n != nn)
  1013. goto Short;
  1014. /* certs */
  1015. i = 0;
  1016. while(n > 0) {
  1017. if(n < 3)
  1018. goto Short;
  1019. nn = get24(p);
  1020. p += 3;
  1021. n -= 3;
  1022. if(nn > n)
  1023. goto Short;
  1024. m->u.certificate.ncert = i+1;
  1025. m->u.certificate.certs = erealloc(m->u.certificate.certs, (i+1)*sizeof(Bytes));
  1026. m->u.certificate.certs[i] = makebytes(p, nn);
  1027. p += nn;
  1028. n -= nn;
  1029. i++;
  1030. }
  1031. break;
  1032. case HCertificateRequest:
  1033. if(n < 1)
  1034. goto Short;
  1035. nn = p[0];
  1036. p += 1;
  1037. n -= 1;
  1038. if(nn < 1 || nn > n)
  1039. goto Short;
  1040. m->u.certificateRequest.types = makebytes(p, nn);
  1041. p += nn;
  1042. n -= nn;
  1043. if(n < 2)
  1044. goto Short;
  1045. nn = get16(p);
  1046. p += 2;
  1047. n -= 2;
  1048. if(nn == 0 || n != nn)
  1049. goto Short;
  1050. /* cas */
  1051. i = 0;
  1052. while(n > 0) {
  1053. if(n < 2)
  1054. goto Short;
  1055. nn = get16(p);
  1056. p += 2;
  1057. n -= 2;
  1058. if(nn < 1 || nn > n)
  1059. goto Short;
  1060. m->u.certificateRequest.nca = i+1;
  1061. m->u.certificateRequest.cas = erealloc(m->u.certificateRequest.cas, (i+1)*sizeof(Bytes));
  1062. m->u.certificateRequest.cas[i] = makebytes(p, nn);
  1063. p += nn;
  1064. n -= nn;
  1065. i++;
  1066. }
  1067. break;
  1068. case HServerHelloDone:
  1069. break;
  1070. case HClientKeyExchange:
  1071. /*
  1072. * this message depends upon the encryption selected
  1073. * assume rsa.
  1074. */
  1075. if(c->version == SSL3Version)
  1076. nn = n;
  1077. else{
  1078. if(n < 2)
  1079. goto Short;
  1080. nn = get16(p);
  1081. p += 2;
  1082. n -= 2;
  1083. }
  1084. if(n < nn)
  1085. goto Short;
  1086. m->u.clientKeyExchange.key = makebytes(p, nn);
  1087. n -= nn;
  1088. break;
  1089. case HFinished:
  1090. m->u.finished.n = c->finished.n;
  1091. if(n < m->u.finished.n)
  1092. goto Short;
  1093. memmove(m->u.finished.verify, p, m->u.finished.n);
  1094. n -= m->u.finished.n;
  1095. break;
  1096. }
  1097. if(type != HClientHello && n != 0)
  1098. goto Short;
  1099. Ok:
  1100. if(c->trace){
  1101. char *buf;
  1102. buf = emalloc(8000);
  1103. c->trace("recv %s", msgPrint(buf, 8000, m));
  1104. free(buf);
  1105. }
  1106. return 1;
  1107. Short:
  1108. tlsError(c, EDecodeError, "handshake message has invalid length");
  1109. Err:
  1110. msgClear(m);
  1111. return 0;
  1112. }
  1113. static void
  1114. msgClear(Msg *m)
  1115. {
  1116. int i;
  1117. switch(m->tag) {
  1118. default:
  1119. sysfatal("msgClear: unknown message type: %d\n", m->tag);
  1120. case HHelloRequest:
  1121. break;
  1122. case HClientHello:
  1123. freebytes(m->u.clientHello.sid);
  1124. freeints(m->u.clientHello.ciphers);
  1125. freebytes(m->u.clientHello.compressors);
  1126. break;
  1127. case HServerHello:
  1128. freebytes(m->u.clientHello.sid);
  1129. break;
  1130. case HCertificate:
  1131. for(i=0; i<m->u.certificate.ncert; i++)
  1132. freebytes(m->u.certificate.certs[i]);
  1133. free(m->u.certificate.certs);
  1134. break;
  1135. case HCertificateRequest:
  1136. freebytes(m->u.certificateRequest.types);
  1137. for(i=0; i<m->u.certificateRequest.nca; i++)
  1138. freebytes(m->u.certificateRequest.cas[i]);
  1139. free(m->u.certificateRequest.cas);
  1140. break;
  1141. case HServerHelloDone:
  1142. break;
  1143. case HClientKeyExchange:
  1144. freebytes(m->u.clientKeyExchange.key);
  1145. break;
  1146. case HFinished:
  1147. break;
  1148. }
  1149. memset(m, 0, sizeof(Msg));
  1150. }
  1151. static char *
  1152. bytesPrint(char *bs, char *be, char *s0, Bytes *b, char *s1)
  1153. {
  1154. int i;
  1155. if(s0)
  1156. bs = seprint(bs, be, "%s", s0);
  1157. bs = seprint(bs, be, "[");
  1158. if(b == nil)
  1159. bs = seprint(bs, be, "nil");
  1160. else
  1161. for(i=0; i<b->len; i++)
  1162. bs = seprint(bs, be, "%.2x ", b->data[i]);
  1163. bs = seprint(bs, be, "]");
  1164. if(s1)
  1165. bs = seprint(bs, be, "%s", s1);
  1166. return bs;
  1167. }
  1168. static char *
  1169. intsPrint(char *bs, char *be, char *s0, Ints *b, char *s1)
  1170. {
  1171. int i;
  1172. if(s0)
  1173. bs = seprint(bs, be, "%s", s0);
  1174. bs = seprint(bs, be, "[");
  1175. if(b == nil)
  1176. bs = seprint(bs, be, "nil");
  1177. else
  1178. for(i=0; i<b->len; i++)
  1179. bs = seprint(bs, be, "%x ", b->data[i]);
  1180. bs = seprint(bs, be, "]");
  1181. if(s1)
  1182. bs = seprint(bs, be, "%s", s1);
  1183. return bs;
  1184. }
  1185. static char*
  1186. msgPrint(char *buf, int n, Msg *m)
  1187. {
  1188. int i;
  1189. char *bs = buf, *be = buf+n;
  1190. switch(m->tag) {
  1191. default:
  1192. bs = seprint(bs, be, "unknown %d\n", m->tag);
  1193. break;
  1194. case HClientHello:
  1195. bs = seprint(bs, be, "ClientHello\n");
  1196. bs = seprint(bs, be, "\tversion: %.4x\n", m->u.clientHello.version);
  1197. bs = seprint(bs, be, "\trandom: ");
  1198. for(i=0; i<RandomSize; i++)
  1199. bs = seprint(bs, be, "%.2x", m->u.clientHello.random[i]);
  1200. bs = seprint(bs, be, "\n");
  1201. bs = bytesPrint(bs, be, "\tsid: ", m->u.clientHello.sid, "\n");
  1202. bs = intsPrint(bs, be, "\tciphers: ", m->u.clientHello.ciphers, "\n");
  1203. bs = bytesPrint(bs, be, "\tcompressors: ", m->u.clientHello.compressors, "\n");
  1204. break;
  1205. case HServerHello:
  1206. bs = seprint(bs, be, "ServerHello\n");
  1207. bs = seprint(bs, be, "\tversion: %.4x\n", m->u.serverHello.version);
  1208. bs = seprint(bs, be, "\trandom: ");
  1209. for(i=0; i<RandomSize; i++)
  1210. bs = seprint(bs, be, "%.2x", m->u.serverHello.random[i]);
  1211. bs = seprint(bs, be, "\n");
  1212. bs = bytesPrint(bs, be, "\tsid: ", m->u.serverHello.sid, "\n");
  1213. bs = seprint(bs, be, "\tcipher: %.4x\n", m->u.serverHello.cipher);
  1214. bs = seprint(bs, be, "\tcompressor: %.2x\n", m->u.serverHello.compressor);
  1215. break;
  1216. case HCertificate:
  1217. bs = seprint(bs, be, "Certificate\n");
  1218. for(i=0; i<m->u.certificate.ncert; i++)
  1219. bs = bytesPrint(bs, be, "\t", m->u.certificate.certs[i], "\n");
  1220. break;
  1221. case HCertificateRequest:
  1222. bs = seprint(bs, be, "CertificateRequest\n");
  1223. bs = bytesPrint(bs, be, "\ttypes: ", m->u.certificateRequest.types, "\n");
  1224. bs = seprint(bs, be, "\tcertificateauthorities\n");
  1225. for(i=0; i<m->u.certificateRequest.nca; i++)
  1226. bs = bytesPrint(bs, be, "\t\t", m->u.certificateRequest.cas[i], "\n");
  1227. break;
  1228. case HServerHelloDone:
  1229. bs = seprint(bs, be, "ServerHelloDone\n");
  1230. break;
  1231. case HClientKeyExchange:
  1232. bs = seprint(bs, be, "HClientKeyExchange\n");
  1233. bs = bytesPrint(bs, be, "\tkey: ", m->u.clientKeyExchange.key, "\n");
  1234. break;
  1235. case HFinished:
  1236. bs = seprint(bs, be, "HFinished\n");
  1237. for(i=0; i<m->u.finished.n; i++)
  1238. bs = seprint(bs, be, "%.2x", m->u.finished.verify[i]);
  1239. bs = seprint(bs, be, "\n");
  1240. break;
  1241. }
  1242. USED(bs);
  1243. return buf;
  1244. }
  1245. static void
  1246. tlsError(TlsConnection *c, int err, char *fmt, ...)
  1247. {
  1248. char msg[512];
  1249. va_list arg;
  1250. va_start(arg, fmt);
  1251. vseprint(msg, msg+sizeof(msg), fmt, arg);
  1252. va_end(arg);
  1253. if(c->trace)
  1254. c->trace("tlsError: %s\n", msg);
  1255. else if(c->erred)
  1256. fprint(2, "double error: %r, %s", msg);
  1257. else
  1258. werrstr("tls: local %s", msg);
  1259. c->erred = 1;
  1260. fprint(c->ctl, "alert %d", err);
  1261. }
  1262. // commit to specific version number
  1263. static int
  1264. setVersion(TlsConnection *c, int version)
  1265. {
  1266. if(c->verset || version > MaxProtoVersion || version < MinProtoVersion)
  1267. return -1;
  1268. if(version > c->version)
  1269. version = c->version;
  1270. if(version == SSL3Version) {
  1271. c->version = version;
  1272. c->finished.n = SSL3FinishedLen;
  1273. }else if(version == TLSVersion){
  1274. c->version = version;
  1275. c->finished.n = TLSFinishedLen;
  1276. }else
  1277. return -1;
  1278. c->verset = 1;
  1279. return fprint(c->ctl, "version 0x%x", version);
  1280. }
  1281. // confirm that received Finished message matches the expected value
  1282. static int
  1283. finishedMatch(TlsConnection *c, Finished *f)
  1284. {
  1285. return memcmp(f->verify, c->finished.verify, f->n) == 0;
  1286. }
  1287. // free memory associated with TlsConnection struct
  1288. // (but don't close the TLS channel itself)
  1289. static void
  1290. tlsConnectionFree(TlsConnection *c)
  1291. {
  1292. tlsSecClose(c->sec);
  1293. freebytes(c->sid);
  1294. freebytes(c->cert);
  1295. memset(c, 0, sizeof(c));
  1296. free(c);
  1297. }
  1298. //================= cipher choices ========================
  1299. static int weakCipher[CipherMax] =
  1300. {
  1301. 1, /* TLS_NULL_WITH_NULL_NULL */
  1302. 1, /* TLS_RSA_WITH_NULL_MD5 */
  1303. 1, /* TLS_RSA_WITH_NULL_SHA */
  1304. 1, /* TLS_RSA_EXPORT_WITH_RC4_40_MD5 */
  1305. 0, /* TLS_RSA_WITH_RC4_128_MD5 */
  1306. 0, /* TLS_RSA_WITH_RC4_128_SHA */
  1307. 1, /* TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 */
  1308. 0, /* TLS_RSA_WITH_IDEA_CBC_SHA */
  1309. 1, /* TLS_RSA_EXPORT_WITH_DES40_CBC_SHA */
  1310. 0, /* TLS_RSA_WITH_DES_CBC_SHA */
  1311. 0, /* TLS_RSA_WITH_3DES_EDE_CBC_SHA */
  1312. 1, /* TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA */
  1313. 0, /* TLS_DH_DSS_WITH_DES_CBC_SHA */
  1314. 0, /* TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA */
  1315. 1, /* TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA */
  1316. 0, /* TLS_DH_RSA_WITH_DES_CBC_SHA */
  1317. 0, /* TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA */
  1318. 1, /* TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA */
  1319. 0, /* TLS_DHE_DSS_WITH_DES_CBC_SHA */
  1320. 0, /* TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA */
  1321. 1, /* TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA */
  1322. 0, /* TLS_DHE_RSA_WITH_DES_CBC_SHA */
  1323. 0, /* TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA */
  1324. 1, /* TLS_DH_anon_EXPORT_WITH_RC4_40_MD5 */
  1325. 1, /* TLS_DH_anon_WITH_RC4_128_MD5 */
  1326. 1, /* TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA */
  1327. 1, /* TLS_DH_anon_WITH_DES_CBC_SHA */
  1328. 1, /* TLS_DH_anon_WITH_3DES_EDE_CBC_SHA */
  1329. };
  1330. static int
  1331. setAlgs(TlsConnection *c, int a)
  1332. {
  1333. int i;
  1334. for(i = 0; i < nelem(cipherAlgs); i++){
  1335. if(cipherAlgs[i].tlsid == a){
  1336. c->enc = cipherAlgs[i].enc;
  1337. c->digest = cipherAlgs[i].digest;
  1338. c->nsecret = cipherAlgs[i].nsecret;
  1339. if(c->nsecret > MaxKeyData)
  1340. return 0;
  1341. return 1;
  1342. }
  1343. }
  1344. return 0;
  1345. }
  1346. static int
  1347. okCipher(Ints *cv)
  1348. {
  1349. int weak, i, j, c;
  1350. weak = 1;
  1351. for(i = 0; i < cv->len; i++) {
  1352. c = cv->data[i];
  1353. if(c >= CipherMax)
  1354. weak = 0;
  1355. else
  1356. weak &= weakCipher[c];
  1357. for(j = 0; j < nelem(cipherAlgs); j++)
  1358. if(cipherAlgs[j].ok && cipherAlgs[j].tlsid == c)
  1359. return c;
  1360. }
  1361. if(weak)
  1362. return -2;
  1363. return -1;
  1364. }
  1365. static int
  1366. okCompression(Bytes *cv)
  1367. {
  1368. int i, j, c;
  1369. for(i = 0; i < cv->len; i++) {
  1370. c = cv->data[i];
  1371. for(j = 0; j < nelem(compressors); j++) {
  1372. if(compressors[j] == c)
  1373. return c;
  1374. }
  1375. }
  1376. return -1;
  1377. }
  1378. static Lock ciphLock;
  1379. static int nciphers;
  1380. static int
  1381. initCiphers(void)
  1382. {
  1383. enum {MaxAlgF = 1024, MaxAlgs = 10};
  1384. char s[MaxAlgF], *flds[MaxAlgs];
  1385. int i, j, n, ok;
  1386. lock(&ciphLock);
  1387. if(nciphers){
  1388. unlock(&ciphLock);
  1389. return nciphers;
  1390. }
  1391. j = open("#a/tls/encalgs", OREAD);
  1392. if(j < 0){
  1393. werrstr("can't open #a/tls/encalgs: %r");
  1394. return 0;
  1395. }
  1396. n = read(j, s, MaxAlgF-1);
  1397. close(j);
  1398. if(n <= 0){
  1399. werrstr("nothing in #a/tls/encalgs: %r");
  1400. return 0;
  1401. }
  1402. s[n] = 0;
  1403. n = getfields(s, flds, MaxAlgs, 1, " \t\r\n");
  1404. for(i = 0; i < nelem(cipherAlgs); i++){
  1405. ok = 0;
  1406. for(j = 0; j < n; j++){
  1407. if(strcmp(cipherAlgs[i].enc, flds[j]) == 0){
  1408. ok = 1;
  1409. break;
  1410. }
  1411. }
  1412. cipherAlgs[i].ok = ok;
  1413. }
  1414. j = open("#a/tls/hashalgs", OREAD);
  1415. if(j < 0){
  1416. werrstr("can't open #a/tls/hashalgs: %r");
  1417. return 0;
  1418. }
  1419. n = read(j, s, MaxAlgF-1);
  1420. close(j);
  1421. if(n <= 0){
  1422. werrstr("nothing in #a/tls/hashalgs: %r");
  1423. return 0;
  1424. }
  1425. s[n] = 0;
  1426. n = getfields(s, flds, MaxAlgs, 1, " \t\r\n");
  1427. for(i = 0; i < nelem(cipherAlgs); i++){
  1428. ok = 0;
  1429. for(j = 0; j < n; j++){
  1430. if(strcmp(cipherAlgs[i].digest, flds[j]) == 0){
  1431. ok = 1;
  1432. break;
  1433. }
  1434. }
  1435. cipherAlgs[i].ok &= ok;
  1436. if(cipherAlgs[i].ok)
  1437. nciphers++;
  1438. }
  1439. unlock(&ciphLock);
  1440. return nciphers;
  1441. }
  1442. static Ints*
  1443. makeciphers(void)
  1444. {
  1445. Ints *is;
  1446. int i, j;
  1447. is = newints(nciphers);
  1448. j = 0;
  1449. for(i = 0; i < nelem(cipherAlgs); i++){
  1450. if(cipherAlgs[i].ok)
  1451. is->data[j++] = cipherAlgs[i].tlsid;
  1452. }
  1453. return is;
  1454. }
  1455. //================= security functions ========================
  1456. // given X.509 certificate, set up connection to factotum
  1457. // for using corresponding private key
  1458. static AuthRpc*
  1459. factotum_rsa_open(uchar *cert, int certlen)
  1460. {
  1461. int afd;
  1462. char *s;
  1463. mpint *pub = nil;
  1464. RSApub *rsapub;
  1465. AuthRpc *rpc;
  1466. // start talking to factotum
  1467. if((afd = open("/mnt/factotum/rpc", ORDWR)) < 0)
  1468. return nil;
  1469. if((rpc = auth_allocrpc(afd)) == nil){
  1470. close(afd);
  1471. return nil;
  1472. }
  1473. s = "proto=rsa service=tls role=client";
  1474. if(auth_rpc(rpc, "start", s, strlen(s)) != ARok){
  1475. factotum_rsa_close(rpc);
  1476. return nil;
  1477. }
  1478. // roll factotum keyring around to match certificate
  1479. rsapub = X509toRSApub(cert, certlen, nil, 0);
  1480. while(1){
  1481. if(auth_rpc(rpc, "read", nil, 0) != ARok){
  1482. factotum_rsa_close(rpc);
  1483. rpc = nil;
  1484. goto done;
  1485. }
  1486. pub = strtomp(rpc->arg, nil, 16, nil);
  1487. assert(pub != nil);
  1488. if(mpcmp(pub,rsapub->n) == 0)
  1489. break;
  1490. }
  1491. done:
  1492. mpfree(pub);
  1493. rsapubfree(rsapub);
  1494. return rpc;
  1495. }
  1496. static mpint*
  1497. factotum_rsa_decrypt(AuthRpc *rpc, mpint *cipher)
  1498. {
  1499. char *p;
  1500. int rv;
  1501. if((p = mptoa(cipher, 16, nil, 0)) == nil)
  1502. return nil;
  1503. rv = auth_rpc(rpc, "write", p, strlen(p));
  1504. free(p);
  1505. if(rv != ARok || auth_rpc(rpc, "read", nil, 0) != ARok)
  1506. return nil;
  1507. mpfree(cipher);
  1508. return strtomp(rpc->arg, nil, 16, nil);
  1509. }
  1510. static void
  1511. factotum_rsa_close(AuthRpc*rpc)
  1512. {
  1513. if(!rpc)
  1514. return;
  1515. close(rpc->afd);
  1516. auth_freerpc(rpc);
  1517. }
  1518. static void
  1519. tlsPmd5(uchar *buf, int nbuf, uchar *key, int nkey, uchar *label, int nlabel, uchar *seed0, int nseed0, uchar *seed1, int nseed1)
  1520. {
  1521. uchar ai[MD5dlen], tmp[MD5dlen];
  1522. int i, n;
  1523. MD5state *s;
  1524. // generate a1
  1525. s = hmac_md5(label, nlabel, key, nkey, nil, nil);
  1526. s = hmac_md5(seed0, nseed0, key, nkey, nil, s);
  1527. hmac_md5(seed1, nseed1, key, nkey, ai, s);
  1528. while(nbuf > 0) {
  1529. s = hmac_md5(ai, MD5dlen, key, nkey, nil, nil);
  1530. s = hmac_md5(label, nlabel, key, nkey, nil, s);
  1531. s = hmac_md5(seed0, nseed0, key, nkey, nil, s);
  1532. hmac_md5(seed1, nseed1, key, nkey, tmp, s);
  1533. n = MD5dlen;
  1534. if(n > nbuf)
  1535. n = nbuf;
  1536. for(i = 0; i < n; i++)
  1537. buf[i] ^= tmp[i];
  1538. buf += n;
  1539. nbuf -= n;
  1540. hmac_md5(ai, MD5dlen, key, nkey, tmp, nil);
  1541. memmove(ai, tmp, MD5dlen);
  1542. }
  1543. }
  1544. static void
  1545. tlsPsha1(uchar *buf, int nbuf, uchar *key, int nkey, uchar *label, int nlabel, uchar *seed0, int nseed0, uchar *seed1, int nseed1)
  1546. {
  1547. uchar ai[SHA1dlen], tmp[SHA1dlen];
  1548. int i, n;
  1549. SHAstate *s;
  1550. // generate a1
  1551. s = hmac_sha1(label, nlabel, key, nkey, nil, nil);
  1552. s = hmac_sha1(seed0, nseed0, key, nkey, nil, s);
  1553. hmac_sha1(seed1, nseed1, key, nkey, ai, s);
  1554. while(nbuf > 0) {
  1555. s = hmac_sha1(ai, SHA1dlen, key, nkey, nil, nil);
  1556. s = hmac_sha1(label, nlabel, key, nkey, nil, s);
  1557. s = hmac_sha1(seed0, nseed0, key, nkey, nil, s);
  1558. hmac_sha1(seed1, nseed1, key, nkey, tmp, s);
  1559. n = SHA1dlen;
  1560. if(n > nbuf)
  1561. n = nbuf;
  1562. for(i = 0; i < n; i++)
  1563. buf[i] ^= tmp[i];
  1564. buf += n;
  1565. nbuf -= n;
  1566. hmac_sha1(ai, SHA1dlen, key, nkey, tmp, nil);
  1567. memmove(ai, tmp, SHA1dlen);
  1568. }
  1569. }
  1570. // fill buf with md5(args)^sha1(args)
  1571. static void
  1572. tlsPRF(uchar *buf, int nbuf, uchar *key, int nkey, char *label, uchar *seed0, int nseed0, uchar *seed1, int nseed1)
  1573. {
  1574. int i;
  1575. int nlabel = strlen(label);
  1576. int n = (nkey + 1) >> 1;
  1577. for(i = 0; i < nbuf; i++)
  1578. buf[i] = 0;
  1579. tlsPmd5(buf, nbuf, key, n, (uchar*)label, nlabel, seed0, nseed0, seed1, nseed1);
  1580. tlsPsha1(buf, nbuf, key+nkey-n, n, (uchar*)label, nlabel, seed0, nseed0, seed1, nseed1);
  1581. }
  1582. /*
  1583. * for setting server session id's
  1584. */
  1585. static Lock sidLock;
  1586. static long maxSid = 1;
  1587. /* the keys are verified to have the same public components
  1588. * and to function correctly with pkcs 1 encryption and decryption. */
  1589. static TlsSec*
  1590. tlsSecInits(int cvers, uchar *csid, int ncsid, uchar *crandom, uchar *ssid, int *nssid, uchar *srandom)
  1591. {
  1592. TlsSec *sec = emalloc(sizeof(*sec));
  1593. USED(csid); USED(ncsid); // ignore csid for now
  1594. memmove(sec->crandom, crandom, RandomSize);
  1595. sec->clientVers = cvers;
  1596. put32(sec->srandom, time(0));
  1597. genrandom(sec->srandom+4, RandomSize-4);
  1598. memmove(srandom, sec->srandom, RandomSize);
  1599. /*
  1600. * make up a unique sid: use our pid, and and incrementing id
  1601. * can signal no sid by setting nssid to 0.
  1602. */
  1603. memset(ssid, 0, SidSize);
  1604. put32(ssid, getpid());
  1605. lock(&sidLock);
  1606. put32(ssid+4, maxSid++);
  1607. unlock(&sidLock);
  1608. *nssid = SidSize;
  1609. return sec;
  1610. }
  1611. static int
  1612. tlsSecSecrets(TlsSec *sec, int vers, uchar *epm, int nepm, uchar *kd, int nkd)
  1613. {
  1614. if(epm != nil){
  1615. if(setVers(sec, vers) < 0)
  1616. goto Err;
  1617. serverMasterSecret(sec, epm, nepm);
  1618. }else if(sec->vers != vers){
  1619. werrstr("mismatched session versions");
  1620. goto Err;
  1621. }
  1622. setSecrets(sec, kd, nkd);
  1623. return 0;
  1624. Err:
  1625. sec->ok = -1;
  1626. return -1;
  1627. }
  1628. static TlsSec*
  1629. tlsSecInitc(int cvers, uchar *crandom)
  1630. {
  1631. TlsSec *sec = emalloc(sizeof(*sec));
  1632. sec->clientVers = cvers;
  1633. put32(sec->crandom, time(0));
  1634. genrandom(sec->crandom+4, RandomSize-4);
  1635. memmove(crandom, sec->crandom, RandomSize);
  1636. return sec;
  1637. }
  1638. static int
  1639. tlsSecSecretc(TlsSec *sec, uchar *sid, int nsid, uchar *srandom, uchar *cert, int ncert, int vers, uchar **epm, int *nepm, uchar *kd, int nkd)
  1640. {
  1641. RSApub *pub;
  1642. pub = nil;
  1643. USED(sid);
  1644. USED(nsid);
  1645. memmove(sec->srandom, srandom, RandomSize);
  1646. if(setVers(sec, vers) < 0)
  1647. goto Err;
  1648. pub = X509toRSApub(cert, ncert, nil, 0);
  1649. if(pub == nil){
  1650. werrstr("invalid x509/rsa certificate");
  1651. goto Err;
  1652. }
  1653. if(clientMasterSecret(sec, pub, epm, nepm) < 0)
  1654. goto Err;
  1655. rsapubfree(pub);
  1656. setSecrets(sec, kd, nkd);
  1657. return 0;
  1658. Err:
  1659. if(pub != nil)
  1660. rsapubfree(pub);
  1661. sec->ok = -1;
  1662. return -1;
  1663. }
  1664. static int
  1665. tlsSecFinished(TlsSec *sec, MD5state md5, SHAstate sha1, uchar *fin, int nfin, int isclient)
  1666. {
  1667. if(sec->nfin != nfin){
  1668. sec->ok = -1;
  1669. werrstr("invalid finished exchange");
  1670. return -1;
  1671. }
  1672. md5.malloced = 0;
  1673. sha1.malloced = 0;
  1674. (*sec->setFinished)(sec, md5, sha1, fin, isclient);
  1675. return 1;
  1676. }
  1677. static void
  1678. tlsSecOk(TlsSec *sec)
  1679. {
  1680. if(sec->ok == 0)
  1681. sec->ok = 1;
  1682. }
  1683. static void
  1684. tlsSecKill(TlsSec *sec)
  1685. {
  1686. if(!sec)
  1687. return;
  1688. factotum_rsa_close(sec->rpc);
  1689. sec->ok = -1;
  1690. }
  1691. static void
  1692. tlsSecClose(TlsSec *sec)
  1693. {
  1694. if(!sec)
  1695. return;
  1696. factotum_rsa_close(sec->rpc);
  1697. free(sec->server);
  1698. free(sec);
  1699. }
  1700. static int
  1701. setVers(TlsSec *sec, int v)
  1702. {
  1703. if(v == SSL3Version){
  1704. sec->setFinished = sslSetFinished;
  1705. sec->nfin = SSL3FinishedLen;
  1706. sec->prf = sslPRF;
  1707. }else if(v == TLSVersion){
  1708. sec->setFinished = tlsSetFinished;
  1709. sec->nfin = TLSFinishedLen;
  1710. sec->prf = tlsPRF;
  1711. }else{
  1712. werrstr("invalid version");
  1713. return -1;
  1714. }
  1715. sec->vers = v;
  1716. return 0;
  1717. }
  1718. /*
  1719. * generate secret keys from the master secret.
  1720. *
  1721. * different crypto selections will require different amounts
  1722. * of key expansion and use of key expansion data,
  1723. * but it's all generated using the same function.
  1724. */
  1725. static void
  1726. setSecrets(TlsSec *sec, uchar *kd, int nkd)
  1727. {
  1728. (*sec->prf)(kd, nkd, sec->sec, MasterSecretSize, "key expansion",
  1729. sec->srandom, RandomSize, sec->crandom, RandomSize);
  1730. }
  1731. /*
  1732. * set the master secret from the pre-master secret.
  1733. */
  1734. static void
  1735. setMasterSecret(TlsSec *sec, Bytes *pm)
  1736. {
  1737. (*sec->prf)(sec->sec, MasterSecretSize, pm->data, MasterSecretSize, "master secret",
  1738. sec->crandom, RandomSize, sec->srandom, RandomSize);
  1739. }
  1740. static void
  1741. serverMasterSecret(TlsSec *sec, uchar *epm, int nepm)
  1742. {
  1743. Bytes *pm;
  1744. pm = pkcs1_decrypt(sec, epm, nepm);
  1745. // if the client messed up, just continue as if everything is ok,
  1746. // to prevent attacks to check for correctly formatted messages.
  1747. // Hence the fprint(2,) can't be replaced by tlsError(), which sends an Alert msg to the client.
  1748. if(sec->ok < 0 || pm == nil || get16(pm->data) != sec->clientVers){
  1749. fprint(2, "serverMasterSecret failed ok=%d pm=%p pmvers=%x cvers=%x nepm=%d\n",
  1750. sec->ok, pm, pm ? get16(pm->data) : -1, sec->clientVers, nepm);
  1751. sec->ok = -1;
  1752. if(pm != nil)
  1753. freebytes(pm);
  1754. pm = newbytes(MasterSecretSize);
  1755. genrandom(pm->data, MasterSecretSize);
  1756. }
  1757. setMasterSecret(sec, pm);
  1758. memset(pm->data, 0, pm->len);
  1759. freebytes(pm);
  1760. }
  1761. static int
  1762. clientMasterSecret(TlsSec *sec, RSApub *pub, uchar **epm, int *nepm)
  1763. {
  1764. Bytes *pm, *key;
  1765. pm = newbytes(MasterSecretSize);
  1766. put16(pm->data, sec->clientVers);
  1767. genrandom(pm->data+2, MasterSecretSize - 2);
  1768. setMasterSecret(sec, pm);
  1769. key = pkcs1_encrypt(pm, pub, 2);
  1770. memset(pm->data, 0, pm->len);
  1771. freebytes(pm);
  1772. if(key == nil){
  1773. werrstr("tls pkcs1_encrypt failed");
  1774. return -1;
  1775. }
  1776. *nepm = key->len;
  1777. *epm = malloc(*nepm);
  1778. if(*epm == nil){
  1779. freebytes(key);
  1780. werrstr("out of memory");
  1781. return -1;
  1782. }
  1783. memmove(*epm, key->data, *nepm);
  1784. freebytes(key);
  1785. return 1;
  1786. }
  1787. static void
  1788. sslSetFinished(TlsSec *sec, MD5state hsmd5, SHAstate hssha1, uchar *finished, int isClient)
  1789. {
  1790. DigestState *s;
  1791. uchar h0[MD5dlen], h1[SHA1dlen], pad[48];
  1792. char *label;
  1793. if(isClient)
  1794. label = "CLNT";
  1795. else
  1796. label = "SRVR";
  1797. md5((uchar*)label, 4, nil, &hsmd5);
  1798. md5(sec->sec, MasterSecretSize, nil, &hsmd5);
  1799. memset(pad, 0x36, 48);
  1800. md5(pad, 48, nil, &hsmd5);
  1801. md5(nil, 0, h0, &hsmd5);
  1802. memset(pad, 0x5C, 48);
  1803. s = md5(sec->sec, MasterSecretSize, nil, nil);
  1804. s = md5(pad, 48, nil, s);
  1805. md5(h0, MD5dlen, finished, s);
  1806. sha1((uchar*)label, 4, nil, &hssha1);
  1807. sha1(sec->sec, MasterSecretSize, nil, &hssha1);
  1808. memset(pad, 0x36, 40);
  1809. sha1(pad, 40, nil, &hssha1);
  1810. sha1(nil, 0, h1, &hssha1);
  1811. memset(pad, 0x5C, 40);
  1812. s = sha1(sec->sec, MasterSecretSize, nil, nil);
  1813. s = sha1(pad, 40, nil, s);
  1814. sha1(h1, SHA1dlen, finished + MD5dlen, s);
  1815. }
  1816. // fill "finished" arg with md5(args)^sha1(args)
  1817. static void
  1818. tlsSetFinished(TlsSec *sec, MD5state hsmd5, SHAstate hssha1, uchar *finished, int isClient)
  1819. {
  1820. uchar h0[MD5dlen], h1[SHA1dlen];
  1821. char *label;
  1822. // get current hash value, but allow further messages to be hashed in
  1823. md5(nil, 0, h0, &hsmd5);
  1824. sha1(nil, 0, h1, &hssha1);
  1825. if(isClient)
  1826. label = "client finished";
  1827. else
  1828. label = "server finished";
  1829. tlsPRF(finished, TLSFinishedLen, sec->sec, MasterSecretSize, label, h0, MD5dlen, h1, SHA1dlen);
  1830. }
  1831. static void
  1832. sslPRF(uchar *buf, int nbuf, uchar *key, int nkey, char *label, uchar *seed0, int nseed0, uchar *seed1, int nseed1)
  1833. {
  1834. DigestState *s;
  1835. uchar sha1dig[SHA1dlen], md5dig[MD5dlen], tmp[26];
  1836. int i, n, len;
  1837. USED(label);
  1838. len = 1;
  1839. while(nbuf > 0){
  1840. if(len > 26)
  1841. return;
  1842. for(i = 0; i < len; i++)
  1843. tmp[i] = 'A' - 1 + len;
  1844. s = sha1(tmp, len, nil, nil);
  1845. s = sha1(key, nkey, nil, s);
  1846. s = sha1(seed0, nseed0, nil, s);
  1847. sha1(seed1, nseed1, sha1dig, s);
  1848. s = md5(key, nkey, nil, nil);
  1849. md5(sha1dig, SHA1dlen, md5dig, s);
  1850. n = MD5dlen;
  1851. if(n > nbuf)
  1852. n = nbuf;
  1853. memmove(buf, md5dig, n);
  1854. buf += n;
  1855. nbuf -= n;
  1856. len++;
  1857. }
  1858. }
  1859. static mpint*
  1860. bytestomp(Bytes* bytes)
  1861. {
  1862. mpint* ans;
  1863. ans = betomp(bytes->data, bytes->len, nil);
  1864. return ans;
  1865. }
  1866. /*
  1867. * Convert mpint* to Bytes, putting high order byte first.
  1868. */
  1869. static Bytes*
  1870. mptobytes(mpint* big)
  1871. {
  1872. int n, m;
  1873. uchar *a;
  1874. Bytes* ans;
  1875. a = nil;
  1876. n = (mpsignif(big)+7)/8;
  1877. m = mptobe(big, nil, n, &a);
  1878. ans = makebytes(a, m);
  1879. if(a != nil)
  1880. free(a);
  1881. return ans;
  1882. }
  1883. // Do RSA computation on block according to key, and pad
  1884. // result on left with zeros to make it modlen long.
  1885. static Bytes*
  1886. rsacomp(Bytes* block, RSApub* key, int modlen)
  1887. {
  1888. mpint *x, *y;
  1889. Bytes *a, *ybytes;
  1890. int ylen;
  1891. x = bytestomp(block);
  1892. y = rsaencrypt(key, x, nil);
  1893. mpfree(x);
  1894. ybytes = mptobytes(y);
  1895. ylen = ybytes->len;
  1896. if(ylen < modlen) {
  1897. a = newbytes(modlen);
  1898. memset(a->data, 0, modlen-ylen);
  1899. memmove(a->data+modlen-ylen, ybytes->data, ylen);
  1900. freebytes(ybytes);
  1901. ybytes = a;
  1902. }
  1903. else if(ylen > modlen) {
  1904. // assume it has leading zeros (mod should make it so)
  1905. a = newbytes(modlen);
  1906. memmove(a->data, ybytes->data, modlen);
  1907. freebytes(ybytes);
  1908. ybytes = a;
  1909. }
  1910. mpfree(y);
  1911. return ybytes;
  1912. }
  1913. // encrypt data according to PKCS#1, /lib/rfc/rfc2437 9.1.2.1
  1914. static Bytes*
  1915. pkcs1_encrypt(Bytes* data, RSApub* key, int blocktype)
  1916. {
  1917. Bytes *pad, *eb, *ans;
  1918. int i, dlen, padlen, modlen;
  1919. modlen = (mpsignif(key->n)+7)/8;
  1920. dlen = data->len;
  1921. if(modlen < 12 || dlen > modlen - 11)
  1922. return nil;
  1923. padlen = modlen - 3 - dlen;
  1924. pad = newbytes(padlen);
  1925. genrandom(pad->data, padlen);
  1926. for(i = 0; i < padlen; i++) {
  1927. if(blocktype == 0)
  1928. pad->data[i] = 0;
  1929. else if(blocktype == 1)
  1930. pad->data[i] = 255;
  1931. else if(pad->data[i] == 0)
  1932. pad->data[i] = 1;
  1933. }
  1934. eb = newbytes(modlen);
  1935. eb->data[0] = 0;
  1936. eb->data[1] = blocktype;
  1937. memmove(eb->data+2, pad->data, padlen);
  1938. eb->data[padlen+2] = 0;
  1939. memmove(eb->data+padlen+3, data->data, dlen);
  1940. ans = rsacomp(eb, key, modlen);
  1941. freebytes(eb);
  1942. freebytes(pad);
  1943. return ans;
  1944. }
  1945. // decrypt data according to PKCS#1, with given key.
  1946. // expect a block type of 2.
  1947. static Bytes*
  1948. pkcs1_decrypt(TlsSec *sec, uchar *epm, int nepm)
  1949. {
  1950. Bytes *eb, *ans = nil;
  1951. int i, modlen;
  1952. mpint *x, *y;
  1953. modlen = (mpsignif(sec->rsapub->n)+7)/8;
  1954. if(nepm != modlen)
  1955. return nil;
  1956. x = betomp(epm, nepm, nil);
  1957. y = factotum_rsa_decrypt(sec->rpc, x);
  1958. if(y == nil)
  1959. return nil;
  1960. eb = mptobytes(y);
  1961. if(eb->len < modlen){ // pad on left with zeros
  1962. ans = newbytes(modlen);
  1963. memset(ans->data, 0, modlen-eb->len);
  1964. memmove(ans->data+modlen-eb->len, eb->data, eb->len);
  1965. freebytes(eb);
  1966. eb = ans;
  1967. }
  1968. if(eb->data[0] == 0 && eb->data[1] == 2) {
  1969. for(i = 2; i < modlen; i++)
  1970. if(eb->data[i] == 0)
  1971. break;
  1972. if(i < modlen - 1)
  1973. ans = makebytes(eb->data+i+1, modlen-(i+1));
  1974. }
  1975. freebytes(eb);
  1976. return ans;
  1977. }
  1978. //================= general utility functions ========================
  1979. static void *
  1980. emalloc(int n)
  1981. {
  1982. void *p;
  1983. if(n==0)
  1984. n=1;
  1985. p = malloc(n);
  1986. if(p == nil){
  1987. exits("out of memory");
  1988. }
  1989. memset(p, 0, n);
  1990. return p;
  1991. }
  1992. static void *
  1993. erealloc(void *ReallocP, int ReallocN)
  1994. {
  1995. if(ReallocN == 0)
  1996. ReallocN = 1;
  1997. if(!ReallocP)
  1998. ReallocP = emalloc(ReallocN);
  1999. else if(!(ReallocP = realloc(ReallocP, ReallocN))){
  2000. exits("out of memory");
  2001. }
  2002. return(ReallocP);
  2003. }
  2004. static void
  2005. put32(uchar *p, u32int x)
  2006. {
  2007. p[0] = x>>24;
  2008. p[1] = x>>16;
  2009. p[2] = x>>8;
  2010. p[3] = x;
  2011. }
  2012. static void
  2013. put24(uchar *p, int x)
  2014. {
  2015. p[0] = x>>16;
  2016. p[1] = x>>8;
  2017. p[2] = x;
  2018. }
  2019. static void
  2020. put16(uchar *p, int x)
  2021. {
  2022. p[0] = x>>8;
  2023. p[1] = x;
  2024. }
  2025. static u32int
  2026. get32(uchar *p)
  2027. {
  2028. return (p[0]<<24)|(p[1]<<16)|(p[2]<<8)|p[3];
  2029. }
  2030. static int
  2031. get24(uchar *p)
  2032. {
  2033. return (p[0]<<16)|(p[1]<<8)|p[2];
  2034. }
  2035. static int
  2036. get16(uchar *p)
  2037. {
  2038. return (p[0]<<8)|p[1];
  2039. }
  2040. #define OFFSET(x, s) offsetof(s, x)
  2041. /*
  2042. * malloc and return a new Bytes structure capable of
  2043. * holding len bytes. (len >= 0)
  2044. * Used to use crypt_malloc, which aborts if malloc fails.
  2045. */
  2046. static Bytes*
  2047. newbytes(int len)
  2048. {
  2049. Bytes* ans;
  2050. ans = (Bytes*)malloc(OFFSET(data[0], Bytes) + len);
  2051. ans->len = len;
  2052. return ans;
  2053. }
  2054. /*
  2055. * newbytes(len), with data initialized from buf
  2056. */
  2057. static Bytes*
  2058. makebytes(uchar* buf, int len)
  2059. {
  2060. Bytes* ans;
  2061. ans = newbytes(len);
  2062. memmove(ans->data, buf, len);
  2063. return ans;
  2064. }
  2065. static void
  2066. freebytes(Bytes* b)
  2067. {
  2068. if(b != nil)
  2069. free(b);
  2070. }
  2071. /* len is number of ints */
  2072. static Ints*
  2073. newints(int len)
  2074. {
  2075. Ints* ans;
  2076. ans = (Ints*)malloc(OFFSET(data[0], Ints) + len*sizeof(int));
  2077. ans->len = len;
  2078. return ans;
  2079. }
  2080. static Ints*
  2081. makeints(int* buf, int len)
  2082. {
  2083. Ints* ans;
  2084. ans = newints(len);
  2085. if(len > 0)
  2086. memmove(ans->data, buf, len*sizeof(int));
  2087. return ans;
  2088. }
  2089. static void
  2090. freeints(Ints* b)
  2091. {
  2092. if(b != nil)
  2093. free(b);
  2094. }