tlshand.c 54 KB

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