1
0

CryptoAuth.c 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135
  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. Er_assert(Message_eshift(msg, -16));
  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. Er_assert(Message_eshift(msg, 16));
  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. Er_assert(Message_eshift(message, CryptoHeader_SIZE));
  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 (auth: %d)",
  368. ((session->nextNonce & 1) ? "repeat " : ""),
  369. ((session->nextNonce < CryptoAuth_State_RECEIVED_HELLO) ? "hello" : "key"),
  370. (passwordHash != NULL));
  371. uint8_t sharedSecret[32];
  372. if (session->nextNonce < CryptoAuth_State_RECEIVED_HELLO) {
  373. getSharedSecret(sharedSecret,
  374. session->context->privateKey,
  375. session->pub.herPublicKey,
  376. passwordHash,
  377. session->context->logger);
  378. session->isInitiator = true;
  379. Assert_true(session->nextNonce <= CryptoAuth_State_SENT_HELLO);
  380. session->nextNonce = CryptoAuth_State_SENT_HELLO;
  381. } else {
  382. // Handshake2
  383. // herTempPubKey was set by decryptHandshake()
  384. Assert_ifParanoid(!Bits_isZero(session->herTempPubKey, 32));
  385. getSharedSecret(sharedSecret,
  386. session->context->privateKey,
  387. session->herTempPubKey,
  388. passwordHash,
  389. session->context->logger);
  390. Assert_true(session->nextNonce <= CryptoAuth_State_SENT_KEY);
  391. session->nextNonce = CryptoAuth_State_SENT_KEY;
  392. if (Defined(Log_KEYS)) {
  393. uint8_t tempKeyHex[65];
  394. Hex_encode(tempKeyHex, 65, session->herTempPubKey, 32);
  395. Log_keys(session->context->logger,
  396. "Using their temp public key:\n"
  397. " %s\n",
  398. tempKeyHex);
  399. }
  400. }
  401. Assert_true((session->nextNonce < CryptoAuth_State_RECEIVED_HELLO) ==
  402. Bits_isZero(session->herTempPubKey, 32));
  403. // Shift message over the encryptedTempKey field.
  404. Er_assert(Message_eshift(message, 32 - CryptoHeader_SIZE));
  405. encryptRndNonce(header->handshakeNonce, message, sharedSecret);
  406. if (Defined(Log_KEYS)) {
  407. uint8_t sharedSecretHex[65];
  408. printHexKey(sharedSecretHex, sharedSecret);
  409. uint8_t nonceHex[49];
  410. Hex_encode(nonceHex, 49, header->handshakeNonce, 24);
  411. uint8_t cipherHex[65];
  412. printHexKey(cipherHex, message->bytes);
  413. Log_keys(session->context->logger,
  414. "Encrypting message with:\n"
  415. " nonce: %s\n"
  416. " secret: %s\n"
  417. " cipher: %s\n",
  418. nonceHex, sharedSecretHex, cipherHex);
  419. }
  420. // Shift it back -- encryptRndNonce adds 16 bytes of authenticator.
  421. Er_assert(Message_eshift(message, CryptoHeader_SIZE - 32 - 16));
  422. }
  423. /** @return 0 on success, -1 otherwise. */
  424. int CryptoAuth_encrypt(struct CryptoAuth_Session* sessionPub, struct Message* msg)
  425. {
  426. struct CryptoAuth_Session_pvt* session =
  427. Identity_check((struct CryptoAuth_Session_pvt*) sessionPub);
  428. // If there has been no incoming traffic for a while, reset the connection to state 0.
  429. // This will prevent "connection in bad state" situations from lasting forever.
  430. // this will reset the session if it has timed out.
  431. resetIfTimeout(session);
  432. // If the nonce wraps, start over.
  433. if (session->nextNonce >= 0xfffffff0) {
  434. reset(session);
  435. }
  436. Assert_true(!((uintptr_t)msg->bytes % 4) || !"alignment fault");
  437. // nextNonce 0: sending hello, we are initiating connection.
  438. // nextNonce 1: sending another hello, nothing received yet.
  439. // nextNonce 2: sending key, hello received.
  440. // nextNonce 3: sending key again, no data packet recieved yet.
  441. // nextNonce >3: handshake complete
  442. //
  443. // if it's a blind handshake, every message will be empty and nextNonce will remain
  444. // zero until the first message is received back.
  445. if (session->nextNonce <= CryptoAuth_State_RECEIVED_KEY) {
  446. if (session->nextNonce < CryptoAuth_State_RECEIVED_KEY) {
  447. encryptHandshake(msg, session, 0);
  448. return 0;
  449. } else {
  450. cryptoAuthDebug0(session, "Doing final step to send message. nonce=4");
  451. Assert_ifParanoid(!Bits_isZero(session->ourTempPrivKey, 32));
  452. Assert_ifParanoid(!Bits_isZero(session->herTempPubKey, 32));
  453. getSharedSecret(session->sharedSecret,
  454. session->ourTempPrivKey,
  455. session->herTempPubKey,
  456. NULL,
  457. session->context->logger);
  458. }
  459. }
  460. Assert_true(msg->length > 0 && "Empty packet during handshake");
  461. Assert_true(msg->padding >= 36 || !"not enough padding");
  462. encrypt(session->nextNonce, msg, session->sharedSecret, session->isInitiator);
  463. Er_assert(Message_epush32be(msg, session->nextNonce));
  464. session->nextNonce++;
  465. return 0;
  466. }
  467. /** Call the external interface and tell it that a message has been received. */
  468. static inline void updateTime(struct CryptoAuth_Session_pvt* session, struct Message* message)
  469. {
  470. session->timeOfLastPacket = Time_currentTimeSeconds(session->context->eventBase);
  471. }
  472. static inline enum CryptoAuth_DecryptErr decryptMessage(struct CryptoAuth_Session_pvt* session,
  473. uint32_t nonce,
  474. struct Message* content,
  475. uint8_t secret[32])
  476. {
  477. // Decrypt with authentication and replay prevention.
  478. if (decrypt(nonce, content, secret, session->isInitiator)) {
  479. cryptoAuthDebug0(session, "DROP authenticated decryption failed");
  480. return CryptoAuth_DecryptErr_DECRYPT;
  481. }
  482. if (!ReplayProtector_checkNonce(nonce, &session->pub.replayProtector)) {
  483. cryptoAuthDebug(session, "DROP nonce checking failed nonce=[%u]", nonce);
  484. return CryptoAuth_DecryptErr_REPLAY;
  485. }
  486. return 0;
  487. }
  488. static bool ip6MatchesKey(uint8_t ip6[16], uint8_t key[32])
  489. {
  490. uint8_t calculatedIp6[16];
  491. AddressCalc_addressForPublicKey(calculatedIp6, key);
  492. return !Bits_memcmp(ip6, calculatedIp6, 16);
  493. }
  494. static enum CryptoAuth_DecryptErr decryptHandshake(struct CryptoAuth_Session_pvt* session,
  495. const uint32_t nonce,
  496. struct Message* message,
  497. struct CryptoHeader* header)
  498. {
  499. if (message->length < CryptoHeader_SIZE) {
  500. cryptoAuthDebug0(session, "DROP runt");
  501. return CryptoAuth_DecryptErr_RUNT;
  502. }
  503. // handshake
  504. // nextNonce 0: recieving hello.
  505. // nextNonce 1: recieving key, we sent hello.
  506. // nextNonce 2: recieving first data packet or duplicate hello.
  507. // nextNonce 3: recieving first data packet.
  508. // nextNonce >3: handshake complete
  509. Assert_true(knowHerKey(session));
  510. if (Bits_memcmp(session->pub.herPublicKey, header->publicKey, 32)) {
  511. cryptoAuthDebug0(session, "DROP a packet with different public key than this session");
  512. return CryptoAuth_DecryptErr_WRONG_PERM_PUBKEY;
  513. }
  514. Assert_true((session->nextNonce < CryptoAuth_State_RECEIVED_HELLO) ==
  515. Bits_isZero(session->herTempPubKey, 32));
  516. struct CryptoAuth_User* userObj = getAuth(&header->auth, session->context);
  517. uint8_t* restrictedToip6 = NULL;
  518. uint8_t* passwordHash = NULL;
  519. if (userObj) {
  520. passwordHash = userObj->secret;
  521. if (userObj->restrictedToip6[0]) {
  522. restrictedToip6 = userObj->restrictedToip6;
  523. if (!ip6MatchesKey(restrictedToip6, session->pub.herPublicKey)) {
  524. cryptoAuthDebug0(session, "DROP packet with key not matching restrictedToip6");
  525. return CryptoAuth_DecryptErr_IP_RESTRICTED;
  526. }
  527. }
  528. }
  529. if (session->requireAuth && !userObj) {
  530. cryptoAuthDebug0(session, "DROP message because auth was not given");
  531. return CryptoAuth_DecryptErr_AUTH_REQUIRED;
  532. }
  533. if (!userObj && header->auth.type != 0) {
  534. cryptoAuthDebug0(session, "DROP message with unrecognized authenticator");
  535. return CryptoAuth_DecryptErr_UNRECOGNIZED_AUTH;
  536. }
  537. // What the nextNonce will become if this packet is valid.
  538. uint32_t nextNonce;
  539. // The secret for decrypting this message.
  540. uint8_t sharedSecret[32];
  541. if (nonce < Nonce_KEY) { // HELLO or REPEAT_HELLO
  542. cryptoAuthDebug(session, "Received a %shello packet, using auth: %d",
  543. (nonce == Nonce_REPEAT_HELLO) ? "repeat " : "",
  544. (userObj != NULL));
  545. getSharedSecret(sharedSecret,
  546. session->context->privateKey,
  547. session->pub.herPublicKey,
  548. passwordHash,
  549. session->context->logger);
  550. nextNonce = CryptoAuth_State_RECEIVED_HELLO;
  551. } else {
  552. if (nonce == Nonce_KEY) {
  553. cryptoAuthDebug0(session, "Received a key packet");
  554. } else {
  555. Assert_true(nonce == Nonce_REPEAT_KEY);
  556. cryptoAuthDebug0(session, "Received a repeat key packet");
  557. }
  558. if (!session->isInitiator) {
  559. cryptoAuthDebug0(session, "DROP a stray key packet");
  560. return CryptoAuth_DecryptErr_STRAY_KEY;
  561. }
  562. // We sent the hello, this is a key
  563. getSharedSecret(sharedSecret,
  564. session->ourTempPrivKey,
  565. session->pub.herPublicKey,
  566. passwordHash,
  567. session->context->logger);
  568. nextNonce = CryptoAuth_State_RECEIVED_KEY;
  569. }
  570. // Shift it on top of the authenticator before the encrypted public key
  571. Er_assert(Message_eshift(message, 48 - CryptoHeader_SIZE));
  572. if (Defined(Log_KEYS)) {
  573. uint8_t sharedSecretHex[65];
  574. printHexKey(sharedSecretHex, sharedSecret);
  575. uint8_t nonceHex[49];
  576. Hex_encode(nonceHex, 49, header->handshakeNonce, 24);
  577. uint8_t cipherHex[65];
  578. printHexKey(cipherHex, message->bytes);
  579. Log_keys(session->context->logger,
  580. "Decrypting message with:\n"
  581. " nonce: %s\n"
  582. " secret: %s\n"
  583. " cipher: %s\n",
  584. nonceHex, sharedSecretHex, cipherHex);
  585. }
  586. // Decrypt her temp public key and the message.
  587. if (decryptRndNonce(header->handshakeNonce, message, sharedSecret)) {
  588. // just in case
  589. Bits_memset(header, 0, CryptoHeader_SIZE);
  590. cryptoAuthDebug(session, "DROP message with nonce [%d], decryption failed", nonce);
  591. return CryptoAuth_DecryptErr_HANDSHAKE_DECRYPT_FAILED;
  592. }
  593. if (Bits_isZero(header->encryptedTempKey, 32)) {
  594. // we need to reject 0 public keys outright because they will be confused with "unknown"
  595. cryptoAuthDebug0(session, "DROP message with zero as temp public key");
  596. return CryptoAuth_DecryptErr_WISEGUY;
  597. }
  598. if (Defined(Log_KEYS)) {
  599. uint8_t tempKeyHex[65];
  600. Hex_encode(tempKeyHex, 65, header->encryptedTempKey, 32);
  601. Log_keys(session->context->logger,
  602. "Unwrapping temp public key:\n"
  603. " %s\n",
  604. tempKeyHex);
  605. }
  606. Er_assert(Message_eshift(message, -32));
  607. // Post-decryption checking
  608. if (nonce == Nonce_HELLO) {
  609. // A new hello packet
  610. if (!Bits_memcmp(session->herTempPubKey, header->encryptedTempKey, 32)) {
  611. // possible replay attack or duped packet
  612. cryptoAuthDebug0(session, "DROP dupe hello packet with same temp key");
  613. return CryptoAuth_DecryptErr_INVALID_PACKET;
  614. }
  615. } else if (nonce == Nonce_KEY && session->nextNonce >= CryptoAuth_State_RECEIVED_KEY) {
  616. // we accept a new key packet and let it change the session since the other end might have
  617. // killed off the session while it was in the midst of setting up.
  618. // This is NOT a repeat key packet because it's nonce is 2, not 3
  619. if (!Bits_memcmp(session->herTempPubKey, header->encryptedTempKey, 32)) {
  620. Assert_true(!Bits_isZero(session->herTempPubKey, 32));
  621. cryptoAuthDebug0(session, "DROP dupe key packet with same temp key");
  622. return CryptoAuth_DecryptErr_INVALID_PACKET;
  623. }
  624. } else if (nonce == Nonce_REPEAT_KEY && session->nextNonce >= CryptoAuth_State_RECEIVED_KEY) {
  625. // Got a repeat key packet, make sure the temp key is the same as the one we know.
  626. if (Bits_memcmp(session->herTempPubKey, header->encryptedTempKey, 32)) {
  627. Assert_true(!Bits_isZero(session->herTempPubKey, 32));
  628. cryptoAuthDebug0(session, "DROP repeat key packet with different temp key");
  629. return CryptoAuth_DecryptErr_INVALID_PACKET;
  630. }
  631. }
  632. // If Alice sent a hello packet then Bob sent a hello packet and they crossed on the wire,
  633. // somebody has to yield and the other has to stand firm otherwise they will either deadlock
  634. // each believing their hello packet is superior or they will livelock, each switching to the
  635. // other's session and never synchronizing.
  636. // In this event whoever has the lower permanent public key wins.
  637. // If we receive a (possibly repeat) key packet
  638. if (nextNonce == CryptoAuth_State_RECEIVED_KEY) {
  639. Assert_true(nonce == Nonce_KEY || nonce == Nonce_REPEAT_KEY);
  640. switch (session->nextNonce) {
  641. case CryptoAuth_State_INIT:
  642. case CryptoAuth_State_RECEIVED_HELLO:
  643. case CryptoAuth_State_SENT_KEY: {
  644. cryptoAuthDebug0(session, "DROP stray key packet");
  645. return CryptoAuth_DecryptErr_STRAY_KEY;
  646. }
  647. case CryptoAuth_State_SENT_HELLO: {
  648. Bits_memcpy(session->herTempPubKey, header->encryptedTempKey, 32);
  649. break;
  650. }
  651. case CryptoAuth_State_RECEIVED_KEY: {
  652. if (nonce == Nonce_KEY) {
  653. Bits_memcpy(session->herTempPubKey, header->encryptedTempKey, 32);
  654. } else {
  655. Assert_true(!Bits_memcmp(session->herTempPubKey, header->encryptedTempKey, 32));
  656. }
  657. break;
  658. }
  659. default: {
  660. Assert_true(!session->established);
  661. if (nonce == Nonce_KEY) {
  662. Bits_memcpy(session->herTempPubKey, header->encryptedTempKey, 32);
  663. cryptoAuthDebug0(session, "New key packet, recalculating shared secret");
  664. Assert_ifParanoid(!Bits_isZero(session->ourTempPrivKey, 32));
  665. Assert_ifParanoid(!Bits_isZero(session->herTempPubKey, 32));
  666. getSharedSecret(session->sharedSecret,
  667. session->ourTempPrivKey,
  668. session->herTempPubKey,
  669. NULL,
  670. session->context->logger);
  671. } else {
  672. Assert_true(!Bits_memcmp(session->herTempPubKey, header->encryptedTempKey, 32));
  673. }
  674. nextNonce = session->nextNonce + 1;
  675. cryptoAuthDebug0(session, "New key packet but we are already sending data");
  676. }
  677. }
  678. } else if (nextNonce == CryptoAuth_State_RECEIVED_HELLO) {
  679. Assert_true(nonce == Nonce_HELLO || nonce == Nonce_REPEAT_HELLO);
  680. if (Bits_memcmp(session->herTempPubKey, header->encryptedTempKey, 32)) {
  681. // fresh new hello packet, we should reset the session.
  682. switch (session->nextNonce) {
  683. case CryptoAuth_State_SENT_HELLO: {
  684. if (Bits_memcmp(session->pub.herPublicKey,
  685. session->context->pub.publicKey, 32) < 0)
  686. {
  687. // It's a hello and we are the initiator but their permant public key is
  688. // numerically lower than ours, this is so that in the event of two hello
  689. // packets crossing on the wire, the nodes will agree on who is the
  690. // initiator.
  691. cryptoAuthDebug0(session,
  692. "Incoming hello from node with lower key, resetting");
  693. reset(session);
  694. Bits_memcpy(session->herTempPubKey, header->encryptedTempKey, 32);
  695. break;
  696. } else {
  697. // We are the initiator and thus we are sending HELLO packets, however they
  698. // have sent a hello to us and we already sent a HELLO
  699. // We accept the packet (return 0) but we do not alter the state because
  700. // we have our own state and we will respond with our (key) packet.
  701. cryptoAuthDebug0(session,
  702. "Incoming hello from node with higher key, not resetting");
  703. return 0;
  704. }
  705. }
  706. case CryptoAuth_State_INIT: {
  707. Bits_memcpy(session->herTempPubKey, header->encryptedTempKey, 32);
  708. break;
  709. }
  710. default: {
  711. cryptoAuthDebug0(session, "Incoming hello packet resetting session");
  712. reset(session);
  713. Bits_memcpy(session->herTempPubKey, header->encryptedTempKey, 32);
  714. break;
  715. }
  716. }
  717. } else {
  718. // received a hello packet with the same key as the session we already know...
  719. switch (session->nextNonce) {
  720. case CryptoAuth_State_RECEIVED_HELLO:
  721. case CryptoAuth_State_SENT_KEY: {
  722. nextNonce = session->nextNonce;
  723. break;
  724. }
  725. default: {
  726. cryptoAuthDebug0(session, "DROP Incoming repeat hello");
  727. // We already know the key which is being used for this hello packet and
  728. // our state has advanced past RECEIVED_HELLO or SENT_KEY or perhaps we
  729. // are the initiator of this session and they're sending us what should
  730. // be a key packet but is marked as hello, it's all invalid.
  731. return CryptoAuth_DecryptErr_INVALID_PACKET;
  732. }
  733. }
  734. }
  735. } else {
  736. Assert_failure("should never happen");
  737. }
  738. // Nonces can never go backward and can only "not advance" if they're 0,1,2,3,4 session state.
  739. Assert_true(session->nextNonce < nextNonce ||
  740. (session->nextNonce <= CryptoAuth_State_RECEIVED_KEY && nextNonce == session->nextNonce)
  741. );
  742. session->nextNonce = nextNonce;
  743. Bits_memset(&session->pub.replayProtector, 0, sizeof(struct ReplayProtector));
  744. return 0;
  745. }
  746. /** @return 0 on success, -1 otherwise. */
  747. enum CryptoAuth_DecryptErr CryptoAuth_decrypt(struct CryptoAuth_Session* sessionPub,
  748. struct Message* msg)
  749. {
  750. struct CryptoAuth_Session_pvt* session =
  751. Identity_check((struct CryptoAuth_Session_pvt*) sessionPub);
  752. struct CryptoHeader* header = (struct CryptoHeader*) msg->bytes;
  753. if (msg->length < 20) {
  754. cryptoAuthDebug0(session, "DROP runt");
  755. return CryptoAuth_DecryptErr_RUNT;
  756. }
  757. Assert_true(msg->padding >= 12 || "need at least 12 bytes of padding in incoming message");
  758. Assert_true(!((uintptr_t)msg->bytes % 4) || !"alignment fault");
  759. Assert_true(!(msg->capacity % 4) || !"length fault");
  760. Er_assert(Message_eshift(msg, -4));
  761. uint32_t nonce = Endian_bigEndianToHost32(header->nonce);
  762. if (!session->established) {
  763. if (nonce >= Nonce_FIRST_TRAFFIC_PACKET) {
  764. if (session->nextNonce < CryptoAuth_State_SENT_KEY) {
  765. // This is impossible because we have not exchanged hello and key messages.
  766. cryptoAuthDebug0(session, "DROP Received a run message to an un-setup session");
  767. return CryptoAuth_DecryptErr_NO_SESSION;
  768. }
  769. cryptoAuthDebug(session, "Trying final handshake step, nonce=%u\n", nonce);
  770. uint8_t secret[32];
  771. Assert_ifParanoid(!Bits_isZero(session->ourTempPrivKey, 32));
  772. Assert_ifParanoid(!Bits_isZero(session->herTempPubKey, 32));
  773. getSharedSecret(secret,
  774. session->ourTempPrivKey,
  775. session->herTempPubKey,
  776. NULL,
  777. session->context->logger);
  778. enum CryptoAuth_DecryptErr ret = decryptMessage(session, nonce, msg, secret);
  779. // This prevents a few "ghost" dropped packets at the beginning of a session.
  780. session->pub.replayProtector.baseOffset = nonce + 1;
  781. session->pub.replayProtector.bitfield = 0;
  782. if (!ret) {
  783. cryptoAuthDebug0(session, "Final handshake step succeeded");
  784. Bits_memcpy(session->sharedSecret, secret, 32);
  785. // Now we're in run mode, no more handshake packets will be accepted
  786. session->established = true;
  787. session->nextNonce += 3;
  788. updateTime(session, msg);
  789. return 0;
  790. }
  791. cryptoAuthDebug0(session, "DROP Final handshake step failed");
  792. return ret;
  793. }
  794. Er_assert(Message_eshift(msg, 4));
  795. return decryptHandshake(session, nonce, msg, header);
  796. } else if (nonce >= Nonce_FIRST_TRAFFIC_PACKET) {
  797. Assert_ifParanoid(!Bits_isZero(session->sharedSecret, 32));
  798. enum CryptoAuth_DecryptErr ret = decryptMessage(session, nonce, msg, session->sharedSecret);
  799. if (!ret) {
  800. updateTime(session, msg);
  801. return 0;
  802. } else {
  803. cryptoAuthDebug(session, "DROP Failed to [%s] message",
  804. ((ret == CryptoAuth_DecryptErr_REPLAY) ? "replay check" : "decrypt"));
  805. return ret;
  806. }
  807. } else if (nonce <= Nonce_REPEAT_HELLO) {
  808. cryptoAuthDebug(session, "hello packet during established session nonce=[%d]", nonce);
  809. Er_assert(Message_eshift(msg, 4));
  810. return decryptHandshake(session, nonce, msg, header);
  811. } else {
  812. cryptoAuthDebug(session, "DROP key packet during established session nonce=[%d]", nonce);
  813. return CryptoAuth_DecryptErr_KEY_PKT_ESTABLISHED_SESSION;
  814. }
  815. Assert_failure("unreachable");
  816. }
  817. /////////////////////////////////////////////////////////////////////////////////////////////////
  818. struct CryptoAuth* CryptoAuth_new(struct Allocator* allocator,
  819. const uint8_t* privateKey,
  820. struct EventBase* eventBase,
  821. struct Log* logger,
  822. struct Random* rand)
  823. {
  824. struct CryptoAuth_pvt* ca = Allocator_calloc(allocator, sizeof(struct CryptoAuth_pvt), 1);
  825. Identity_set(ca);
  826. ca->allocator = allocator;
  827. ca->eventBase = eventBase;
  828. ca->logger = logger;
  829. ca->rand = rand;
  830. if (privateKey != NULL) {
  831. Bits_memcpy(ca->privateKey, privateKey, 32);
  832. } else {
  833. Random_bytes(rand, ca->privateKey, 32);
  834. }
  835. crypto_scalarmult_curve25519_base(ca->pub.publicKey, ca->privateKey);
  836. if (Defined(Log_KEYS)) {
  837. uint8_t publicKeyHex[65];
  838. printHexKey(publicKeyHex, ca->pub.publicKey);
  839. uint8_t privateKeyHex[65];
  840. printHexKey(privateKeyHex, ca->privateKey);
  841. Log_keys(logger,
  842. "Initialized CryptoAuth:\n myPrivateKey=%s\n myPublicKey=%s\n",
  843. privateKeyHex,
  844. publicKeyHex);
  845. }
  846. return &ca->pub;
  847. }
  848. int CryptoAuth_addUser_ipv6(String* password,
  849. String* login,
  850. uint8_t ipv6[16],
  851. struct CryptoAuth* cryptoAuth)
  852. {
  853. struct CryptoAuth_pvt* ca = Identity_check((struct CryptoAuth_pvt*) cryptoAuth);
  854. struct Allocator* alloc = Allocator_child(ca->allocator);
  855. struct CryptoAuth_User* user = Allocator_calloc(alloc, sizeof(struct CryptoAuth_User), 1);
  856. user->alloc = alloc;
  857. Identity_set(user);
  858. if (!login) {
  859. int i = 0;
  860. for (struct CryptoAuth_User* u = ca->users; u; u = u->next) { i++; }
  861. user->login = login = String_printf(alloc, "Anon #%d", i);
  862. } else {
  863. user->login = String_clone(login, alloc);
  864. }
  865. struct CryptoHeader_Challenge ac;
  866. // Users specified with a login field might want to use authType 1 still.
  867. hashPassword(user->secret, &ac, login, password, 2);
  868. Bits_memcpy(user->userNameHash, &ac, CryptoHeader_Challenge_KEYSIZE);
  869. hashPassword(user->secret, &ac, NULL, password, 1);
  870. Bits_memcpy(user->passwordHash, &ac, CryptoHeader_Challenge_KEYSIZE);
  871. for (struct CryptoAuth_User* u = ca->users; u; u = u->next) {
  872. if (Bits_memcmp(user->secret, u->secret, 32)) {
  873. } else if (!login) {
  874. } else if (String_equals(login, u->login)) {
  875. Allocator_free(alloc);
  876. return CryptoAuth_addUser_DUPLICATE;
  877. }
  878. }
  879. if (ipv6) {
  880. Bits_memcpy(user->restrictedToip6, ipv6, 16);
  881. }
  882. // Add the user to the *end* of the list
  883. for (struct CryptoAuth_User** up = &ca->users; ; up = &(*up)->next) {
  884. if (!*up) {
  885. *up = user;
  886. break;
  887. }
  888. }
  889. return 0;
  890. }
  891. int CryptoAuth_removeUsers(struct CryptoAuth* context, String* login)
  892. {
  893. struct CryptoAuth_pvt* ca = Identity_check((struct CryptoAuth_pvt*) context);
  894. int count = 0;
  895. struct CryptoAuth_User** up = &ca->users;
  896. struct CryptoAuth_User* u = *up;
  897. while ((u = *up)) {
  898. if (!login || String_equals(login, u->login)) {
  899. *up = u->next;
  900. Allocator_free(u->alloc);
  901. count++;
  902. } else {
  903. up = &u->next;
  904. }
  905. }
  906. if (!login) {
  907. Log_debug(ca->logger, "Flushing [%d] users", count);
  908. } else {
  909. Log_debug(ca->logger, "Removing [%d] user(s) identified by [%s]", count, login->bytes);
  910. }
  911. return count;
  912. }
  913. struct StringList* CryptoAuth_getUsers(struct CryptoAuth* context, struct Allocator* alloc)
  914. {
  915. struct CryptoAuth_pvt* ca = Identity_check((struct CryptoAuth_pvt*) context);
  916. struct StringList* users = StringList_new(alloc);
  917. for (struct CryptoAuth_User* u = ca->users; u; u = u->next) {
  918. StringList_add(users, String_clone(u->login, alloc));
  919. }
  920. return users;
  921. }
  922. struct CryptoAuth_Session* CryptoAuth_newSession(struct CryptoAuth* ca,
  923. struct Allocator* alloc,
  924. const uint8_t herPublicKey[32],
  925. const bool requireAuth,
  926. char* displayName)
  927. {
  928. struct CryptoAuth_pvt* context = Identity_check((struct CryptoAuth_pvt*) ca);
  929. struct CryptoAuth_Session_pvt* session =
  930. Allocator_calloc(alloc, sizeof(struct CryptoAuth_Session_pvt), 1);
  931. Identity_set(session);
  932. session->context = context;
  933. session->requireAuth = requireAuth;
  934. session->pub.displayName = displayName ? String_new(displayName, alloc) : NULL;
  935. session->timeOfLastPacket = Time_currentTimeSeconds(context->eventBase);
  936. session->alloc = alloc;
  937. session->pub.resetAfterInactivitySeconds = CryptoAuth_DEFAULT_RESET_AFTER_INACTIVITY_SECONDS;
  938. session->pub.setupResetAfterInactivitySeconds =
  939. CryptoAuth_DEFAULT_SETUP_RESET_AFTER_INACTIVITY_SECONDS;
  940. Assert_true(herPublicKey);
  941. Bits_memcpy(session->pub.herPublicKey, herPublicKey, 32);
  942. uint8_t calculatedIp6[16];
  943. AddressCalc_addressForPublicKey(calculatedIp6, herPublicKey);
  944. Bits_memcpy(session->pub.herIp6, calculatedIp6, 16);
  945. return &session->pub;
  946. }
  947. void CryptoAuth_setAuth(const String* password,
  948. const String* login,
  949. struct CryptoAuth_Session* caSession)
  950. {
  951. struct CryptoAuth_Session_pvt* session =
  952. Identity_check((struct CryptoAuth_Session_pvt*)caSession);
  953. if (!password && (session->password || session->authType)) {
  954. if (session->passwdAlloc) {
  955. Allocator_free(session->passwdAlloc);
  956. session->passwdAlloc = NULL;
  957. }
  958. session->password = NULL;
  959. session->authType = 0;
  960. } else if (!session->password || !String_equals(session->password, password)) {
  961. if (session->passwdAlloc) {
  962. Allocator_free(session->passwdAlloc);
  963. }
  964. session->passwdAlloc = Allocator_child(session->alloc);
  965. session->password = String_clone(password, session->passwdAlloc);
  966. session->authType = 1;
  967. if (login) {
  968. session->authType = 2;
  969. if (session->loginAlloc) {
  970. Allocator_free(session->loginAlloc);
  971. }
  972. session->loginAlloc = Allocator_child(session->alloc);
  973. session->login = String_clone(login, session->loginAlloc);
  974. }
  975. } else {
  976. return;
  977. }
  978. reset(session);
  979. }
  980. enum CryptoAuth_State CryptoAuth_getState(struct CryptoAuth_Session* caSession)
  981. {
  982. struct CryptoAuth_Session_pvt* session =
  983. Identity_check((struct CryptoAuth_Session_pvt*)caSession);
  984. if (session->nextNonce <= CryptoAuth_State_RECEIVED_KEY) {
  985. return session->nextNonce;
  986. }
  987. return (session->established) ? CryptoAuth_State_ESTABLISHED : CryptoAuth_State_RECEIVED_KEY;
  988. }
  989. void CryptoAuth_resetIfTimeout(struct CryptoAuth_Session* caSession)
  990. {
  991. struct CryptoAuth_Session_pvt* session =
  992. Identity_check((struct CryptoAuth_Session_pvt*)caSession);
  993. resetIfTimeout(session);
  994. }
  995. void CryptoAuth_reset(struct CryptoAuth_Session* caSession)
  996. {
  997. struct CryptoAuth_Session_pvt* session =
  998. Identity_check((struct CryptoAuth_Session_pvt*)caSession);
  999. reset(session);
  1000. }
  1001. // For testing:
  1002. void CryptoAuth_encryptRndNonce(uint8_t nonce[24], struct Message* msg, uint8_t secret[32])
  1003. {
  1004. encryptRndNonce(nonce, msg, secret);
  1005. }
  1006. int CryptoAuth_decryptRndNonce(uint8_t nonce[24], struct Message* msg, uint8_t secret[32])
  1007. {
  1008. return decryptRndNonce(nonce, msg, secret);
  1009. }