tlshand.c 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308
  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;
  1094. buf = emalloc(8000);
  1095. c->trace("recv %s", msgPrint(buf, 8000, m));
  1096. free(buf);
  1097. }
  1098. return 1;
  1099. Short:
  1100. tlsError(c, EDecodeError, "handshake message has invalid length");
  1101. Err:
  1102. msgClear(m);
  1103. return 0;
  1104. }
  1105. static void
  1106. msgClear(Msg *m)
  1107. {
  1108. int i;
  1109. switch(m->tag) {
  1110. default:
  1111. sysfatal("msgClear: unknown message type: %d\n", m->tag);
  1112. case HHelloRequest:
  1113. break;
  1114. case HClientHello:
  1115. freebytes(m->u.clientHello.sid);
  1116. freeints(m->u.clientHello.ciphers);
  1117. freebytes(m->u.clientHello.compressors);
  1118. break;
  1119. case HServerHello:
  1120. freebytes(m->u.clientHello.sid);
  1121. break;
  1122. case HCertificate:
  1123. for(i=0; i<m->u.certificate.ncert; i++)
  1124. freebytes(m->u.certificate.certs[i]);
  1125. free(m->u.certificate.certs);
  1126. break;
  1127. case HCertificateRequest:
  1128. freebytes(m->u.certificateRequest.types);
  1129. for(i=0; i<m->u.certificateRequest.nca; i++)
  1130. freebytes(m->u.certificateRequest.cas[i]);
  1131. free(m->u.certificateRequest.cas);
  1132. break;
  1133. case HServerHelloDone:
  1134. break;
  1135. case HClientKeyExchange:
  1136. freebytes(m->u.clientKeyExchange.key);
  1137. break;
  1138. case HFinished:
  1139. break;
  1140. }
  1141. memset(m, 0, sizeof(Msg));
  1142. }
  1143. static char *
  1144. bytesPrint(char *bs, char *be, char *s0, Bytes *b, char *s1)
  1145. {
  1146. int i;
  1147. if(s0)
  1148. bs = seprint(bs, be, "%s", s0);
  1149. bs = seprint(bs, be, "[");
  1150. if(b == nil)
  1151. bs = seprint(bs, be, "nil");
  1152. else
  1153. for(i=0; i<b->len; i++)
  1154. bs = seprint(bs, be, "%.2x ", b->data[i]);
  1155. bs = seprint(bs, be, "]");
  1156. if(s1)
  1157. bs = seprint(bs, be, "%s", s1);
  1158. return bs;
  1159. }
  1160. static char *
  1161. intsPrint(char *bs, char *be, char *s0, Ints *b, char *s1)
  1162. {
  1163. int i;
  1164. if(s0)
  1165. bs = seprint(bs, be, "%s", s0);
  1166. bs = seprint(bs, be, "[");
  1167. if(b == nil)
  1168. bs = seprint(bs, be, "nil");
  1169. else
  1170. for(i=0; i<b->len; i++)
  1171. bs = seprint(bs, be, "%x ", b->data[i]);
  1172. bs = seprint(bs, be, "]");
  1173. if(s1)
  1174. bs = seprint(bs, be, "%s", s1);
  1175. return bs;
  1176. }
  1177. static char*
  1178. msgPrint(char *buf, int n, Msg *m)
  1179. {
  1180. int i;
  1181. char *bs = buf, *be = buf+n;
  1182. switch(m->tag) {
  1183. default:
  1184. bs = seprint(bs, be, "unknown %d\n", m->tag);
  1185. break;
  1186. case HClientHello:
  1187. bs = seprint(bs, be, "ClientHello\n");
  1188. bs = seprint(bs, be, "\tversion: %.4x\n", m->u.clientHello.version);
  1189. bs = seprint(bs, be, "\trandom: ");
  1190. for(i=0; i<RandomSize; i++)
  1191. bs = seprint(bs, be, "%.2x", m->u.clientHello.random[i]);
  1192. bs = seprint(bs, be, "\n");
  1193. bs = bytesPrint(bs, be, "\tsid: ", m->u.clientHello.sid, "\n");
  1194. bs = intsPrint(bs, be, "\tciphers: ", m->u.clientHello.ciphers, "\n");
  1195. bs = bytesPrint(bs, be, "\tcompressors: ", m->u.clientHello.compressors, "\n");
  1196. break;
  1197. case HServerHello:
  1198. bs = seprint(bs, be, "ServerHello\n");
  1199. bs = seprint(bs, be, "\tversion: %.4x\n", m->u.serverHello.version);
  1200. bs = seprint(bs, be, "\trandom: ");
  1201. for(i=0; i<RandomSize; i++)
  1202. bs = seprint(bs, be, "%.2x", m->u.serverHello.random[i]);
  1203. bs = seprint(bs, be, "\n");
  1204. bs = bytesPrint(bs, be, "\tsid: ", m->u.serverHello.sid, "\n");
  1205. bs = seprint(bs, be, "\tcipher: %.4x\n", m->u.serverHello.cipher);
  1206. bs = seprint(bs, be, "\tcompressor: %.2x\n", m->u.serverHello.compressor);
  1207. break;
  1208. case HCertificate:
  1209. bs = seprint(bs, be, "Certificate\n");
  1210. for(i=0; i<m->u.certificate.ncert; i++)
  1211. bs = bytesPrint(bs, be, "\t", m->u.certificate.certs[i], "\n");
  1212. break;
  1213. case HCertificateRequest:
  1214. bs = seprint(bs, be, "CertificateRequest\n");
  1215. bs = bytesPrint(bs, be, "\ttypes: ", m->u.certificateRequest.types, "\n");
  1216. bs = seprint(bs, be, "\tcertificateauthorities\n");
  1217. for(i=0; i<m->u.certificateRequest.nca; i++)
  1218. bs = bytesPrint(bs, be, "\t\t", m->u.certificateRequest.cas[i], "\n");
  1219. break;
  1220. case HServerHelloDone:
  1221. bs = seprint(bs, be, "ServerHelloDone\n");
  1222. break;
  1223. case HClientKeyExchange:
  1224. bs = seprint(bs, be, "HClientKeyExchange\n");
  1225. bs = bytesPrint(bs, be, "\tkey: ", m->u.clientKeyExchange.key, "\n");
  1226. break;
  1227. case HFinished:
  1228. bs = seprint(bs, be, "HFinished\n");
  1229. for(i=0; i<m->u.finished.n; i++)
  1230. bs = seprint(bs, be, "%.2x", m->u.finished.verify[i]);
  1231. bs = seprint(bs, be, "\n");
  1232. break;
  1233. }
  1234. USED(bs);
  1235. return buf;
  1236. }
  1237. static void
  1238. tlsError(TlsConnection *c, int err, char *fmt, ...)
  1239. {
  1240. char msg[512];
  1241. va_list arg;
  1242. va_start(arg, fmt);
  1243. vseprint(msg, msg+sizeof(msg), fmt, arg);
  1244. va_end(arg);
  1245. if(c->trace)
  1246. c->trace("tlsError: %s\n", msg);
  1247. else if(c->erred)
  1248. fprint(2, "double error: %r, %s", msg);
  1249. else
  1250. werrstr("tls: local %s", msg);
  1251. c->erred = 1;
  1252. fprint(c->ctl, "alert %d", err);
  1253. }
  1254. // commit to specific version number
  1255. static int
  1256. setVersion(TlsConnection *c, int version)
  1257. {
  1258. if(c->verset || version > MaxProtoVersion || version < MinProtoVersion)
  1259. return -1;
  1260. if(version > c->version)
  1261. version = c->version;
  1262. if(version == SSL3Version) {
  1263. c->version = version;
  1264. c->finished.n = SSL3FinishedLen;
  1265. }else if(version == TLSVersion){
  1266. c->version = version;
  1267. c->finished.n = TLSFinishedLen;
  1268. }else
  1269. return -1;
  1270. c->verset = 1;
  1271. return fprint(c->ctl, "version 0x%x", version);
  1272. }
  1273. // confirm that received Finished message matches the expected value
  1274. static int
  1275. finishedMatch(TlsConnection *c, Finished *f)
  1276. {
  1277. return memcmp(f->verify, c->finished.verify, f->n) == 0;
  1278. }
  1279. // free memory associated with TlsConnection struct
  1280. // (but don't close the TLS channel itself)
  1281. static void
  1282. tlsConnectionFree(TlsConnection *c)
  1283. {
  1284. tlsSecClose(c->sec);
  1285. freebytes(c->sid);
  1286. freebytes(c->cert);
  1287. memset(c, 0, sizeof(c));
  1288. free(c);
  1289. }
  1290. //================= cipher choices ========================
  1291. static int weakCipher[CipherMax] =
  1292. {
  1293. 1, /* TLS_NULL_WITH_NULL_NULL */
  1294. 1, /* TLS_RSA_WITH_NULL_MD5 */
  1295. 1, /* TLS_RSA_WITH_NULL_SHA */
  1296. 1, /* TLS_RSA_EXPORT_WITH_RC4_40_MD5 */
  1297. 0, /* TLS_RSA_WITH_RC4_128_MD5 */
  1298. 0, /* TLS_RSA_WITH_RC4_128_SHA */
  1299. 1, /* TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 */
  1300. 0, /* TLS_RSA_WITH_IDEA_CBC_SHA */
  1301. 1, /* TLS_RSA_EXPORT_WITH_DES40_CBC_SHA */
  1302. 0, /* TLS_RSA_WITH_DES_CBC_SHA */
  1303. 0, /* TLS_RSA_WITH_3DES_EDE_CBC_SHA */
  1304. 1, /* TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA */
  1305. 0, /* TLS_DH_DSS_WITH_DES_CBC_SHA */
  1306. 0, /* TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA */
  1307. 1, /* TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA */
  1308. 0, /* TLS_DH_RSA_WITH_DES_CBC_SHA */
  1309. 0, /* TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA */
  1310. 1, /* TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA */
  1311. 0, /* TLS_DHE_DSS_WITH_DES_CBC_SHA */
  1312. 0, /* TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA */
  1313. 1, /* TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA */
  1314. 0, /* TLS_DHE_RSA_WITH_DES_CBC_SHA */
  1315. 0, /* TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA */
  1316. 1, /* TLS_DH_anon_EXPORT_WITH_RC4_40_MD5 */
  1317. 1, /* TLS_DH_anon_WITH_RC4_128_MD5 */
  1318. 1, /* TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA */
  1319. 1, /* TLS_DH_anon_WITH_DES_CBC_SHA */
  1320. 1, /* TLS_DH_anon_WITH_3DES_EDE_CBC_SHA */
  1321. };
  1322. static int
  1323. setAlgs(TlsConnection *c, int a)
  1324. {
  1325. int i;
  1326. for(i = 0; i < nelem(cipherAlgs); i++){
  1327. if(cipherAlgs[i].tlsid == a){
  1328. c->enc = cipherAlgs[i].enc;
  1329. c->digest = cipherAlgs[i].digest;
  1330. c->nsecret = cipherAlgs[i].nsecret;
  1331. if(c->nsecret > MaxKeyData)
  1332. return 0;
  1333. return 1;
  1334. }
  1335. }
  1336. return 0;
  1337. }
  1338. static int
  1339. okCipher(Ints *cv)
  1340. {
  1341. int weak, i, j, c;
  1342. weak = 1;
  1343. for(i = 0; i < cv->len; i++) {
  1344. c = cv->data[i];
  1345. if(c >= CipherMax)
  1346. weak = 0;
  1347. else
  1348. weak &= weakCipher[c];
  1349. for(j = 0; j < nelem(cipherAlgs); j++)
  1350. if(cipherAlgs[j].ok && cipherAlgs[j].tlsid == c)
  1351. return c;
  1352. }
  1353. if(weak)
  1354. return -2;
  1355. return -1;
  1356. }
  1357. static int
  1358. okCompression(Bytes *cv)
  1359. {
  1360. int i, j, c;
  1361. for(i = 0; i < cv->len; i++) {
  1362. c = cv->data[i];
  1363. for(j = 0; j < nelem(compressors); j++) {
  1364. if(compressors[j] == c)
  1365. return c;
  1366. }
  1367. }
  1368. return -1;
  1369. }
  1370. static Lock ciphLock;
  1371. static int nciphers;
  1372. static int
  1373. initCiphers(void)
  1374. {
  1375. enum {MaxAlgF = 1024, MaxAlgs = 10};
  1376. char s[MaxAlgF], *flds[MaxAlgs];
  1377. int i, j, n, ok;
  1378. lock(&ciphLock);
  1379. if(nciphers){
  1380. unlock(&ciphLock);
  1381. return nciphers;
  1382. }
  1383. j = open("#a/tls/encalgs", OREAD);
  1384. if(j < 0){
  1385. werrstr("can't open #a/tls/encalgs: %r");
  1386. return 0;
  1387. }
  1388. n = read(j, s, MaxAlgF-1);
  1389. close(j);
  1390. if(n <= 0){
  1391. werrstr("nothing in #a/tls/encalgs: %r");
  1392. return 0;
  1393. }
  1394. s[n] = 0;
  1395. n = getfields(s, flds, MaxAlgs, 1, " \t\r\n");
  1396. for(i = 0; i < nelem(cipherAlgs); i++){
  1397. ok = 0;
  1398. for(j = 0; j < n; j++){
  1399. if(strcmp(cipherAlgs[i].enc, flds[j]) == 0){
  1400. ok = 1;
  1401. break;
  1402. }
  1403. }
  1404. cipherAlgs[i].ok = ok;
  1405. }
  1406. j = open("#a/tls/hashalgs", OREAD);
  1407. if(j < 0){
  1408. werrstr("can't open #a/tls/hashalgs: %r");
  1409. return 0;
  1410. }
  1411. n = read(j, s, MaxAlgF-1);
  1412. close(j);
  1413. if(n <= 0){
  1414. werrstr("nothing in #a/tls/hashalgs: %r");
  1415. return 0;
  1416. }
  1417. s[n] = 0;
  1418. n = getfields(s, flds, MaxAlgs, 1, " \t\r\n");
  1419. for(i = 0; i < nelem(cipherAlgs); i++){
  1420. ok = 0;
  1421. for(j = 0; j < n; j++){
  1422. if(strcmp(cipherAlgs[i].digest, flds[j]) == 0){
  1423. ok = 1;
  1424. break;
  1425. }
  1426. }
  1427. cipherAlgs[i].ok &= ok;
  1428. if(cipherAlgs[i].ok)
  1429. nciphers++;
  1430. }
  1431. unlock(&ciphLock);
  1432. return nciphers;
  1433. }
  1434. static Ints*
  1435. makeciphers(void)
  1436. {
  1437. Ints *is;
  1438. int i, j;
  1439. is = newints(nciphers);
  1440. j = 0;
  1441. for(i = 0; i < nelem(cipherAlgs); i++){
  1442. if(cipherAlgs[i].ok)
  1443. is->data[j++] = cipherAlgs[i].tlsid;
  1444. }
  1445. return is;
  1446. }
  1447. //================= security functions ========================
  1448. // given X.509 certificate, set up connection to factotum
  1449. // for using corresponding private key
  1450. static AuthRpc*
  1451. factotum_rsa_open(uchar *cert, int certlen)
  1452. {
  1453. int afd;
  1454. char *s;
  1455. mpint *pub = nil;
  1456. RSApub *rsapub;
  1457. AuthRpc *rpc;
  1458. // start talking to factotum
  1459. if((afd = open("/mnt/factotum/rpc", ORDWR)) < 0)
  1460. return nil;
  1461. if((rpc = auth_allocrpc(afd)) == nil){
  1462. close(afd);
  1463. return nil;
  1464. }
  1465. s = "proto=rsa service=tls role=client";
  1466. if(auth_rpc(rpc, "start", s, strlen(s)) != ARok){
  1467. factotum_rsa_close(rpc);
  1468. return nil;
  1469. }
  1470. // roll factotum keyring around to match certificate
  1471. rsapub = X509toRSApub(cert, certlen, nil, 0);
  1472. while(1){
  1473. if(auth_rpc(rpc, "read", nil, 0) != ARok){
  1474. factotum_rsa_close(rpc);
  1475. rpc = nil;
  1476. goto done;
  1477. }
  1478. pub = strtomp(rpc->arg, nil, 16, nil);
  1479. assert(pub != nil);
  1480. if(mpcmp(pub,rsapub->n) == 0)
  1481. break;
  1482. }
  1483. done:
  1484. mpfree(pub);
  1485. rsapubfree(rsapub);
  1486. return rpc;
  1487. }
  1488. static mpint*
  1489. factotum_rsa_decrypt(AuthRpc *rpc, mpint *cipher)
  1490. {
  1491. char *p;
  1492. int rv;
  1493. if((p = mptoa(cipher, 16, nil, 0)) == nil)
  1494. return nil;
  1495. rv = auth_rpc(rpc, "write", p, strlen(p));
  1496. free(p);
  1497. if(rv != ARok || auth_rpc(rpc, "read", nil, 0) != ARok)
  1498. return nil;
  1499. mpfree(cipher);
  1500. return strtomp(rpc->arg, nil, 16, nil);
  1501. }
  1502. static void
  1503. factotum_rsa_close(AuthRpc*rpc)
  1504. {
  1505. if(!rpc)
  1506. return;
  1507. close(rpc->afd);
  1508. auth_freerpc(rpc);
  1509. }
  1510. static void
  1511. tlsPmd5(uchar *buf, int nbuf, uchar *key, int nkey, uchar *label, int nlabel, uchar *seed0, int nseed0, uchar *seed1, int nseed1)
  1512. {
  1513. uchar ai[MD5dlen], tmp[MD5dlen];
  1514. int i, n;
  1515. MD5state *s;
  1516. // generate a1
  1517. s = hmac_md5(label, nlabel, key, nkey, nil, nil);
  1518. s = hmac_md5(seed0, nseed0, key, nkey, nil, s);
  1519. hmac_md5(seed1, nseed1, key, nkey, ai, s);
  1520. while(nbuf > 0) {
  1521. s = hmac_md5(ai, MD5dlen, key, nkey, nil, nil);
  1522. s = hmac_md5(label, nlabel, key, nkey, nil, s);
  1523. s = hmac_md5(seed0, nseed0, key, nkey, nil, s);
  1524. hmac_md5(seed1, nseed1, key, nkey, tmp, s);
  1525. n = MD5dlen;
  1526. if(n > nbuf)
  1527. n = nbuf;
  1528. for(i = 0; i < n; i++)
  1529. buf[i] ^= tmp[i];
  1530. buf += n;
  1531. nbuf -= n;
  1532. hmac_md5(ai, MD5dlen, key, nkey, tmp, nil);
  1533. memmove(ai, tmp, MD5dlen);
  1534. }
  1535. }
  1536. static void
  1537. tlsPsha1(uchar *buf, int nbuf, uchar *key, int nkey, uchar *label, int nlabel, uchar *seed0, int nseed0, uchar *seed1, int nseed1)
  1538. {
  1539. uchar ai[SHA1dlen], tmp[SHA1dlen];
  1540. int i, n;
  1541. SHAstate *s;
  1542. // generate a1
  1543. s = hmac_sha1(label, nlabel, key, nkey, nil, nil);
  1544. s = hmac_sha1(seed0, nseed0, key, nkey, nil, s);
  1545. hmac_sha1(seed1, nseed1, key, nkey, ai, s);
  1546. while(nbuf > 0) {
  1547. s = hmac_sha1(ai, SHA1dlen, key, nkey, nil, nil);
  1548. s = hmac_sha1(label, nlabel, key, nkey, nil, s);
  1549. s = hmac_sha1(seed0, nseed0, key, nkey, nil, s);
  1550. hmac_sha1(seed1, nseed1, key, nkey, tmp, s);
  1551. n = SHA1dlen;
  1552. if(n > nbuf)
  1553. n = nbuf;
  1554. for(i = 0; i < n; i++)
  1555. buf[i] ^= tmp[i];
  1556. buf += n;
  1557. nbuf -= n;
  1558. hmac_sha1(ai, SHA1dlen, key, nkey, tmp, nil);
  1559. memmove(ai, tmp, SHA1dlen);
  1560. }
  1561. }
  1562. // fill buf with md5(args)^sha1(args)
  1563. static void
  1564. tlsPRF(uchar *buf, int nbuf, uchar *key, int nkey, char *label, uchar *seed0, int nseed0, uchar *seed1, int nseed1)
  1565. {
  1566. int i;
  1567. int nlabel = strlen(label);
  1568. int n = (nkey + 1) >> 1;
  1569. for(i = 0; i < nbuf; i++)
  1570. buf[i] = 0;
  1571. tlsPmd5(buf, nbuf, key, n, (uchar*)label, nlabel, seed0, nseed0, seed1, nseed1);
  1572. tlsPsha1(buf, nbuf, key+nkey-n, n, (uchar*)label, nlabel, seed0, nseed0, seed1, nseed1);
  1573. }
  1574. /*
  1575. * for setting server session id's
  1576. */
  1577. static Lock sidLock;
  1578. static long maxSid = 1;
  1579. /* the keys are verified to have the same public components
  1580. * and to function correctly with pkcs 1 encryption and decryption. */
  1581. static TlsSec*
  1582. tlsSecInits(int cvers, uchar *csid, int ncsid, uchar *crandom, uchar *ssid, int *nssid, uchar *srandom)
  1583. {
  1584. TlsSec *sec = emalloc(sizeof(*sec));
  1585. USED(csid); USED(ncsid); // ignore csid for now
  1586. memmove(sec->crandom, crandom, RandomSize);
  1587. sec->clientVers = cvers;
  1588. put32(sec->srandom, time(0));
  1589. genrandom(sec->srandom+4, RandomSize-4);
  1590. memmove(srandom, sec->srandom, RandomSize);
  1591. /*
  1592. * make up a unique sid: use our pid, and and incrementing id
  1593. * can signal no sid by setting nssid to 0.
  1594. */
  1595. memset(ssid, 0, SidSize);
  1596. put32(ssid, getpid());
  1597. lock(&sidLock);
  1598. put32(ssid+4, maxSid++);
  1599. unlock(&sidLock);
  1600. *nssid = SidSize;
  1601. return sec;
  1602. }
  1603. static int
  1604. tlsSecSecrets(TlsSec *sec, int vers, uchar *epm, int nepm, uchar *kd, int nkd)
  1605. {
  1606. if(epm != nil){
  1607. if(setVers(sec, vers) < 0)
  1608. goto Err;
  1609. serverMasterSecret(sec, epm, nepm);
  1610. }else if(sec->vers != vers){
  1611. werrstr("mismatched session versions");
  1612. goto Err;
  1613. }
  1614. setSecrets(sec, kd, nkd);
  1615. return 0;
  1616. Err:
  1617. sec->ok = -1;
  1618. return -1;
  1619. }
  1620. static TlsSec*
  1621. tlsSecInitc(int cvers, uchar *crandom)
  1622. {
  1623. TlsSec *sec = emalloc(sizeof(*sec));
  1624. sec->clientVers = cvers;
  1625. put32(sec->crandom, time(0));
  1626. genrandom(sec->crandom+4, RandomSize-4);
  1627. memmove(crandom, sec->crandom, RandomSize);
  1628. return sec;
  1629. }
  1630. static int
  1631. tlsSecSecretc(TlsSec *sec, uchar *sid, int nsid, uchar *srandom, uchar *cert, int ncert, int vers, uchar **epm, int *nepm, uchar *kd, int nkd)
  1632. {
  1633. RSApub *pub;
  1634. pub = nil;
  1635. USED(sid);
  1636. USED(nsid);
  1637. memmove(sec->srandom, srandom, RandomSize);
  1638. if(setVers(sec, vers) < 0)
  1639. goto Err;
  1640. pub = X509toRSApub(cert, ncert, nil, 0);
  1641. if(pub == nil){
  1642. werrstr("invalid x509/rsa certificate");
  1643. goto Err;
  1644. }
  1645. if(clientMasterSecret(sec, pub, epm, nepm) < 0)
  1646. goto Err;
  1647. rsapubfree(pub);
  1648. setSecrets(sec, kd, nkd);
  1649. return 0;
  1650. Err:
  1651. if(pub != nil)
  1652. rsapubfree(pub);
  1653. sec->ok = -1;
  1654. return -1;
  1655. }
  1656. static int
  1657. tlsSecFinished(TlsSec *sec, MD5state md5, SHAstate sha1, uchar *fin, int nfin, int isclient)
  1658. {
  1659. if(sec->nfin != nfin){
  1660. sec->ok = -1;
  1661. werrstr("invalid finished exchange");
  1662. return -1;
  1663. }
  1664. md5.malloced = 0;
  1665. sha1.malloced = 0;
  1666. (*sec->setFinished)(sec, md5, sha1, fin, isclient);
  1667. return 1;
  1668. }
  1669. static void
  1670. tlsSecOk(TlsSec *sec)
  1671. {
  1672. if(sec->ok == 0)
  1673. sec->ok = 1;
  1674. }
  1675. static void
  1676. tlsSecKill(TlsSec *sec)
  1677. {
  1678. if(!sec)
  1679. return;
  1680. factotum_rsa_close(sec->rpc);
  1681. sec->ok = -1;
  1682. }
  1683. static void
  1684. tlsSecClose(TlsSec *sec)
  1685. {
  1686. if(!sec)
  1687. return;
  1688. factotum_rsa_close(sec->rpc);
  1689. free(sec->server);
  1690. free(sec);
  1691. }
  1692. static int
  1693. setVers(TlsSec *sec, int v)
  1694. {
  1695. if(v == SSL3Version){
  1696. sec->setFinished = sslSetFinished;
  1697. sec->nfin = SSL3FinishedLen;
  1698. sec->prf = sslPRF;
  1699. }else if(v == TLSVersion){
  1700. sec->setFinished = tlsSetFinished;
  1701. sec->nfin = TLSFinishedLen;
  1702. sec->prf = tlsPRF;
  1703. }else{
  1704. werrstr("invalid version");
  1705. return -1;
  1706. }
  1707. sec->vers = v;
  1708. return 0;
  1709. }
  1710. /*
  1711. * generate secret keys from the master secret.
  1712. *
  1713. * different crypto selections will require different amounts
  1714. * of key expansion and use of key expansion data,
  1715. * but it's all generated using the same function.
  1716. */
  1717. static void
  1718. setSecrets(TlsSec *sec, uchar *kd, int nkd)
  1719. {
  1720. (*sec->prf)(kd, nkd, sec->sec, MasterSecretSize, "key expansion",
  1721. sec->srandom, RandomSize, sec->crandom, RandomSize);
  1722. }
  1723. /*
  1724. * set the master secret from the pre-master secret.
  1725. */
  1726. static void
  1727. setMasterSecret(TlsSec *sec, Bytes *pm)
  1728. {
  1729. (*sec->prf)(sec->sec, MasterSecretSize, pm->data, MasterSecretSize, "master secret",
  1730. sec->crandom, RandomSize, sec->srandom, RandomSize);
  1731. }
  1732. static void
  1733. serverMasterSecret(TlsSec *sec, uchar *epm, int nepm)
  1734. {
  1735. Bytes *pm;
  1736. pm = pkcs1_decrypt(sec, epm, nepm);
  1737. // if the client messed up, just continue as if everything is ok,
  1738. // to prevent attacks to check for correctly formatted messages.
  1739. // Hence the fprint(2,) can't be replaced by tlsError(), which sends an Alert msg to the client.
  1740. if(sec->ok < 0 || pm == nil || get16(pm->data) != sec->clientVers){
  1741. fprint(2, "serverMasterSecret failed ok=%d pm=%p pmvers=%x cvers=%x nepm=%d\n",
  1742. sec->ok, pm, pm ? get16(pm->data) : -1, sec->clientVers, nepm);
  1743. sec->ok = -1;
  1744. if(pm != nil)
  1745. freebytes(pm);
  1746. pm = newbytes(MasterSecretSize);
  1747. genrandom(pm->data, MasterSecretSize);
  1748. }
  1749. setMasterSecret(sec, pm);
  1750. memset(pm->data, 0, pm->len);
  1751. freebytes(pm);
  1752. }
  1753. static int
  1754. clientMasterSecret(TlsSec *sec, RSApub *pub, uchar **epm, int *nepm)
  1755. {
  1756. Bytes *pm, *key;
  1757. pm = newbytes(MasterSecretSize);
  1758. put16(pm->data, sec->clientVers);
  1759. genrandom(pm->data+2, MasterSecretSize - 2);
  1760. setMasterSecret(sec, pm);
  1761. key = pkcs1_encrypt(pm, pub, 2);
  1762. memset(pm->data, 0, pm->len);
  1763. freebytes(pm);
  1764. if(key == nil){
  1765. werrstr("tls pkcs1_encrypt failed");
  1766. return -1;
  1767. }
  1768. *nepm = key->len;
  1769. *epm = malloc(*nepm);
  1770. if(*epm == nil){
  1771. freebytes(key);
  1772. werrstr("out of memory");
  1773. return -1;
  1774. }
  1775. memmove(*epm, key->data, *nepm);
  1776. freebytes(key);
  1777. return 1;
  1778. }
  1779. static void
  1780. sslSetFinished(TlsSec *sec, MD5state hsmd5, SHAstate hssha1, uchar *finished, int isClient)
  1781. {
  1782. DigestState *s;
  1783. uchar h0[MD5dlen], h1[SHA1dlen], pad[48];
  1784. char *label;
  1785. if(isClient)
  1786. label = "CLNT";
  1787. else
  1788. label = "SRVR";
  1789. md5((uchar*)label, 4, nil, &hsmd5);
  1790. md5(sec->sec, MasterSecretSize, nil, &hsmd5);
  1791. memset(pad, 0x36, 48);
  1792. md5(pad, 48, nil, &hsmd5);
  1793. md5(nil, 0, h0, &hsmd5);
  1794. memset(pad, 0x5C, 48);
  1795. s = md5(sec->sec, MasterSecretSize, nil, nil);
  1796. s = md5(pad, 48, nil, s);
  1797. md5(h0, MD5dlen, finished, s);
  1798. sha1((uchar*)label, 4, nil, &hssha1);
  1799. sha1(sec->sec, MasterSecretSize, nil, &hssha1);
  1800. memset(pad, 0x36, 40);
  1801. sha1(pad, 40, nil, &hssha1);
  1802. sha1(nil, 0, h1, &hssha1);
  1803. memset(pad, 0x5C, 40);
  1804. s = sha1(sec->sec, MasterSecretSize, nil, nil);
  1805. s = sha1(pad, 40, nil, s);
  1806. sha1(h1, SHA1dlen, finished + MD5dlen, s);
  1807. }
  1808. // fill "finished" arg with md5(args)^sha1(args)
  1809. static void
  1810. tlsSetFinished(TlsSec *sec, MD5state hsmd5, SHAstate hssha1, uchar *finished, int isClient)
  1811. {
  1812. uchar h0[MD5dlen], h1[SHA1dlen];
  1813. char *label;
  1814. // get current hash value, but allow further messages to be hashed in
  1815. md5(nil, 0, h0, &hsmd5);
  1816. sha1(nil, 0, h1, &hssha1);
  1817. if(isClient)
  1818. label = "client finished";
  1819. else
  1820. label = "server finished";
  1821. tlsPRF(finished, TLSFinishedLen, sec->sec, MasterSecretSize, label, h0, MD5dlen, h1, SHA1dlen);
  1822. }
  1823. static void
  1824. sslPRF(uchar *buf, int nbuf, uchar *key, int nkey, char *label, uchar *seed0, int nseed0, uchar *seed1, int nseed1)
  1825. {
  1826. DigestState *s;
  1827. uchar sha1dig[SHA1dlen], md5dig[MD5dlen], tmp[26];
  1828. int i, n, len;
  1829. USED(label);
  1830. len = 1;
  1831. while(nbuf > 0){
  1832. if(len > 26)
  1833. return;
  1834. for(i = 0; i < len; i++)
  1835. tmp[i] = 'A' - 1 + len;
  1836. s = sha1(tmp, len, nil, nil);
  1837. s = sha1(key, nkey, nil, s);
  1838. s = sha1(seed0, nseed0, nil, s);
  1839. sha1(seed1, nseed1, sha1dig, s);
  1840. s = md5(key, nkey, nil, nil);
  1841. md5(sha1dig, SHA1dlen, md5dig, s);
  1842. n = MD5dlen;
  1843. if(n > nbuf)
  1844. n = nbuf;
  1845. memmove(buf, md5dig, n);
  1846. buf += n;
  1847. nbuf -= n;
  1848. len++;
  1849. }
  1850. }
  1851. static mpint*
  1852. bytestomp(Bytes* bytes)
  1853. {
  1854. mpint* ans;
  1855. ans = betomp(bytes->data, bytes->len, nil);
  1856. return ans;
  1857. }
  1858. /*
  1859. * Convert mpint* to Bytes, putting high order byte first.
  1860. */
  1861. static Bytes*
  1862. mptobytes(mpint* big)
  1863. {
  1864. int n, m;
  1865. uchar *a;
  1866. Bytes* ans;
  1867. n = (mpsignif(big)+7)/8;
  1868. m = mptobe(big, nil, n, &a);
  1869. ans = makebytes(a, m);
  1870. return ans;
  1871. }
  1872. // Do RSA computation on block according to key, and pad
  1873. // result on left with zeros to make it modlen long.
  1874. static Bytes*
  1875. rsacomp(Bytes* block, RSApub* key, int modlen)
  1876. {
  1877. mpint *x, *y;
  1878. Bytes *a, *ybytes;
  1879. int ylen;
  1880. x = bytestomp(block);
  1881. y = rsaencrypt(key, x, nil);
  1882. mpfree(x);
  1883. ybytes = mptobytes(y);
  1884. ylen = ybytes->len;
  1885. if(ylen < modlen) {
  1886. a = newbytes(modlen);
  1887. memset(a->data, 0, modlen-ylen);
  1888. memmove(a->data+modlen-ylen, ybytes->data, ylen);
  1889. freebytes(ybytes);
  1890. ybytes = a;
  1891. }
  1892. else if(ylen > modlen) {
  1893. // assume it has leading zeros (mod should make it so)
  1894. a = newbytes(modlen);
  1895. memmove(a->data, ybytes->data, modlen);
  1896. freebytes(ybytes);
  1897. ybytes = a;
  1898. }
  1899. mpfree(y);
  1900. return ybytes;
  1901. }
  1902. // encrypt data according to PKCS#1, /lib/rfc/rfc2437 9.1.2.1
  1903. static Bytes*
  1904. pkcs1_encrypt(Bytes* data, RSApub* key, int blocktype)
  1905. {
  1906. Bytes *pad, *eb, *ans;
  1907. int i, dlen, padlen, modlen;
  1908. modlen = (mpsignif(key->n)+7)/8;
  1909. dlen = data->len;
  1910. if(modlen < 12 || dlen > modlen - 11)
  1911. return nil;
  1912. padlen = modlen - 3 - dlen;
  1913. pad = newbytes(padlen);
  1914. genrandom(pad->data, padlen);
  1915. for(i = 0; i < padlen; i++) {
  1916. if(blocktype == 0)
  1917. pad->data[i] = 0;
  1918. else if(blocktype == 1)
  1919. pad->data[i] = 255;
  1920. else if(pad->data[i] == 0)
  1921. pad->data[i] = 1;
  1922. }
  1923. eb = newbytes(modlen);
  1924. eb->data[0] = 0;
  1925. eb->data[1] = blocktype;
  1926. memmove(eb->data+2, pad->data, padlen);
  1927. eb->data[padlen+2] = 0;
  1928. memmove(eb->data+padlen+3, data->data, dlen);
  1929. ans = rsacomp(eb, key, modlen);
  1930. freebytes(eb);
  1931. freebytes(pad);
  1932. return ans;
  1933. }
  1934. // decrypt data according to PKCS#1, with given key.
  1935. // expect a block type of 2.
  1936. static Bytes*
  1937. pkcs1_decrypt(TlsSec *sec, uchar *epm, int nepm)
  1938. {
  1939. Bytes *eb, *ans = nil;
  1940. int i, modlen;
  1941. mpint *x, *y;
  1942. modlen = (mpsignif(sec->rsapub->n)+7)/8;
  1943. if(nepm != modlen)
  1944. return nil;
  1945. x = betomp(epm, nepm, nil);
  1946. y = factotum_rsa_decrypt(sec->rpc, x);
  1947. if(y == nil)
  1948. return nil;
  1949. eb = mptobytes(y);
  1950. if(eb->len < modlen){ // pad on left with zeros
  1951. ans = newbytes(modlen);
  1952. memset(ans->data, 0, modlen-eb->len);
  1953. memmove(ans->data+modlen-eb->len, eb->data, eb->len);
  1954. freebytes(eb);
  1955. eb = ans;
  1956. }
  1957. if(eb->data[0] == 0 && eb->data[1] == 2) {
  1958. for(i = 2; i < modlen; i++)
  1959. if(eb->data[i] == 0)
  1960. break;
  1961. if(i < modlen - 1)
  1962. ans = makebytes(eb->data+i+1, modlen-(i+1));
  1963. }
  1964. freebytes(eb);
  1965. return ans;
  1966. }
  1967. //================= general utility functions ========================
  1968. static void *
  1969. emalloc(int n)
  1970. {
  1971. void *p;
  1972. if(n==0)
  1973. n=1;
  1974. p = malloc(n);
  1975. if(p == nil){
  1976. exits("out of memory");
  1977. }
  1978. memset(p, 0, n);
  1979. return p;
  1980. }
  1981. static void *
  1982. erealloc(void *ReallocP, int ReallocN)
  1983. {
  1984. if(ReallocN == 0)
  1985. ReallocN = 1;
  1986. if(!ReallocP)
  1987. ReallocP = emalloc(ReallocN);
  1988. else if(!(ReallocP = realloc(ReallocP, ReallocN))){
  1989. exits("out of memory");
  1990. }
  1991. return(ReallocP);
  1992. }
  1993. static void
  1994. put32(uchar *p, u32int x)
  1995. {
  1996. p[0] = x>>24;
  1997. p[1] = x>>16;
  1998. p[2] = x>>8;
  1999. p[3] = x;
  2000. }
  2001. static void
  2002. put24(uchar *p, int x)
  2003. {
  2004. p[0] = x>>16;
  2005. p[1] = x>>8;
  2006. p[2] = x;
  2007. }
  2008. static void
  2009. put16(uchar *p, int x)
  2010. {
  2011. p[0] = x>>8;
  2012. p[1] = x;
  2013. }
  2014. static u32int
  2015. get32(uchar *p)
  2016. {
  2017. return (p[0]<<24)|(p[1]<<16)|(p[2]<<8)|p[3];
  2018. }
  2019. static int
  2020. get24(uchar *p)
  2021. {
  2022. return (p[0]<<16)|(p[1]<<8)|p[2];
  2023. }
  2024. static int
  2025. get16(uchar *p)
  2026. {
  2027. return (p[0]<<8)|p[1];
  2028. }
  2029. /* ANSI offsetof() */
  2030. #define OFFSET(x, s) ((int)(&(((s*)0)->x)))
  2031. /*
  2032. * malloc and return a new Bytes structure capable of
  2033. * holding len bytes. (len >= 0)
  2034. * Used to use crypt_malloc, which aborts if malloc fails.
  2035. */
  2036. static Bytes*
  2037. newbytes(int len)
  2038. {
  2039. Bytes* ans;
  2040. ans = (Bytes*)malloc(OFFSET(data[0], Bytes) + len);
  2041. ans->len = len;
  2042. return ans;
  2043. }
  2044. /*
  2045. * newbytes(len), with data initialized from buf
  2046. */
  2047. static Bytes*
  2048. makebytes(uchar* buf, int len)
  2049. {
  2050. Bytes* ans;
  2051. ans = newbytes(len);
  2052. memmove(ans->data, buf, len);
  2053. return ans;
  2054. }
  2055. static void
  2056. freebytes(Bytes* b)
  2057. {
  2058. if(b != nil)
  2059. free(b);
  2060. }
  2061. /* len is number of ints */
  2062. static Ints*
  2063. newints(int len)
  2064. {
  2065. Ints* ans;
  2066. ans = (Ints*)malloc(OFFSET(data[0], Ints) + len*sizeof(int));
  2067. ans->len = len;
  2068. return ans;
  2069. }
  2070. static Ints*
  2071. makeints(int* buf, int len)
  2072. {
  2073. Ints* ans;
  2074. ans = newints(len);
  2075. if(len > 0)
  2076. memmove(ans->data, buf, len*sizeof(int));
  2077. return ans;
  2078. }
  2079. static void
  2080. freeints(Ints* b)
  2081. {
  2082. if(b != nil)
  2083. free(b);
  2084. }