1
0

CryptoAuth.c 44 KB

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