1
0

CryptoAuth.c 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  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(const uint8_t nonce[24],
  173. struct Message* msg,
  174. const uint8_t secret[32])
  175. {
  176. if (Message_getLength(msg) < 16) {
  177. return -1;
  178. }
  179. Assert_true(Message_getPadding(msg) >= 16);
  180. uint8_t* startAt = msg->msgbytes - 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, Message_getLength(msg) + 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(const uint8_t nonce[24],
  204. struct Message* msg,
  205. const uint8_t secret[32])
  206. {
  207. Assert_true(Message_getPadding(msg) >= 32);
  208. uint8_t* startAt = msg->msgbytes - 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, Message_getLength(msg) + 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->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->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)->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->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();
  303. if (nowSecs - session->timeOfLastPacket < session->setupResetAfterInactivitySeconds) {
  304. return;
  305. } else if (nowSecs - session->timeOfLastPacket < session->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->msgbytes;
  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->pubKey, 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->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->msgbytes);
  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. static int encryptPacket(struct CryptoAuth_Session_pvt* session, struct Message* msg)
  426. {
  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->msgbytes % 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(Message_getLength(msg) > 0 && "Empty packet during handshake");
  460. Assert_true(Message_getPadding(msg) >= 36 || !"not enough padding");
  461. encrypt(session->nextNonce, msg, session->sharedSecret, session->isInitiator);
  462. Er_assert(Message_epush32be(msg, session->nextNonce));
  463. session->nextNonce++;
  464. return 0;
  465. }
  466. /** @return 0 on success, -1 otherwise. */ // Now only used in unit tests on Rust side
  467. int CryptoAuth_encrypt(struct CryptoAuth_Session* sessionPub, struct Message* msg) {
  468. struct CryptoAuth_Session_pvt *session =
  469. Identity_check((struct CryptoAuth_Session_pvt *) sessionPub);
  470. return encryptPacket(session, msg);
  471. }
  472. /** Call the external interface and tell it that a message has been received. */
  473. static inline void updateTime(struct CryptoAuth_Session_pvt* session, struct Message* message)
  474. {
  475. session->timeOfLastPacket = Time_currentTimeSeconds();
  476. }
  477. static inline enum CryptoAuth_DecryptErr decryptMessage(struct CryptoAuth_Session_pvt* session,
  478. uint32_t nonce,
  479. struct Message* content,
  480. uint8_t secret[32])
  481. {
  482. // Decrypt with authentication and replay prevention.
  483. if (decrypt(nonce, content, secret, session->isInitiator)) {
  484. cryptoAuthDebug0(session, "DROP authenticated decryption failed");
  485. return CryptoAuth_DecryptErr_DECRYPT;
  486. }
  487. if (!ReplayProtector_checkNonce(nonce, &session->replayProtector)) {
  488. cryptoAuthDebug(session, "DROP nonce checking failed nonce=[%u]", nonce);
  489. return CryptoAuth_DecryptErr_REPLAY;
  490. }
  491. return 0;
  492. }
  493. static bool ip6MatchesKey(uint8_t ip6[16], uint8_t key[32])
  494. {
  495. uint8_t calculatedIp6[16];
  496. AddressCalc_addressForPublicKey(calculatedIp6, key);
  497. return !Bits_memcmp(ip6, calculatedIp6, 16);
  498. }
  499. static enum CryptoAuth_DecryptErr decryptHandshake(struct CryptoAuth_Session_pvt* session,
  500. const uint32_t nonce,
  501. struct Message* message,
  502. struct CryptoHeader* header)
  503. {
  504. if (Message_getLength(message) < CryptoHeader_SIZE) {
  505. cryptoAuthDebug0(session, "DROP runt");
  506. return CryptoAuth_DecryptErr_RUNT;
  507. }
  508. // handshake
  509. // nextNonce 0: recieving hello.
  510. // nextNonce 1: recieving key, we sent hello.
  511. // nextNonce 2: recieving first data packet or duplicate hello.
  512. // nextNonce 3: recieving first data packet.
  513. // nextNonce >3: handshake complete
  514. Assert_true(knowHerKey(session));
  515. if (Bits_memcmp(session->herPublicKey, header->publicKey, 32)) {
  516. cryptoAuthDebug0(session, "DROP a packet with different public key than this session");
  517. return CryptoAuth_DecryptErr_WRONG_PERM_PUBKEY;
  518. }
  519. Assert_true((session->nextNonce < CryptoAuth_State_RECEIVED_HELLO) ==
  520. Bits_isZero(session->herTempPubKey, 32));
  521. struct CryptoAuth_User* userObj = getAuth(&header->auth, session->context);
  522. uint8_t* restrictedToip6 = NULL;
  523. uint8_t* passwordHash = NULL;
  524. if (userObj) {
  525. passwordHash = userObj->secret;
  526. if (userObj->restrictedToip6[0]) {
  527. restrictedToip6 = userObj->restrictedToip6;
  528. if (!ip6MatchesKey(restrictedToip6, session->herPublicKey)) {
  529. cryptoAuthDebug0(session, "DROP packet with key not matching restrictedToip6");
  530. return CryptoAuth_DecryptErr_IP_RESTRICTED;
  531. }
  532. }
  533. }
  534. if (session->requireAuth && !userObj) {
  535. cryptoAuthDebug0(session, "DROP message because auth was not given");
  536. return CryptoAuth_DecryptErr_AUTH_REQUIRED;
  537. }
  538. if (!userObj && header->auth.type != 0) {
  539. cryptoAuthDebug0(session, "DROP message with unrecognized authenticator");
  540. return CryptoAuth_DecryptErr_UNRECOGNIZED_AUTH;
  541. }
  542. // What the nextNonce will become if this packet is valid.
  543. uint32_t nextNonce;
  544. // The secret for decrypting this message.
  545. uint8_t sharedSecret[32];
  546. if (nonce < Nonce_KEY) { // HELLO or REPEAT_HELLO
  547. cryptoAuthDebug(session, "Received a %shello packet, using auth: %d",
  548. (nonce == Nonce_REPEAT_HELLO) ? "repeat " : "",
  549. (userObj != NULL));
  550. getSharedSecret(sharedSecret,
  551. session->context->privateKey,
  552. session->herPublicKey,
  553. passwordHash,
  554. session->context->logger);
  555. nextNonce = CryptoAuth_State_RECEIVED_HELLO;
  556. } else {
  557. if (nonce == Nonce_KEY) {
  558. cryptoAuthDebug0(session, "Received a key packet");
  559. } else {
  560. Assert_true(nonce == Nonce_REPEAT_KEY);
  561. cryptoAuthDebug0(session, "Received a repeat key packet");
  562. }
  563. if (!session->isInitiator) {
  564. cryptoAuthDebug0(session, "DROP a stray key packet");
  565. return CryptoAuth_DecryptErr_STRAY_KEY;
  566. }
  567. // We sent the hello, this is a key
  568. getSharedSecret(sharedSecret,
  569. session->ourTempPrivKey,
  570. session->herPublicKey,
  571. passwordHash,
  572. session->context->logger);
  573. nextNonce = CryptoAuth_State_RECEIVED_KEY;
  574. }
  575. // Shift it on top of the authenticator before the encrypted public key
  576. Er_assert(Message_eshift(message, 48 - CryptoHeader_SIZE));
  577. if (Defined(Log_KEYS)) {
  578. uint8_t sharedSecretHex[65];
  579. printHexKey(sharedSecretHex, sharedSecret);
  580. uint8_t nonceHex[49];
  581. Hex_encode(nonceHex, 49, header->handshakeNonce, 24);
  582. uint8_t cipherHex[65];
  583. printHexKey(cipherHex, message->msgbytes);
  584. Log_keys(session->context->logger,
  585. "Decrypting message with:\n"
  586. " nonce: %s\n"
  587. " secret: %s\n"
  588. " cipher: %s\n",
  589. nonceHex, sharedSecretHex, cipherHex);
  590. }
  591. // Decrypt her temp public key and the message.
  592. if (decryptRndNonce(header->handshakeNonce, message, sharedSecret)) {
  593. // just in case
  594. Bits_memset(header, 0, CryptoHeader_SIZE);
  595. cryptoAuthDebug(session, "DROP message with nonce [%d], decryption failed", nonce);
  596. return CryptoAuth_DecryptErr_HANDSHAKE_DECRYPT_FAILED;
  597. }
  598. if (Bits_isZero(header->encryptedTempKey, 32)) {
  599. // we need to reject 0 public keys outright because they will be confused with "unknown"
  600. cryptoAuthDebug0(session, "DROP message with zero as temp public key");
  601. return CryptoAuth_DecryptErr_WISEGUY;
  602. }
  603. if (Defined(Log_KEYS)) {
  604. uint8_t tempKeyHex[65];
  605. Hex_encode(tempKeyHex, 65, header->encryptedTempKey, 32);
  606. Log_keys(session->context->logger,
  607. "Unwrapping temp public key:\n"
  608. " %s\n",
  609. tempKeyHex);
  610. }
  611. Er_assert(Message_eshift(message, -32));
  612. // Post-decryption checking
  613. if (nonce == Nonce_HELLO) {
  614. // A new hello packet
  615. if (!Bits_memcmp(session->herTempPubKey, header->encryptedTempKey, 32)) {
  616. // possible replay attack or duped packet
  617. cryptoAuthDebug0(session, "DROP dupe hello packet with same temp key");
  618. return CryptoAuth_DecryptErr_INVALID_PACKET;
  619. }
  620. } else if (nonce == Nonce_KEY && session->nextNonce >= CryptoAuth_State_RECEIVED_KEY) {
  621. // we accept a new key packet and let it change the session since the other end might have
  622. // killed off the session while it was in the midst of setting up.
  623. // This is NOT a repeat key packet because it's nonce is 2, not 3
  624. if (!Bits_memcmp(session->herTempPubKey, header->encryptedTempKey, 32)) {
  625. Assert_true(!Bits_isZero(session->herTempPubKey, 32));
  626. cryptoAuthDebug0(session, "DROP dupe key packet with same temp key");
  627. return CryptoAuth_DecryptErr_INVALID_PACKET;
  628. }
  629. } else if (nonce == Nonce_REPEAT_KEY && session->nextNonce >= CryptoAuth_State_RECEIVED_KEY) {
  630. // Got a repeat key packet, make sure the temp key is the same as the one we know.
  631. if (Bits_memcmp(session->herTempPubKey, header->encryptedTempKey, 32)) {
  632. Assert_true(!Bits_isZero(session->herTempPubKey, 32));
  633. cryptoAuthDebug0(session, "DROP repeat key packet with different temp key");
  634. return CryptoAuth_DecryptErr_INVALID_PACKET;
  635. }
  636. }
  637. // If Alice sent a hello packet then Bob sent a hello packet and they crossed on the wire,
  638. // somebody has to yield and the other has to stand firm otherwise they will either deadlock
  639. // each believing their hello packet is superior or they will livelock, each switching to the
  640. // other's session and never synchronizing.
  641. // In this event whoever has the lower permanent public key wins.
  642. // If we receive a (possibly repeat) key packet
  643. if (nextNonce == CryptoAuth_State_RECEIVED_KEY) {
  644. Assert_true(nonce == Nonce_KEY || nonce == Nonce_REPEAT_KEY);
  645. switch (session->nextNonce) {
  646. case CryptoAuth_State_INIT:
  647. case CryptoAuth_State_RECEIVED_HELLO:
  648. case CryptoAuth_State_SENT_KEY: {
  649. cryptoAuthDebug0(session, "DROP stray key packet");
  650. return CryptoAuth_DecryptErr_STRAY_KEY;
  651. }
  652. case CryptoAuth_State_SENT_HELLO: {
  653. Bits_memcpy(session->herTempPubKey, header->encryptedTempKey, 32);
  654. break;
  655. }
  656. case CryptoAuth_State_RECEIVED_KEY: {
  657. if (nonce == Nonce_KEY) {
  658. Bits_memcpy(session->herTempPubKey, header->encryptedTempKey, 32);
  659. } else {
  660. Assert_true(!Bits_memcmp(session->herTempPubKey, header->encryptedTempKey, 32));
  661. }
  662. break;
  663. }
  664. default: {
  665. Assert_true(!session->established);
  666. if (nonce == Nonce_KEY) {
  667. Bits_memcpy(session->herTempPubKey, header->encryptedTempKey, 32);
  668. cryptoAuthDebug0(session, "New key packet, recalculating shared secret");
  669. Assert_ifParanoid(!Bits_isZero(session->ourTempPrivKey, 32));
  670. Assert_ifParanoid(!Bits_isZero(session->herTempPubKey, 32));
  671. getSharedSecret(session->sharedSecret,
  672. session->ourTempPrivKey,
  673. session->herTempPubKey,
  674. NULL,
  675. session->context->logger);
  676. } else {
  677. Assert_true(!Bits_memcmp(session->herTempPubKey, header->encryptedTempKey, 32));
  678. }
  679. nextNonce = session->nextNonce + 1;
  680. cryptoAuthDebug0(session, "New key packet but we are already sending data");
  681. }
  682. }
  683. } else if (nextNonce == CryptoAuth_State_RECEIVED_HELLO) {
  684. Assert_true(nonce == Nonce_HELLO || nonce == Nonce_REPEAT_HELLO);
  685. if (Bits_memcmp(session->herTempPubKey, header->encryptedTempKey, 32)) {
  686. // fresh new hello packet, we should reset the session.
  687. switch (session->nextNonce) {
  688. case CryptoAuth_State_SENT_HELLO: {
  689. if (Bits_memcmp(session->herPublicKey,
  690. session->context->pubKey, 32) < 0)
  691. {
  692. // It's a hello and we are the initiator but their permant public key is
  693. // numerically lower than ours, this is so that in the event of two hello
  694. // packets crossing on the wire, the nodes will agree on who is the
  695. // initiator.
  696. cryptoAuthDebug0(session,
  697. "Incoming hello from node with lower key, resetting");
  698. reset(session);
  699. Bits_memcpy(session->herTempPubKey, header->encryptedTempKey, 32);
  700. break;
  701. } else {
  702. // We are the initiator and thus we are sending HELLO packets, however they
  703. // have sent a hello to us and we already sent a HELLO
  704. // We accept the packet (return 0) but we do not alter the state because
  705. // we have our own state and we will respond with our (key) packet.
  706. cryptoAuthDebug0(session,
  707. "Incoming hello from node with higher key, not resetting");
  708. return 0;
  709. }
  710. }
  711. case CryptoAuth_State_INIT: {
  712. Bits_memcpy(session->herTempPubKey, header->encryptedTempKey, 32);
  713. break;
  714. }
  715. default: {
  716. cryptoAuthDebug0(session, "Incoming hello packet resetting session");
  717. reset(session);
  718. Bits_memcpy(session->herTempPubKey, header->encryptedTempKey, 32);
  719. break;
  720. }
  721. }
  722. } else {
  723. // received a hello packet with the same key as the session we already know...
  724. switch (session->nextNonce) {
  725. case CryptoAuth_State_RECEIVED_HELLO:
  726. case CryptoAuth_State_SENT_KEY: {
  727. nextNonce = session->nextNonce;
  728. break;
  729. }
  730. default: {
  731. cryptoAuthDebug0(session, "DROP Incoming repeat hello");
  732. // We already know the key which is being used for this hello packet and
  733. // our state has advanced past RECEIVED_HELLO or SENT_KEY or perhaps we
  734. // are the initiator of this session and they're sending us what should
  735. // be a key packet but is marked as hello, it's all invalid.
  736. return CryptoAuth_DecryptErr_INVALID_PACKET;
  737. }
  738. }
  739. }
  740. } else {
  741. Assert_failure("should never happen");
  742. }
  743. // Nonces can never go backward and can only "not advance" if they're 0,1,2,3,4 session state.
  744. Assert_true(session->nextNonce < nextNonce ||
  745. (session->nextNonce <= CryptoAuth_State_RECEIVED_KEY && nextNonce == session->nextNonce)
  746. );
  747. session->nextNonce = nextNonce;
  748. Bits_memset(&session->replayProtector, 0, sizeof(struct ReplayProtector));
  749. return 0;
  750. }
  751. /** @return 0 on success, -1 otherwise. */
  752. static enum CryptoAuth_DecryptErr decryptPacket(struct CryptoAuth_Session_pvt* session,
  753. struct Message* msg)
  754. {
  755. struct CryptoHeader* header = (struct CryptoHeader*) msg->msgbytes;
  756. if (Message_getLength(msg) < 20) {
  757. cryptoAuthDebug0(session, "DROP runt");
  758. return CryptoAuth_DecryptErr_RUNT;
  759. }
  760. Assert_true(Message_getPadding(msg) >= 12 || "need at least 12 bytes of padding in incoming message");
  761. Assert_true(!((uintptr_t)msg->msgbytes % 4) || !"alignment fault");
  762. Assert_true(!(Message_getCapacity(msg) % 4) || !"length fault");
  763. Er_assert(Message_eshift(msg, -4));
  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->replayProtector.baseOffset = nonce + 1;
  784. session->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. Er_assert(Message_eshift(msg, 4));
  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. Er_assert(Message_eshift(msg, 4));
  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. /** @return 0 on success, -1 otherwise. */ // Now only used in unit tests on Rust side
  821. enum CryptoAuth_DecryptErr CryptoAuth_decrypt(struct CryptoAuth_Session* sessionPub,
  822. struct Message* msg) {
  823. struct CryptoAuth_Session_pvt *session =
  824. Identity_check((struct CryptoAuth_Session_pvt *) sessionPub);
  825. return decryptPacket(session, msg);
  826. }
  827. /////////////////////////////////////////////////////////////////////////////////////////////////
  828. struct CryptoAuth* CryptoAuth_new(struct Allocator* allocator,
  829. const uint8_t* privateKey,
  830. struct EventBase* eventBase,
  831. struct Log* logger,
  832. struct Random* rand)
  833. {
  834. struct CryptoAuth_pvt* ca = Allocator_calloc(allocator, sizeof(struct CryptoAuth_pvt), 1);
  835. Identity_set(ca);
  836. ca->allocator = allocator;
  837. ca->eventBase = eventBase;
  838. ca->logger = logger;
  839. ca->rand = rand;
  840. if (privateKey != NULL) {
  841. Bits_memcpy(ca->privateKey, privateKey, 32);
  842. } else {
  843. Random_bytes(rand, ca->privateKey, 32);
  844. }
  845. crypto_scalarmult_curve25519_base(ca->pubKey, ca->privateKey);
  846. if (Defined(Log_KEYS)) {
  847. uint8_t publicKeyHex[65];
  848. printHexKey(publicKeyHex, ca->pubKey);
  849. uint8_t privateKeyHex[65];
  850. printHexKey(privateKeyHex, ca->privateKey);
  851. Log_keys(logger,
  852. "Initialized CryptoAuth:\n myPrivateKey=%s\n myPublicKey=%s\n",
  853. privateKeyHex,
  854. publicKeyHex);
  855. }
  856. return &ca->pub;
  857. }
  858. int CryptoAuth_addUser_ipv6(String* password,
  859. String* login,
  860. uint8_t ipv6[16],
  861. struct CryptoAuth* cryptoAuth)
  862. {
  863. struct CryptoAuth_pvt* ca = Identity_check((struct CryptoAuth_pvt*) cryptoAuth);
  864. struct Allocator* alloc = Allocator_child(ca->allocator);
  865. struct CryptoAuth_User* user = Allocator_calloc(alloc, sizeof(struct CryptoAuth_User), 1);
  866. user->alloc = alloc;
  867. Identity_set(user);
  868. if (!login) {
  869. int i = 0;
  870. for (struct CryptoAuth_User* u = ca->users; u; u = u->next) { i++; }
  871. user->login = login = String_printf(alloc, "Anon #%d", i);
  872. } else {
  873. user->login = String_clone(login, alloc);
  874. }
  875. struct CryptoHeader_Challenge ac;
  876. // Users specified with a login field might want to use authType 1 still.
  877. hashPassword(user->secret, &ac, login, password, 2);
  878. Bits_memcpy(user->userNameHash, &ac, CryptoHeader_Challenge_KEYSIZE);
  879. hashPassword(user->secret, &ac, NULL, password, 1);
  880. Bits_memcpy(user->passwordHash, &ac, CryptoHeader_Challenge_KEYSIZE);
  881. for (struct CryptoAuth_User* u = ca->users; u; u = u->next) {
  882. if (Bits_memcmp(user->secret, u->secret, 32)) {
  883. } else if (!login) {
  884. } else if (String_equals(login, u->login)) {
  885. Allocator_free(alloc);
  886. return CryptoAuth_addUser_DUPLICATE;
  887. }
  888. }
  889. if (ipv6) {
  890. Bits_memcpy(user->restrictedToip6, ipv6, 16);
  891. }
  892. // Add the user to the *end* of the list
  893. for (struct CryptoAuth_User** up = &ca->users; ; up = &(*up)->next) {
  894. if (!*up) {
  895. *up = user;
  896. break;
  897. }
  898. }
  899. return 0;
  900. }
  901. int CryptoAuth_removeUsers(struct CryptoAuth* context, String* login)
  902. {
  903. struct CryptoAuth_pvt* ca = Identity_check((struct CryptoAuth_pvt*) context);
  904. int count = 0;
  905. struct CryptoAuth_User** up = &ca->users;
  906. struct CryptoAuth_User* u = *up;
  907. while ((u = *up)) {
  908. if (!login || String_equals(login, u->login)) {
  909. *up = u->next;
  910. Allocator_free(u->alloc);
  911. count++;
  912. } else {
  913. up = &u->next;
  914. }
  915. }
  916. if (!login) {
  917. Log_debug(ca->logger, "Flushing [%d] users", count);
  918. } else {
  919. Log_debug(ca->logger, "Removing [%d] user(s) identified by [%s]", count, login->bytes);
  920. }
  921. return count;
  922. }
  923. RTypes_StrList_t* CryptoAuth_getUsers(const struct CryptoAuth* context, struct Allocator* alloc)
  924. {
  925. struct CryptoAuth_pvt* ca = Identity_check((struct CryptoAuth_pvt*) context);
  926. int count = 0;
  927. for (struct CryptoAuth_User* u = ca->users; u; u = u->next) {
  928. count++;
  929. }
  930. RTypes_StrList_t* out = Allocator_calloc(alloc, sizeof(RTypes_StrList_t), 1);
  931. out->len = count;
  932. out->items = Allocator_calloc(alloc, sizeof(String*), count);
  933. int i = 0;
  934. for (struct CryptoAuth_User* u = ca->users; u; u = u->next) {
  935. out->items[i] = String_clone(u->login, alloc);
  936. i++;
  937. }
  938. return out;
  939. }
  940. static Iface_DEFUN plaintextMsg(struct Message* msg, struct Iface* iface)
  941. {
  942. struct CryptoAuth_Session_pvt* sess =
  943. Identity_containerOf(iface, struct CryptoAuth_Session_pvt, pub.plaintext);
  944. if (encryptPacket(sess, msg)) {
  945. return Error(msg, "INTERNAL");
  946. }
  947. return Iface_next(&sess->pub.ciphertext, msg);
  948. }
  949. static Iface_DEFUN ciphertextMsg(struct Message* msg, struct Iface* iface)
  950. {
  951. struct CryptoAuth_Session_pvt* sess =
  952. Identity_containerOf(iface, struct CryptoAuth_Session_pvt, pub.ciphertext);
  953. if (Message_getLength(msg) < 32) {
  954. return Error(msg, "RUNT");
  955. }
  956. // Address is pushed on top of the message
  957. Er_assert(Message_epop(msg, NULL, 16));
  958. uint8_t firstSixteen[16];
  959. Bits_memcpy(firstSixteen, msg->msgbytes, 16);
  960. enum CryptoAuth_DecryptErr e = decryptPacket(sess, msg);
  961. if (e == CryptoAuth_DecryptErr_NONE) {
  962. Er_assert(Message_epush32be(msg, CryptoAuth_DecryptErr_NONE));
  963. return Iface_next(&sess->pub.plaintext, msg);
  964. }
  965. Er_assert(Message_epop(msg, NULL, Message_getLength(msg)));
  966. Er_assert(Message_epush32be(msg, CryptoAuth_getState(&sess->pub)));
  967. Er_assert(Message_epush32be(msg, e));
  968. Er_assert(Message_epush(msg, firstSixteen, 16));
  969. Er_assert(Message_epush32h(msg, e));
  970. return Iface_next(&sess->pub.plaintext, msg);
  971. }
  972. struct CryptoAuth_Session* CryptoAuth_newSession(struct CryptoAuth* ca,
  973. struct Allocator* alloc,
  974. const uint8_t herPublicKey[32],
  975. const bool requireAuth,
  976. const char* displayName,
  977. bool useNoise)
  978. {
  979. Assert_true(!useNoise && "Noise protocol not implemented in old CryptoAuth");
  980. struct CryptoAuth_pvt* context = Identity_check((struct CryptoAuth_pvt*) ca);
  981. struct CryptoAuth_Session_pvt* session =
  982. Allocator_calloc(alloc, sizeof(struct CryptoAuth_Session_pvt), 1);
  983. Identity_set(session);
  984. session->pub.plaintext.send = plaintextMsg;
  985. session->pub.ciphertext.send = ciphertextMsg;
  986. session->context = context;
  987. session->requireAuth = requireAuth;
  988. session->displayName = displayName ? String_new(displayName, alloc) : NULL;
  989. session->timeOfLastPacket = Time_currentTimeSeconds();
  990. session->alloc = alloc;
  991. session->resetAfterInactivitySeconds = CryptoAuth_DEFAULT_RESET_AFTER_INACTIVITY_SECONDS;
  992. session->setupResetAfterInactivitySeconds =
  993. CryptoAuth_DEFAULT_SETUP_RESET_AFTER_INACTIVITY_SECONDS;
  994. Assert_true(herPublicKey);
  995. Bits_memcpy(session->herPublicKey, herPublicKey, 32);
  996. uint8_t calculatedIp6[16];
  997. AddressCalc_addressForPublicKey(calculatedIp6, herPublicKey);
  998. Bits_memcpy(session->herIp6, calculatedIp6, 16);
  999. return &session->pub;
  1000. }
  1001. void CryptoAuth_setAuth(const String* password,
  1002. const String* login,
  1003. struct CryptoAuth_Session* caSession)
  1004. {
  1005. struct CryptoAuth_Session_pvt* session =
  1006. Identity_check((struct CryptoAuth_Session_pvt*)caSession);
  1007. if (!password && (session->password || session->authType)) {
  1008. if (session->passwdAlloc) {
  1009. Allocator_free(session->passwdAlloc);
  1010. session->passwdAlloc = NULL;
  1011. }
  1012. session->password = NULL;
  1013. session->authType = 0;
  1014. } else if (!session->password || !String_equals(session->password, password)) {
  1015. if (session->passwdAlloc) {
  1016. Allocator_free(session->passwdAlloc);
  1017. }
  1018. session->passwdAlloc = Allocator_child(session->alloc);
  1019. session->password = String_clone(password, session->passwdAlloc);
  1020. session->authType = 1;
  1021. if (login) {
  1022. session->authType = 2;
  1023. if (session->loginAlloc) {
  1024. Allocator_free(session->loginAlloc);
  1025. }
  1026. session->loginAlloc = Allocator_child(session->alloc);
  1027. session->login = String_clone(login, session->loginAlloc);
  1028. }
  1029. } else {
  1030. return;
  1031. }
  1032. reset(session);
  1033. }
  1034. RTypes_CryptoAuth_State_t CryptoAuth_getState(struct CryptoAuth_Session* caSession)
  1035. {
  1036. struct CryptoAuth_Session_pvt* session =
  1037. Identity_check((struct CryptoAuth_Session_pvt*)caSession);
  1038. if (session->nextNonce <= CryptoAuth_State_RECEIVED_KEY) {
  1039. return (RTypes_CryptoAuth_State_t) session->nextNonce;
  1040. }
  1041. return (session->established) ? CryptoAuth_State_ESTABLISHED : CryptoAuth_State_RECEIVED_KEY;
  1042. }
  1043. void CryptoAuth_resetIfTimeout(struct CryptoAuth_Session* caSession)
  1044. {
  1045. struct CryptoAuth_Session_pvt* session =
  1046. Identity_check((struct CryptoAuth_Session_pvt*)caSession);
  1047. resetIfTimeout(session);
  1048. }
  1049. void CryptoAuth_reset(struct CryptoAuth_Session* caSession)
  1050. {
  1051. struct CryptoAuth_Session_pvt* session =
  1052. Identity_check((struct CryptoAuth_Session_pvt*)caSession);
  1053. reset(session);
  1054. }
  1055. void CryptoAuth_getHerPubKey(const struct CryptoAuth_Session* session, uint8_t* pkOut)
  1056. {
  1057. const struct CryptoAuth_Session_pvt* s =
  1058. Identity_check((struct CryptoAuth_Session_pvt*)session);
  1059. Bits_memcpy(pkOut, s->herPublicKey, 32);
  1060. }
  1061. void CryptoAuth_getHerIp6(const struct CryptoAuth_Session* session, uint8_t* ipOut)
  1062. {
  1063. const struct CryptoAuth_Session_pvt* s =
  1064. Identity_check((struct CryptoAuth_Session_pvt*)session);
  1065. Bits_memcpy(ipOut, s->herIp6, 16);
  1066. }
  1067. void CryptoAuth_getPubKey(const struct CryptoAuth* ca, uint8_t* pkOut)
  1068. {
  1069. const struct CryptoAuth_pvt* context = Identity_check((struct CryptoAuth_pvt*) ca);
  1070. Bits_memcpy(pkOut, context->pubKey, 32);
  1071. }
  1072. String_t *CryptoAuth_getName(const struct CryptoAuth_Session* session, Allocator_t* alloc)
  1073. {
  1074. const struct CryptoAuth_Session_pvt* s =
  1075. Identity_check((struct CryptoAuth_Session_pvt*)session);
  1076. if (s->displayName) {
  1077. return String_clone(s->displayName, alloc);
  1078. } else {
  1079. return NULL;
  1080. }
  1081. }
  1082. void CryptoAuth_stats(const struct CryptoAuth_Session* session, RTypes_CryptoStats_t* statsOut)
  1083. {
  1084. const struct CryptoAuth_Session_pvt* s =
  1085. Identity_check((struct CryptoAuth_Session_pvt*)session);
  1086. statsOut->received_packets = s->replayProtector.baseOffset +
  1087. Bits_popCountx64(s->replayProtector.bitfield);
  1088. statsOut->lost_packets = s->replayProtector.lostPackets;
  1089. statsOut->received_unexpected = s->replayProtector.receivedOutOfRange;
  1090. statsOut->duplicate_packets = s->replayProtector.duplicates;
  1091. statsOut->noise_proto = false;
  1092. }
  1093. // For testing:
  1094. void CryptoAuth_encryptRndNonce(const uint8_t nonce[24], struct Message* msg, const uint8_t secret[32])
  1095. {
  1096. encryptRndNonce(nonce, msg, secret);
  1097. }
  1098. int CryptoAuth_decryptRndNonce(const uint8_t nonce[24], struct Message* msg, const uint8_t secret[32])
  1099. {
  1100. return decryptRndNonce(nonce, msg, secret);
  1101. }