tlshand.c 53 KB

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