CryptoAuth.c 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. #include "crypto/CryptoAuth_pvt.h"
  16. #include "crypto/AddressCalc.h"
  17. #include "crypto/ReplayProtector.h"
  18. #include "crypto/random/Random.h"
  19. #include "benc/Dict.h"
  20. #include "benc/List.h"
  21. #include "benc/String.h"
  22. #include "util/log/Log.h"
  23. #include "memory/Allocator.h"
  24. #include "util/Assert.h"
  25. #include "util/AddrTools.h"
  26. #include "util/Bits.h"
  27. #include "util/Defined.h"
  28. #include "util/Endian.h"
  29. #include "util/Hex.h"
  30. #include "util/events/Time.h"
  31. #include "wire/Error.h"
  32. #include "wire/Headers.h"
  33. #include "wire/Message.h"
  34. #include <sodium/crypto_box_curve25519xsalsa20poly1305.h>
  35. #include <sodium/crypto_hash_sha256.h>
  36. #include <sodium/crypto_scalarmult_curve25519.h>
  37. #include <stdint.h>
  38. #include <stdbool.h>
  39. enum Nonce {
  40. Nonce_HELLO = 0,
  41. Nonce_REPEAT_HELLO = 1,
  42. Nonce_KEY = 2,
  43. Nonce_REPEAT_KEY = 3,
  44. Nonce_FIRST_TRAFFIC_PACKET = 4
  45. };
  46. static inline void printHexKey(uint8_t output[65], uint8_t key[32])
  47. {
  48. if (key) {
  49. Hex_encode(output, 65, key, 32);
  50. } else {
  51. Bits_memcpy(output, "NULL", 5);
  52. }
  53. }
  54. static inline void printHexPubKey(uint8_t output[65], uint8_t privateKey[32])
  55. {
  56. if (privateKey) {
  57. uint8_t publicKey[32];
  58. crypto_scalarmult_curve25519_base(publicKey, privateKey);
  59. printHexKey(output, publicKey);
  60. } else {
  61. printHexKey(output, NULL);
  62. }
  63. }
  64. /**
  65. * Get a shared secret.
  66. *
  67. * @param outputSecret an array to place the shared secret in.
  68. * @param myPrivateKey
  69. * @param herPublicKey
  70. * @param logger
  71. * @param passwordHash a 32 byte value known to both ends, this must be provably pseudorandom
  72. * the first 32 bytes of a sha256 output from hashing a password is ok,
  73. * whatever she happens to send me in the Auth field is NOT ok.
  74. * If this field is null, the secret will be generated without the password.
  75. */
  76. static inline void getSharedSecret(uint8_t outputSecret[32],
  77. uint8_t myPrivateKey[32],
  78. uint8_t herPublicKey[32],
  79. uint8_t passwordHash[32],
  80. struct Log* logger)
  81. {
  82. if (passwordHash == NULL) {
  83. Assert_true(!crypto_box_curve25519xsalsa20poly1305_beforenm(
  84. outputSecret, herPublicKey, myPrivateKey));
  85. } else {
  86. union {
  87. struct {
  88. uint8_t key[32];
  89. uint8_t passwd[32];
  90. } components;
  91. uint8_t bytes[64];
  92. } buff;
  93. Assert_true(!crypto_scalarmult_curve25519(buff.components.key, myPrivateKey, herPublicKey));
  94. Bits_memcpy(buff.components.passwd, passwordHash, 32);
  95. crypto_hash_sha256(outputSecret, buff.bytes, 64);
  96. }
  97. if (Defined(Log_KEYS)) {
  98. uint8_t myPublicKeyHex[65];
  99. printHexPubKey(myPublicKeyHex, myPrivateKey);
  100. uint8_t herPublicKeyHex[65];
  101. printHexKey(herPublicKeyHex, herPublicKey);
  102. uint8_t passwordHashHex[65];
  103. printHexKey(passwordHashHex, passwordHash);
  104. uint8_t outputSecretHex[65] = "NULL";
  105. printHexKey(outputSecretHex, outputSecret);
  106. Log_keys(logger,
  107. "Generated a shared secret:\n"
  108. " myPublicKey=%s\n"
  109. " herPublicKey=%s\n"
  110. " passwordHash=%s\n"
  111. " outputSecret=%s\n",
  112. myPublicKeyHex, herPublicKeyHex, passwordHashHex, outputSecretHex);
  113. }
  114. }
  115. static inline void hashPassword(uint8_t secretOut[32],
  116. struct CryptoHeader_Challenge* challengeOut,
  117. const String* login,
  118. const String* password,
  119. const uint8_t authType)
  120. {
  121. crypto_hash_sha256(secretOut, (uint8_t*) password->bytes, password->len);
  122. uint8_t tempBuff[32];
  123. if (authType == 1) {
  124. crypto_hash_sha256(tempBuff, secretOut, 32);
  125. } else if (authType == 2) {
  126. crypto_hash_sha256(tempBuff, (uint8_t*) login->bytes, login->len);
  127. } else {
  128. Assert_failure("Unsupported auth type [%u]", authType);
  129. }
  130. Bits_memcpy(challengeOut, tempBuff, CryptoHeader_Challenge_SIZE);
  131. CryptoHeader_setAuthChallengeDerivations(challengeOut, 0);
  132. challengeOut->type = authType;
  133. challengeOut->additional = 0;
  134. }
  135. /**
  136. * Search the authorized passwords for one matching this auth header.
  137. *
  138. * @param auth the auth header.
  139. * @param context the CryptoAuth engine to search in.
  140. * @return an Auth struct with a if one is found, otherwise NULL.
  141. */
  142. static inline struct CryptoAuth_User* getAuth(struct CryptoHeader_Challenge* auth,
  143. struct CryptoAuth_pvt* ca)
  144. {
  145. if (auth->type == 0) {
  146. return NULL;
  147. }
  148. int count = 0;
  149. for (struct CryptoAuth_User* u = ca->users; u; u = u->next) {
  150. count++;
  151. if (auth->type == 1 &&
  152. !Bits_memcmp(auth, u->passwordHash, CryptoHeader_Challenge_KEYSIZE))
  153. {
  154. return u;
  155. } else if (auth->type == 2 &&
  156. !Bits_memcmp(auth, u->userNameHash, CryptoHeader_Challenge_KEYSIZE))
  157. {
  158. return u;
  159. }
  160. }
  161. Log_debug(ca->logger, "Got unrecognized auth, password count = [%d]", count);
  162. return NULL;
  163. }
  164. /**
  165. * Decrypt and authenticate.
  166. *
  167. * @param nonce a 24 byte number, may be random, cannot repeat.
  168. * @param msg a message to encipher and authenticate.
  169. * @param secret a shared secret.
  170. * @return 0 if decryption is succeddful, otherwise -1.
  171. */
  172. static inline Gcc_USE_RET int decryptRndNonce(uint8_t nonce[24],
  173. struct Message* msg,
  174. uint8_t secret[32])
  175. {
  176. if (msg->length < 16) {
  177. return -1;
  178. }
  179. Assert_true(msg->padding >= 16);
  180. uint8_t* startAt = msg->bytes - 16;
  181. uint8_t paddingSpace[16];
  182. Bits_memcpy(paddingSpace, startAt, 16);
  183. Bits_memset(startAt, 0, 16);
  184. if (!Defined(NSA_APPROVED)) {
  185. if (crypto_box_curve25519xsalsa20poly1305_open_afternm(
  186. startAt, startAt, msg->length + 16, nonce, secret) != 0)
  187. {
  188. return -1;
  189. }
  190. }
  191. Bits_memcpy(startAt, paddingSpace, 16);
  192. Er_assert(Message_eshift(msg, -16));
  193. return 0;
  194. }
  195. /**
  196. * Encrypt and authenticate.
  197. * Shifts the message by 16 bytes.
  198. *
  199. * @param nonce a 24 byte number, may be random, cannot repeat.
  200. * @param msg a message to encipher and authenticate.
  201. * @param secret a shared secret.
  202. */
  203. static inline void encryptRndNonce(uint8_t nonce[24],
  204. struct Message* msg,
  205. uint8_t secret[32])
  206. {
  207. Assert_true(msg->padding >= 32);
  208. uint8_t* startAt = msg->bytes - 32;
  209. // This function trashes 16 bytes of the padding so we will put it back
  210. uint8_t paddingSpace[16];
  211. Bits_memcpy(paddingSpace, startAt, 16);
  212. Bits_memset(startAt, 0, 32);
  213. if (!Defined(NSA_APPROVED)) {
  214. crypto_box_curve25519xsalsa20poly1305_afternm(
  215. startAt, startAt, msg->length + 32, nonce, secret);
  216. }
  217. Bits_memcpy(startAt, paddingSpace, 16);
  218. Er_assert(Message_eshift(msg, 16));
  219. }
  220. /**
  221. * Decrypt a packet.
  222. *
  223. * @param nonce a counter.
  224. * @param msg the message to decrypt, decrypted in place.
  225. * @param secret the shared secret.
  226. * @param isInitiator true if we started the connection.
  227. */
  228. static inline Gcc_USE_RET int decrypt(uint32_t nonce,
  229. struct Message* msg,
  230. uint8_t secret[32],
  231. bool isInitiator)
  232. {
  233. union {
  234. uint32_t ints[2];
  235. uint8_t bytes[24];
  236. } nonceAs = { .ints = {0, 0} };
  237. nonceAs.ints[!isInitiator] = Endian_hostToLittleEndian32(nonce);
  238. return decryptRndNonce(nonceAs.bytes, msg, secret);
  239. }
  240. /**
  241. * Encrypt a packet.
  242. *
  243. * @param nonce a counter.
  244. * @param msg the message to decrypt, decrypted in place.
  245. * @param secret the shared secret.
  246. * @param isInitiator true if we started the connection.
  247. */
  248. static inline void encrypt(uint32_t nonce,
  249. struct Message* msg,
  250. uint8_t secret[32],
  251. bool isInitiator)
  252. {
  253. union {
  254. uint32_t ints[2];
  255. uint8_t bytes[24];
  256. } nonceAs = { .ints = {0, 0} };
  257. nonceAs.ints[isInitiator] = Endian_hostToLittleEndian32(nonce);
  258. encryptRndNonce(nonceAs.bytes, msg, secret);
  259. }
  260. static inline bool knowHerKey(struct CryptoAuth_Session_pvt* session)
  261. {
  262. return !Bits_isZero(session->pub.herPublicKey, 32);
  263. }
  264. static void getIp6(struct CryptoAuth_Session_pvt* session, uint8_t* addr)
  265. {
  266. Assert_true(knowHerKey(session));
  267. uint8_t ip6[16];
  268. AddressCalc_addressForPublicKey(ip6, session->pub.herPublicKey);
  269. AddrTools_printIp(addr, ip6);
  270. }
  271. #define cryptoAuthDebug(wrapper, format, ...) \
  272. do { \
  273. if (!Defined(Log_DEBUG)) { break; } \
  274. uint8_t addr[40] = "unknown"; \
  275. getIp6((session), addr); \
  276. String* dn = (session)->pub.displayName; \
  277. Log_debug((session)->context->logger, "%p %s [%s] state[%d]: " format, (void*)(session), \
  278. dn ? dn->bytes : "", addr, (session)->nextNonce, __VA_ARGS__); \
  279. } while (0)
  280. // CHECKFILES_IGNORE missing ;
  281. #define cryptoAuthDebug0(wrapper, format) \
  282. cryptoAuthDebug(session, format "%s", "")
  283. static void reset(struct CryptoAuth_Session_pvt* session)
  284. {
  285. session->nextNonce = CryptoAuth_State_INIT;
  286. session->isInitiator = false;
  287. Bits_memset(session->ourTempPrivKey, 0, 32);
  288. Bits_memset(session->ourTempPubKey, 0, 32);
  289. Bits_memset(session->herTempPubKey, 0, 32);
  290. Bits_memset(session->sharedSecret, 0, 32);
  291. session->established = false;
  292. Bits_memset(&session->pub.replayProtector, 0, sizeof(struct ReplayProtector));
  293. }
  294. static void resetIfTimeout(struct CryptoAuth_Session_pvt* session)
  295. {
  296. if (session->nextNonce == CryptoAuth_State_SENT_HELLO) {
  297. // Lets not reset the session, we just sent one or more hello packets and
  298. // have not received a response, if they respond after we reset then we'll
  299. // be in a tough state.
  300. return;
  301. }
  302. uint64_t nowSecs = Time_currentTimeSeconds(session->context->eventBase);
  303. if (nowSecs - session->timeOfLastPacket < session->pub.setupResetAfterInactivitySeconds) {
  304. return;
  305. } else if (nowSecs - session->timeOfLastPacket < session->pub.resetAfterInactivitySeconds) {
  306. if (session->established) { return; }
  307. }
  308. cryptoAuthDebug(session, "No traffic in [%d] seconds, resetting connection.",
  309. (int) (nowSecs - session->timeOfLastPacket));
  310. session->timeOfLastPacket = nowSecs;
  311. reset(session);
  312. }
  313. static void encryptHandshake(struct Message* message,
  314. struct CryptoAuth_Session_pvt* session,
  315. int setupMessage)
  316. {
  317. Er_assert(Message_eshift(message, CryptoHeader_SIZE));
  318. struct CryptoHeader* header = (struct CryptoHeader*) message->bytes;
  319. // garbage the auth challenge and set the nonce which follows it
  320. Random_bytes(session->context->rand, (uint8_t*) &header->auth,
  321. CryptoHeader_Challenge_SIZE + 24);
  322. // set the permanent key
  323. Bits_memcpy(header->publicKey, session->context->pub.publicKey, 32);
  324. Assert_true(knowHerKey(session));
  325. // Password auth
  326. uint8_t* passwordHash = NULL;
  327. uint8_t passwordHashStore[32];
  328. if (session->password != NULL) {
  329. hashPassword(passwordHashStore,
  330. &header->auth,
  331. session->login,
  332. session->password,
  333. session->authType);
  334. passwordHash = passwordHashStore;
  335. } else {
  336. header->auth.type = session->authType;
  337. header->auth.additional = 0;
  338. }
  339. // Set the session state
  340. header->nonce = Endian_hostToBigEndian32(session->nextNonce);
  341. if (session->nextNonce == CryptoAuth_State_INIT ||
  342. session->nextNonce == CryptoAuth_State_RECEIVED_HELLO)
  343. {
  344. // If we're sending a hello or a key
  345. // Here we make up a temp keypair
  346. Random_bytes(session->context->rand, session->ourTempPrivKey, 32);
  347. crypto_scalarmult_curve25519_base(session->ourTempPubKey, session->ourTempPrivKey);
  348. if (Defined(Log_KEYS)) {
  349. uint8_t tempPrivateKeyHex[65];
  350. Hex_encode(tempPrivateKeyHex, 65, session->ourTempPrivKey, 32);
  351. uint8_t tempPubKeyHex[65];
  352. Hex_encode(tempPubKeyHex, 65, session->ourTempPubKey, 32);
  353. Log_keys(session->context->logger, "Generating temporary keypair\n"
  354. " myTempPrivateKey=%s\n"
  355. " myTempPublicKey=%s\n",
  356. tempPrivateKeyHex, tempPubKeyHex);
  357. }
  358. }
  359. Bits_memcpy(header->encryptedTempKey, session->ourTempPubKey, 32);
  360. if (Defined(Log_KEYS)) {
  361. uint8_t tempKeyHex[65];
  362. Hex_encode(tempKeyHex, 65, header->encryptedTempKey, 32);
  363. Log_keys(session->context->logger,
  364. "Wrapping temp public key:\n"
  365. " %s\n",
  366. tempKeyHex);
  367. }
  368. cryptoAuthDebug(session, "Sending %s%s packet (auth: %d)",
  369. ((session->nextNonce & 1) ? "repeat " : ""),
  370. ((session->nextNonce < CryptoAuth_State_RECEIVED_HELLO) ? "hello" : "key"),
  371. (passwordHash != NULL));
  372. uint8_t sharedSecret[32];
  373. if (session->nextNonce < CryptoAuth_State_RECEIVED_HELLO) {
  374. getSharedSecret(sharedSecret,
  375. session->context->privateKey,
  376. session->pub.herPublicKey,
  377. passwordHash,
  378. session->context->logger);
  379. session->isInitiator = true;
  380. Assert_true(session->nextNonce <= CryptoAuth_State_SENT_HELLO);
  381. session->nextNonce = CryptoAuth_State_SENT_HELLO;
  382. } else {
  383. // Handshake2
  384. // herTempPubKey was set by decryptHandshake()
  385. Assert_ifParanoid(!Bits_isZero(session->herTempPubKey, 32));
  386. getSharedSecret(sharedSecret,
  387. session->context->privateKey,
  388. session->herTempPubKey,
  389. passwordHash,
  390. session->context->logger);
  391. Assert_true(session->nextNonce <= CryptoAuth_State_SENT_KEY);
  392. session->nextNonce = CryptoAuth_State_SENT_KEY;
  393. if (Defined(Log_KEYS)) {
  394. uint8_t tempKeyHex[65];
  395. Hex_encode(tempKeyHex, 65, session->herTempPubKey, 32);
  396. Log_keys(session->context->logger,
  397. "Using their temp public key:\n"
  398. " %s\n",
  399. tempKeyHex);
  400. }
  401. }
  402. Assert_true((session->nextNonce < CryptoAuth_State_RECEIVED_HELLO) ==
  403. Bits_isZero(session->herTempPubKey, 32));
  404. // Shift message over the encryptedTempKey field.
  405. Er_assert(Message_eshift(message, 32 - CryptoHeader_SIZE));
  406. encryptRndNonce(header->handshakeNonce, message, sharedSecret);
  407. if (Defined(Log_KEYS)) {
  408. uint8_t sharedSecretHex[65];
  409. printHexKey(sharedSecretHex, sharedSecret);
  410. uint8_t nonceHex[49];
  411. Hex_encode(nonceHex, 49, header->handshakeNonce, 24);
  412. uint8_t cipherHex[65];
  413. printHexKey(cipherHex, message->bytes);
  414. Log_keys(session->context->logger,
  415. "Encrypting message with:\n"
  416. " nonce: %s\n"
  417. " secret: %s\n"
  418. " cipher: %s\n",
  419. nonceHex, sharedSecretHex, cipherHex);
  420. }
  421. // Shift it back -- encryptRndNonce adds 16 bytes of authenticator.
  422. Er_assert(Message_eshift(message, CryptoHeader_SIZE - 32 - 16));
  423. }
  424. /** @return 0 on success, -1 otherwise. */
  425. int CryptoAuth_encrypt(struct CryptoAuth_Session* sessionPub, struct Message* msg)
  426. {
  427. struct CryptoAuth_Session_pvt* session =
  428. Identity_check((struct CryptoAuth_Session_pvt*) sessionPub);
  429. // If there has been no incoming traffic for a while, reset the connection to state 0.
  430. // This will prevent "connection in bad state" situations from lasting forever.
  431. // this will reset the session if it has timed out.
  432. resetIfTimeout(session);
  433. // If the nonce wraps, start over.
  434. if (session->nextNonce >= 0xfffffff0) {
  435. reset(session);
  436. }
  437. Assert_true(!((uintptr_t)msg->bytes % 4) || !"alignment fault");
  438. // nextNonce 0: sending hello, we are initiating connection.
  439. // nextNonce 1: sending another hello, nothing received yet.
  440. // nextNonce 2: sending key, hello received.
  441. // nextNonce 3: sending key again, no data packet recieved yet.
  442. // nextNonce >3: handshake complete
  443. //
  444. // if it's a blind handshake, every message will be empty and nextNonce will remain
  445. // zero until the first message is received back.
  446. if (session->nextNonce <= CryptoAuth_State_RECEIVED_KEY) {
  447. if (session->nextNonce < CryptoAuth_State_RECEIVED_KEY) {
  448. encryptHandshake(msg, session, 0);
  449. return 0;
  450. } else {
  451. cryptoAuthDebug0(session, "Doing final step to send message. nonce=4");
  452. Assert_ifParanoid(!Bits_isZero(session->ourTempPrivKey, 32));
  453. Assert_ifParanoid(!Bits_isZero(session->herTempPubKey, 32));
  454. getSharedSecret(session->sharedSecret,
  455. session->ourTempPrivKey,
  456. session->herTempPubKey,
  457. NULL,
  458. session->context->logger);
  459. }
  460. }
  461. Assert_true(msg->length > 0 && "Empty packet during handshake");
  462. Assert_true(msg->padding >= 36 || !"not enough padding");
  463. encrypt(session->nextNonce, msg, session->sharedSecret, session->isInitiator);
  464. Er_assert(Message_epush32be(msg, session->nextNonce));
  465. session->nextNonce++;
  466. return 0;
  467. }
  468. /** Call the external interface and tell it that a message has been received. */
  469. static inline void updateTime(struct CryptoAuth_Session_pvt* session, struct Message* message)
  470. {
  471. session->timeOfLastPacket = Time_currentTimeSeconds(session->context->eventBase);
  472. }
  473. static inline enum CryptoAuth_DecryptErr decryptMessage(struct CryptoAuth_Session_pvt* session,
  474. uint32_t nonce,
  475. struct Message* content,
  476. uint8_t secret[32])
  477. {
  478. // Decrypt with authentication and replay prevention.
  479. if (decrypt(nonce, content, secret, session->isInitiator)) {
  480. cryptoAuthDebug0(session, "DROP authenticated decryption failed");
  481. return CryptoAuth_DecryptErr_DECRYPT;
  482. }
  483. if (!ReplayProtector_checkNonce(nonce, &session->pub.replayProtector)) {
  484. cryptoAuthDebug(session, "DROP nonce checking failed nonce=[%u]", nonce);
  485. return CryptoAuth_DecryptErr_REPLAY;
  486. }
  487. return 0;
  488. }
  489. static bool ip6MatchesKey(uint8_t ip6[16], uint8_t key[32])
  490. {
  491. uint8_t calculatedIp6[16];
  492. AddressCalc_addressForPublicKey(calculatedIp6, key);
  493. return !Bits_memcmp(ip6, calculatedIp6, 16);
  494. }
  495. static enum CryptoAuth_DecryptErr decryptHandshake(struct CryptoAuth_Session_pvt* session,
  496. const uint32_t nonce,
  497. struct Message* message,
  498. struct CryptoHeader* header)
  499. {
  500. if (message->length < CryptoHeader_SIZE) {
  501. cryptoAuthDebug0(session, "DROP runt");
  502. return CryptoAuth_DecryptErr_RUNT;
  503. }
  504. // handshake
  505. // nextNonce 0: recieving hello.
  506. // nextNonce 1: recieving key, we sent hello.
  507. // nextNonce 2: recieving first data packet or duplicate hello.
  508. // nextNonce 3: recieving first data packet.
  509. // nextNonce >3: handshake complete
  510. Assert_true(knowHerKey(session));
  511. if (Bits_memcmp(session->pub.herPublicKey, header->publicKey, 32)) {
  512. cryptoAuthDebug0(session, "DROP a packet with different public key than this session");
  513. return CryptoAuth_DecryptErr_WRONG_PERM_PUBKEY;
  514. }
  515. Assert_true((session->nextNonce < CryptoAuth_State_RECEIVED_HELLO) ==
  516. Bits_isZero(session->herTempPubKey, 32));
  517. struct CryptoAuth_User* userObj = getAuth(&header->auth, session->context);
  518. uint8_t* restrictedToip6 = NULL;
  519. uint8_t* passwordHash = NULL;
  520. if (userObj) {
  521. passwordHash = userObj->secret;
  522. if (userObj->restrictedToip6[0]) {
  523. restrictedToip6 = userObj->restrictedToip6;
  524. if (!ip6MatchesKey(restrictedToip6, session->pub.herPublicKey)) {
  525. cryptoAuthDebug0(session, "DROP packet with key not matching restrictedToip6");
  526. return CryptoAuth_DecryptErr_IP_RESTRICTED;
  527. }
  528. }
  529. }
  530. if (session->requireAuth && !userObj) {
  531. cryptoAuthDebug0(session, "DROP message because auth was not given");
  532. return CryptoAuth_DecryptErr_AUTH_REQUIRED;
  533. }
  534. if (!userObj && header->auth.type != 0) {
  535. cryptoAuthDebug0(session, "DROP message with unrecognized authenticator");
  536. return CryptoAuth_DecryptErr_UNRECOGNIZED_AUTH;
  537. }
  538. // What the nextNonce will become if this packet is valid.
  539. uint32_t nextNonce;
  540. // The secret for decrypting this message.
  541. uint8_t sharedSecret[32];
  542. if (nonce < Nonce_KEY) { // HELLO or REPEAT_HELLO
  543. cryptoAuthDebug(session, "Received a %shello packet, using auth: %d",
  544. (nonce == Nonce_REPEAT_HELLO) ? "repeat " : "",
  545. (userObj != NULL));
  546. getSharedSecret(sharedSecret,
  547. session->context->privateKey,
  548. session->pub.herPublicKey,
  549. passwordHash,
  550. session->context->logger);
  551. nextNonce = CryptoAuth_State_RECEIVED_HELLO;
  552. } else {
  553. if (nonce == Nonce_KEY) {
  554. cryptoAuthDebug0(session, "Received a key packet");
  555. } else {
  556. Assert_true(nonce == Nonce_REPEAT_KEY);
  557. cryptoAuthDebug0(session, "Received a repeat key packet");
  558. }
  559. if (!session->isInitiator) {
  560. cryptoAuthDebug0(session, "DROP a stray key packet");
  561. return CryptoAuth_DecryptErr_STRAY_KEY;
  562. }
  563. // We sent the hello, this is a key
  564. getSharedSecret(sharedSecret,
  565. session->ourTempPrivKey,
  566. session->pub.herPublicKey,
  567. passwordHash,
  568. session->context->logger);
  569. nextNonce = CryptoAuth_State_RECEIVED_KEY;
  570. }
  571. // Shift it on top of the authenticator before the encrypted public key
  572. Er_assert(Message_eshift(message, 48 - CryptoHeader_SIZE));
  573. if (Defined(Log_KEYS)) {
  574. uint8_t sharedSecretHex[65];
  575. printHexKey(sharedSecretHex, sharedSecret);
  576. uint8_t nonceHex[49];
  577. Hex_encode(nonceHex, 49, header->handshakeNonce, 24);
  578. uint8_t cipherHex[65];
  579. printHexKey(cipherHex, message->bytes);
  580. Log_keys(session->context->logger,
  581. "Decrypting message with:\n"
  582. " nonce: %s\n"
  583. " secret: %s\n"
  584. " cipher: %s\n",
  585. nonceHex, sharedSecretHex, cipherHex);
  586. }
  587. // Decrypt her temp public key and the message.
  588. if (decryptRndNonce(header->handshakeNonce, message, sharedSecret)) {
  589. // just in case
  590. Bits_memset(header, 0, CryptoHeader_SIZE);
  591. cryptoAuthDebug(session, "DROP message with nonce [%d], decryption failed", nonce);
  592. return CryptoAuth_DecryptErr_HANDSHAKE_DECRYPT_FAILED;
  593. }
  594. if (Bits_isZero(header->encryptedTempKey, 32)) {
  595. // we need to reject 0 public keys outright because they will be confused with "unknown"
  596. cryptoAuthDebug0(session, "DROP message with zero as temp public key");
  597. return CryptoAuth_DecryptErr_WISEGUY;
  598. }
  599. if (Defined(Log_KEYS)) {
  600. uint8_t tempKeyHex[65];
  601. Hex_encode(tempKeyHex, 65, header->encryptedTempKey, 32);
  602. Log_keys(session->context->logger,
  603. "Unwrapping temp public key:\n"
  604. " %s\n",
  605. tempKeyHex);
  606. }
  607. Er_assert(Message_eshift(message, -32));
  608. // Post-decryption checking
  609. if (nonce == Nonce_HELLO) {
  610. // A new hello packet
  611. if (!Bits_memcmp(session->herTempPubKey, header->encryptedTempKey, 32)) {
  612. // possible replay attack or duped packet
  613. cryptoAuthDebug0(session, "DROP dupe hello packet with same temp key");
  614. return CryptoAuth_DecryptErr_INVALID_PACKET;
  615. }
  616. } else if (nonce == Nonce_KEY && session->nextNonce >= CryptoAuth_State_RECEIVED_KEY) {
  617. // we accept a new key packet and let it change the session since the other end might have
  618. // killed off the session while it was in the midst of setting up.
  619. // This is NOT a repeat key packet because it's nonce is 2, not 3
  620. if (!Bits_memcmp(session->herTempPubKey, header->encryptedTempKey, 32)) {
  621. Assert_true(!Bits_isZero(session->herTempPubKey, 32));
  622. cryptoAuthDebug0(session, "DROP dupe key packet with same temp key");
  623. return CryptoAuth_DecryptErr_INVALID_PACKET;
  624. }
  625. } else if (nonce == Nonce_REPEAT_KEY && session->nextNonce >= CryptoAuth_State_RECEIVED_KEY) {
  626. // Got a repeat key packet, make sure the temp key is the same as the one we know.
  627. if (Bits_memcmp(session->herTempPubKey, header->encryptedTempKey, 32)) {
  628. Assert_true(!Bits_isZero(session->herTempPubKey, 32));
  629. cryptoAuthDebug0(session, "DROP repeat key packet with different temp key");
  630. return CryptoAuth_DecryptErr_INVALID_PACKET;
  631. }
  632. }
  633. // If Alice sent a hello packet then Bob sent a hello packet and they crossed on the wire,
  634. // somebody has to yield and the other has to stand firm otherwise they will either deadlock
  635. // each believing their hello packet is superior or they will livelock, each switching to the
  636. // other's session and never synchronizing.
  637. // In this event whoever has the lower permanent public key wins.
  638. // If we receive a (possibly repeat) key packet
  639. if (nextNonce == CryptoAuth_State_RECEIVED_KEY) {
  640. Assert_true(nonce == Nonce_KEY || nonce == Nonce_REPEAT_KEY);
  641. switch (session->nextNonce) {
  642. case CryptoAuth_State_INIT:
  643. case CryptoAuth_State_RECEIVED_HELLO:
  644. case CryptoAuth_State_SENT_KEY: {
  645. cryptoAuthDebug0(session, "DROP stray key packet");
  646. return CryptoAuth_DecryptErr_STRAY_KEY;
  647. }
  648. case CryptoAuth_State_SENT_HELLO: {
  649. Bits_memcpy(session->herTempPubKey, header->encryptedTempKey, 32);
  650. break;
  651. }
  652. case CryptoAuth_State_RECEIVED_KEY: {
  653. if (nonce == Nonce_KEY) {
  654. Bits_memcpy(session->herTempPubKey, header->encryptedTempKey, 32);
  655. } else {
  656. Assert_true(!Bits_memcmp(session->herTempPubKey, header->encryptedTempKey, 32));
  657. }
  658. break;
  659. }
  660. default: {
  661. Assert_true(!session->established);
  662. if (nonce == Nonce_KEY) {
  663. Bits_memcpy(session->herTempPubKey, header->encryptedTempKey, 32);
  664. cryptoAuthDebug0(session, "New key packet, recalculating shared secret");
  665. Assert_ifParanoid(!Bits_isZero(session->ourTempPrivKey, 32));
  666. Assert_ifParanoid(!Bits_isZero(session->herTempPubKey, 32));
  667. getSharedSecret(session->sharedSecret,
  668. session->ourTempPrivKey,
  669. session->herTempPubKey,
  670. NULL,
  671. session->context->logger);
  672. } else {
  673. Assert_true(!Bits_memcmp(session->herTempPubKey, header->encryptedTempKey, 32));
  674. }
  675. nextNonce = session->nextNonce + 1;
  676. cryptoAuthDebug0(session, "New key packet but we are already sending data");
  677. }
  678. }
  679. } else if (nextNonce == CryptoAuth_State_RECEIVED_HELLO) {
  680. Assert_true(nonce == Nonce_HELLO || nonce == Nonce_REPEAT_HELLO);
  681. if (Bits_memcmp(session->herTempPubKey, header->encryptedTempKey, 32)) {
  682. // fresh new hello packet, we should reset the session.
  683. switch (session->nextNonce) {
  684. case CryptoAuth_State_SENT_HELLO: {
  685. if (Bits_memcmp(session->pub.herPublicKey,
  686. session->context->pub.publicKey, 32) < 0)
  687. {
  688. // It's a hello and we are the initiator but their permant public key is
  689. // numerically lower than ours, this is so that in the event of two hello
  690. // packets crossing on the wire, the nodes will agree on who is the
  691. // initiator.
  692. cryptoAuthDebug0(session,
  693. "Incoming hello from node with lower key, resetting");
  694. reset(session);
  695. Bits_memcpy(session->herTempPubKey, header->encryptedTempKey, 32);
  696. break;
  697. } else {
  698. // We are the initiator and thus we are sending HELLO packets, however they
  699. // have sent a hello to us and we already sent a HELLO
  700. // We accept the packet (return 0) but we do not alter the state because
  701. // we have our own state and we will respond with our (key) packet.
  702. cryptoAuthDebug0(session,
  703. "Incoming hello from node with higher key, not resetting");
  704. return 0;
  705. }
  706. }
  707. case CryptoAuth_State_INIT: {
  708. Bits_memcpy(session->herTempPubKey, header->encryptedTempKey, 32);
  709. break;
  710. }
  711. default: {
  712. cryptoAuthDebug0(session, "Incoming hello packet resetting session");
  713. reset(session);
  714. Bits_memcpy(session->herTempPubKey, header->encryptedTempKey, 32);
  715. break;
  716. }
  717. }
  718. } else {
  719. // received a hello packet with the same key as the session we already know...
  720. switch (session->nextNonce) {
  721. case CryptoAuth_State_RECEIVED_HELLO:
  722. case CryptoAuth_State_SENT_KEY: {
  723. nextNonce = session->nextNonce;
  724. break;
  725. }
  726. default: {
  727. cryptoAuthDebug0(session, "DROP Incoming repeat hello");
  728. // We already know the key which is being used for this hello packet and
  729. // our state has advanced past RECEIVED_HELLO or SENT_KEY or perhaps we
  730. // are the initiator of this session and they're sending us what should
  731. // be a key packet but is marked as hello, it's all invalid.
  732. return CryptoAuth_DecryptErr_INVALID_PACKET;
  733. }
  734. }
  735. }
  736. } else {
  737. Assert_failure("should never happen");
  738. }
  739. // Nonces can never go backward and can only "not advance" if they're 0,1,2,3,4 session state.
  740. Assert_true(session->nextNonce < nextNonce ||
  741. (session->nextNonce <= CryptoAuth_State_RECEIVED_KEY && nextNonce == session->nextNonce)
  742. );
  743. session->nextNonce = nextNonce;
  744. Bits_memset(&session->pub.replayProtector, 0, sizeof(struct ReplayProtector));
  745. return 0;
  746. }
  747. /** @return 0 on success, -1 otherwise. */
  748. enum CryptoAuth_DecryptErr CryptoAuth_decrypt(struct CryptoAuth_Session* sessionPub,
  749. struct Message* msg)
  750. {
  751. struct CryptoAuth_Session_pvt* session =
  752. Identity_check((struct CryptoAuth_Session_pvt*) sessionPub);
  753. struct CryptoHeader* header = (struct CryptoHeader*) msg->bytes;
  754. if (msg->length < 20) {
  755. cryptoAuthDebug0(session, "DROP runt");
  756. return CryptoAuth_DecryptErr_RUNT;
  757. }
  758. Assert_true(msg->padding >= 12 || "need at least 12 bytes of padding in incoming message");
  759. Assert_true(!((uintptr_t)msg->bytes % 4) || !"alignment fault");
  760. Assert_true(!(msg->capacity % 4) || !"length fault");
  761. Er_assert(Message_eshift(msg, -4));
  762. uint32_t nonce = Endian_bigEndianToHost32(header->nonce);
  763. if (!session->established) {
  764. if (nonce >= Nonce_FIRST_TRAFFIC_PACKET) {
  765. if (session->nextNonce < CryptoAuth_State_SENT_KEY) {
  766. // This is impossible because we have not exchanged hello and key messages.
  767. cryptoAuthDebug0(session, "DROP Received a run message to an un-setup session");
  768. return CryptoAuth_DecryptErr_NO_SESSION;
  769. }
  770. cryptoAuthDebug(session, "Trying final handshake step, nonce=%u\n", nonce);
  771. uint8_t secret[32];
  772. Assert_ifParanoid(!Bits_isZero(session->ourTempPrivKey, 32));
  773. Assert_ifParanoid(!Bits_isZero(session->herTempPubKey, 32));
  774. getSharedSecret(secret,
  775. session->ourTempPrivKey,
  776. session->herTempPubKey,
  777. NULL,
  778. session->context->logger);
  779. enum CryptoAuth_DecryptErr ret = decryptMessage(session, nonce, msg, secret);
  780. // This prevents a few "ghost" dropped packets at the beginning of a session.
  781. session->pub.replayProtector.baseOffset = nonce + 1;
  782. session->pub.replayProtector.bitfield = 0;
  783. if (!ret) {
  784. cryptoAuthDebug0(session, "Final handshake step succeeded");
  785. Bits_memcpy(session->sharedSecret, secret, 32);
  786. // Now we're in run mode, no more handshake packets will be accepted
  787. session->established = true;
  788. session->nextNonce += 3;
  789. updateTime(session, msg);
  790. return 0;
  791. }
  792. cryptoAuthDebug0(session, "DROP Final handshake step failed");
  793. return ret;
  794. }
  795. Er_assert(Message_eshift(msg, 4));
  796. return decryptHandshake(session, nonce, msg, header);
  797. } else if (nonce >= Nonce_FIRST_TRAFFIC_PACKET) {
  798. Assert_ifParanoid(!Bits_isZero(session->sharedSecret, 32));
  799. enum CryptoAuth_DecryptErr ret = decryptMessage(session, nonce, msg, session->sharedSecret);
  800. if (!ret) {
  801. updateTime(session, msg);
  802. return 0;
  803. } else {
  804. cryptoAuthDebug(session, "DROP Failed to [%s] message",
  805. ((ret == CryptoAuth_DecryptErr_REPLAY) ? "replay check" : "decrypt"));
  806. return ret;
  807. }
  808. } else if (nonce <= Nonce_REPEAT_HELLO) {
  809. cryptoAuthDebug(session, "hello packet during established session nonce=[%d]", nonce);
  810. Er_assert(Message_eshift(msg, 4));
  811. return decryptHandshake(session, nonce, msg, header);
  812. } else {
  813. cryptoAuthDebug(session, "DROP key packet during established session nonce=[%d]", nonce);
  814. return CryptoAuth_DecryptErr_KEY_PKT_ESTABLISHED_SESSION;
  815. }
  816. Assert_failure("unreachable");
  817. }
  818. /////////////////////////////////////////////////////////////////////////////////////////////////
  819. struct CryptoAuth* CryptoAuth_new(struct Allocator* allocator,
  820. const uint8_t* privateKey,
  821. struct EventBase* eventBase,
  822. struct Log* logger,
  823. struct Random* rand)
  824. {
  825. struct CryptoAuth_pvt* ca = Allocator_calloc(allocator, sizeof(struct CryptoAuth_pvt), 1);
  826. Identity_set(ca);
  827. ca->allocator = allocator;
  828. ca->eventBase = eventBase;
  829. ca->logger = logger;
  830. ca->rand = rand;
  831. if (privateKey != NULL) {
  832. Bits_memcpy(ca->privateKey, privateKey, 32);
  833. } else {
  834. Random_bytes(rand, ca->privateKey, 32);
  835. }
  836. crypto_scalarmult_curve25519_base(ca->pub.publicKey, ca->privateKey);
  837. if (Defined(Log_KEYS)) {
  838. uint8_t publicKeyHex[65];
  839. printHexKey(publicKeyHex, ca->pub.publicKey);
  840. uint8_t privateKeyHex[65];
  841. printHexKey(privateKeyHex, ca->privateKey);
  842. Log_keys(logger,
  843. "Initialized CryptoAuth:\n myPrivateKey=%s\n myPublicKey=%s\n",
  844. privateKeyHex,
  845. publicKeyHex);
  846. }
  847. return &ca->pub;
  848. }
  849. int CryptoAuth_addUser_ipv6(String* password,
  850. String* login,
  851. uint8_t ipv6[16],
  852. struct CryptoAuth* cryptoAuth)
  853. {
  854. struct CryptoAuth_pvt* ca = Identity_check((struct CryptoAuth_pvt*) cryptoAuth);
  855. struct Allocator* alloc = Allocator_child(ca->allocator);
  856. struct CryptoAuth_User* user = Allocator_calloc(alloc, sizeof(struct CryptoAuth_User), 1);
  857. user->alloc = alloc;
  858. Identity_set(user);
  859. if (!login) {
  860. int i = 0;
  861. for (struct CryptoAuth_User* u = ca->users; u; u = u->next) { i++; }
  862. user->login = login = String_printf(alloc, "Anon #%d", i);
  863. } else {
  864. user->login = String_clone(login, alloc);
  865. }
  866. struct CryptoHeader_Challenge ac;
  867. // Users specified with a login field might want to use authType 1 still.
  868. hashPassword(user->secret, &ac, login, password, 2);
  869. Bits_memcpy(user->userNameHash, &ac, CryptoHeader_Challenge_KEYSIZE);
  870. hashPassword(user->secret, &ac, NULL, password, 1);
  871. Bits_memcpy(user->passwordHash, &ac, CryptoHeader_Challenge_KEYSIZE);
  872. for (struct CryptoAuth_User* u = ca->users; u; u = u->next) {
  873. if (Bits_memcmp(user->secret, u->secret, 32)) {
  874. } else if (!login) {
  875. } else if (String_equals(login, u->login)) {
  876. Allocator_free(alloc);
  877. return CryptoAuth_addUser_DUPLICATE;
  878. }
  879. }
  880. if (ipv6) {
  881. Bits_memcpy(user->restrictedToip6, ipv6, 16);
  882. }
  883. // Add the user to the *end* of the list
  884. for (struct CryptoAuth_User** up = &ca->users; ; up = &(*up)->next) {
  885. if (!*up) {
  886. *up = user;
  887. break;
  888. }
  889. }
  890. return 0;
  891. }
  892. int CryptoAuth_removeUsers(struct CryptoAuth* context, String* login)
  893. {
  894. struct CryptoAuth_pvt* ca = Identity_check((struct CryptoAuth_pvt*) context);
  895. int count = 0;
  896. struct CryptoAuth_User** up = &ca->users;
  897. struct CryptoAuth_User* u = *up;
  898. while ((u = *up)) {
  899. if (!login || String_equals(login, u->login)) {
  900. *up = u->next;
  901. Allocator_free(u->alloc);
  902. count++;
  903. } else {
  904. up = &u->next;
  905. }
  906. }
  907. if (!login) {
  908. Log_debug(ca->logger, "Flushing [%d] users", count);
  909. } else {
  910. Log_debug(ca->logger, "Removing [%d] user(s) identified by [%s]", count, login->bytes);
  911. }
  912. return count;
  913. }
  914. struct StringList* CryptoAuth_getUsers(struct CryptoAuth* context, struct Allocator* alloc)
  915. {
  916. struct CryptoAuth_pvt* ca = Identity_check((struct CryptoAuth_pvt*) context);
  917. struct StringList* users = StringList_new(alloc);
  918. for (struct CryptoAuth_User* u = ca->users; u; u = u->next) {
  919. StringList_add(users, String_clone(u->login, alloc));
  920. }
  921. return users;
  922. }
  923. struct CryptoAuth_Session* CryptoAuth_newSession(struct CryptoAuth* ca,
  924. struct Allocator* alloc,
  925. const uint8_t herPublicKey[32],
  926. const bool requireAuth,
  927. char* displayName)
  928. {
  929. struct CryptoAuth_pvt* context = Identity_check((struct CryptoAuth_pvt*) ca);
  930. struct CryptoAuth_Session_pvt* session =
  931. Allocator_calloc(alloc, sizeof(struct CryptoAuth_Session_pvt), 1);
  932. Identity_set(session);
  933. session->context = context;
  934. session->requireAuth = requireAuth;
  935. session->pub.displayName = displayName ? String_new(displayName, alloc) : NULL;
  936. session->timeOfLastPacket = Time_currentTimeSeconds(context->eventBase);
  937. session->alloc = alloc;
  938. session->pub.resetAfterInactivitySeconds = CryptoAuth_DEFAULT_RESET_AFTER_INACTIVITY_SECONDS;
  939. session->pub.setupResetAfterInactivitySeconds =
  940. CryptoAuth_DEFAULT_SETUP_RESET_AFTER_INACTIVITY_SECONDS;
  941. Assert_true(herPublicKey);
  942. Bits_memcpy(session->pub.herPublicKey, herPublicKey, 32);
  943. uint8_t calculatedIp6[16];
  944. AddressCalc_addressForPublicKey(calculatedIp6, herPublicKey);
  945. Bits_memcpy(session->pub.herIp6, calculatedIp6, 16);
  946. return &session->pub;
  947. }
  948. void CryptoAuth_setAuth(const String* password,
  949. const String* login,
  950. struct CryptoAuth_Session* caSession)
  951. {
  952. struct CryptoAuth_Session_pvt* session =
  953. Identity_check((struct CryptoAuth_Session_pvt*)caSession);
  954. if (!password && (session->password || session->authType)) {
  955. if (session->passwdAlloc) {
  956. Allocator_free(session->passwdAlloc);
  957. session->passwdAlloc = NULL;
  958. }
  959. session->password = NULL;
  960. session->authType = 0;
  961. } else if (!session->password || !String_equals(session->password, password)) {
  962. if (session->passwdAlloc) {
  963. Allocator_free(session->passwdAlloc);
  964. }
  965. session->passwdAlloc = Allocator_child(session->alloc);
  966. session->password = String_clone(password, session->passwdAlloc);
  967. session->authType = 1;
  968. if (login) {
  969. session->authType = 2;
  970. if (session->loginAlloc) {
  971. Allocator_free(session->loginAlloc);
  972. }
  973. session->loginAlloc = Allocator_child(session->alloc);
  974. session->login = String_clone(login, session->loginAlloc);
  975. }
  976. } else {
  977. return;
  978. }
  979. reset(session);
  980. }
  981. enum CryptoAuth_State CryptoAuth_getState(struct CryptoAuth_Session* caSession)
  982. {
  983. struct CryptoAuth_Session_pvt* session =
  984. Identity_check((struct CryptoAuth_Session_pvt*)caSession);
  985. if (session->nextNonce <= CryptoAuth_State_RECEIVED_KEY) {
  986. return session->nextNonce;
  987. }
  988. return (session->established) ? CryptoAuth_State_ESTABLISHED : CryptoAuth_State_RECEIVED_KEY;
  989. }
  990. void CryptoAuth_resetIfTimeout(struct CryptoAuth_Session* caSession)
  991. {
  992. struct CryptoAuth_Session_pvt* session =
  993. Identity_check((struct CryptoAuth_Session_pvt*)caSession);
  994. resetIfTimeout(session);
  995. }
  996. void CryptoAuth_reset(struct CryptoAuth_Session* caSession)
  997. {
  998. struct CryptoAuth_Session_pvt* session =
  999. Identity_check((struct CryptoAuth_Session_pvt*)caSession);
  1000. reset(session);
  1001. }
  1002. // For testing:
  1003. void CryptoAuth_encryptRndNonce(uint8_t nonce[24], struct Message* msg, uint8_t secret[32])
  1004. {
  1005. encryptRndNonce(nonce, msg, secret);
  1006. }
  1007. int CryptoAuth_decryptRndNonce(uint8_t nonce[24], struct Message* msg, uint8_t secret[32])
  1008. {
  1009. return decryptRndNonce(nonce, msg, secret);
  1010. }