CryptoAuth.c 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309
  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 <http://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 "interface/Interface.h"
  20. #include "benc/Dict.h"
  21. #include "benc/List.h"
  22. #include "benc/String.h"
  23. #include "util/log/Log.h"
  24. #include "memory/Allocator.h"
  25. #include "util/Assert.h"
  26. #include "util/AddrTools.h"
  27. #include "util/Bits.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_core_hsalsa20.h"
  36. #include "crypto_hash_sha256.h"
  37. #include "crypto_scalarmult_curve25519.h"
  38. #include "crypto_stream_salsa20.h"
  39. #include "crypto_stream_xsalsa20.h"
  40. #include <stdint.h>
  41. #include <stdbool.h>
  42. #ifdef win32
  43. #undef interface
  44. #endif
  45. #ifdef Log_KEYS
  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_memcpyConst(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. #endif
  65. /**
  66. * Get a shared secret.
  67. *
  68. * @param outputSecret an array to place the shared secret in.
  69. * @param myPrivateKey
  70. * @param herPublicKey
  71. * @param logger
  72. * @param passwordHash a 32 byte value known to both ends, this must be provably pseudorandom
  73. * the first 32 bytes of a sha256 output from hashing a password is ok,
  74. * whatever she happens to send me in the Auth field is NOT ok.
  75. * If this field is null, the secret will be generated without the password.
  76. */
  77. static inline void getSharedSecret(uint8_t outputSecret[32],
  78. uint8_t myPrivateKey[32],
  79. uint8_t herPublicKey[32],
  80. uint8_t passwordHash[32],
  81. struct Log* logger)
  82. {
  83. if (passwordHash == NULL) {
  84. crypto_box_curve25519xsalsa20poly1305_beforenm(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. crypto_scalarmult_curve25519(buff.components.key, myPrivateKey, herPublicKey);
  94. Bits_memcpyConst(buff.components.passwd, passwordHash, 32);
  95. crypto_hash_sha256(outputSecret, buff.bytes, 64);
  96. }
  97. #ifdef 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. #endif
  114. }
  115. static inline void hashPassword_sha256(struct CryptoAuth_Auth* auth, const String* password)
  116. {
  117. uint8_t tempBuff[32];
  118. crypto_hash_sha256(auth->secret, (uint8_t*) password->bytes, password->len);
  119. crypto_hash_sha256(tempBuff, auth->secret, 32);
  120. Bits_memcpyConst(auth->challenge.bytes, tempBuff, Headers_AuthChallenge_SIZE);
  121. Headers_setAuthChallengeDerivations(&auth->challenge, 0);
  122. auth->challenge.challenge.type = 1;
  123. }
  124. static inline uint8_t* hashPassword(struct CryptoAuth_Auth* auth,
  125. const String* password,
  126. const uint8_t authType)
  127. {
  128. switch (authType) {
  129. case 1:
  130. hashPassword_sha256(auth, password);
  131. break;
  132. default:
  133. Assert_always(!"Unsupported auth type.");
  134. };
  135. return auth->secret;
  136. }
  137. /**
  138. * Search the authorized passwords for one matching this auth header.
  139. *
  140. * @param auth the auth header.
  141. * @param context the CryptoAuth engine to search in.
  142. * @return an Auth struct with a if one is found, otherwise NULL.
  143. */
  144. static inline struct CryptoAuth_Auth* getAuth(union Headers_AuthChallenge auth,
  145. struct CryptoAuth_pvt* context)
  146. {
  147. if (auth.challenge.type != 1) {
  148. return NULL;
  149. }
  150. for (uint32_t i = 0; i < context->passwordCount; i++) {
  151. if (Bits_memcmp(auth.bytes, &context->passwords[i], Headers_AuthChallenge_KEYSIZE) == 0) {
  152. return &context->passwords[i];
  153. }
  154. }
  155. Log_debug(context->logger, "Got unrecognized auth, password count = [%d]",
  156. context->passwordCount);
  157. return NULL;
  158. }
  159. static inline void getPasswordHash_typeOne(uint8_t output[32],
  160. uint16_t derivations,
  161. struct CryptoAuth_Auth* auth)
  162. {
  163. Bits_memcpyConst(output, auth->secret, 32);
  164. if (derivations) {
  165. union {
  166. uint8_t bytes[2];
  167. uint8_t asShort;
  168. } deriv = { .asShort = derivations };
  169. output[0] ^= deriv.bytes[0];
  170. output[1] ^= deriv.bytes[1];
  171. crypto_hash_sha256(output, output, 32);
  172. }
  173. }
  174. static inline uint8_t* tryAuth(union Headers_CryptoAuth* cauth,
  175. uint8_t hashOutput[32],
  176. struct CryptoAuth_Wrapper* wrapper,
  177. String** userPtr)
  178. {
  179. struct CryptoAuth_Auth* auth = getAuth(cauth->handshake.auth, wrapper->context);
  180. if (auth != NULL) {
  181. uint16_t deriv = Headers_getAuthChallengeDerivations(&cauth->handshake.auth);
  182. getPasswordHash_typeOne(hashOutput, deriv, auth);
  183. if (deriv == 0) {
  184. *userPtr = auth->user;
  185. }
  186. return hashOutput;
  187. }
  188. return NULL;
  189. }
  190. /**
  191. * Decrypt and authenticate.
  192. *
  193. * @param nonce a 24 byte number, may be random, cannot repeat.
  194. * @param msg a message to encipher and authenticate.
  195. * @param secret a shared secret.
  196. * @return 0 if decryption is succeddful, otherwise -1.
  197. */
  198. static inline int decryptRndNonce(uint8_t nonce[24],
  199. struct Message* msg,
  200. uint8_t secret[32])
  201. {
  202. if (msg->length < 16) {
  203. return -1;
  204. }
  205. Assert_true(msg->padding >= 16);
  206. uint8_t* startAt = msg->bytes - 16;
  207. uint8_t paddingSpace[16];
  208. Bits_memcpyConst(paddingSpace, startAt, 16);
  209. Bits_memset(startAt, 0, 16);
  210. if (crypto_box_curve25519xsalsa20poly1305_open_afternm(
  211. startAt, startAt, msg->length + 16, nonce, secret) != 0)
  212. {
  213. return -1;
  214. }
  215. Bits_memcpyConst(startAt, paddingSpace, 16);
  216. Message_shift(msg, -16, NULL);
  217. return 0;
  218. }
  219. /**
  220. * Encrypt and authenticate.
  221. * Shifts the message by 16 bytes.
  222. *
  223. * @param nonce a 24 byte number, may be random, cannot repeat.
  224. * @param msg a message to encipher and authenticate.
  225. * @param secret a shared secret.
  226. */
  227. static inline void encryptRndNonce(uint8_t nonce[24],
  228. struct Message* msg,
  229. uint8_t secret[32])
  230. {
  231. Assert_true(msg->padding >= 32);
  232. uint8_t* startAt = msg->bytes - 32;
  233. // This function trashes 16 bytes of the padding so we will put it back
  234. uint8_t paddingSpace[16];
  235. Bits_memcpyConst(paddingSpace, startAt, 16);
  236. Bits_memset(startAt, 0, 32);
  237. crypto_box_curve25519xsalsa20poly1305_afternm(
  238. startAt, startAt, msg->length + 32, nonce, secret);
  239. Bits_memcpyConst(startAt, paddingSpace, 16);
  240. Message_shift(msg, 16, NULL);
  241. }
  242. /**
  243. * Decrypt a packet.
  244. *
  245. * @param nonce a counter.
  246. * @param msg the message to decrypt, decrypted in place.
  247. * @param secret the shared secret.
  248. * @param isInitiator true if we started the connection.
  249. */
  250. static inline int decrypt(uint32_t nonce,
  251. struct Message* msg,
  252. uint8_t secret[32],
  253. bool isInitiator)
  254. {
  255. union {
  256. uint32_t ints[2];
  257. uint8_t bytes[24];
  258. } nonceAs = { .ints = {0, 0} };
  259. nonceAs.ints[!isInitiator] = Endian_hostToLittleEndian32(nonce);
  260. return decryptRndNonce(nonceAs.bytes, msg, secret);
  261. }
  262. /**
  263. * Encrypt a packet.
  264. *
  265. * @param nonce a counter.
  266. * @param msg the message to decrypt, decrypted in place.
  267. * @param secret the shared secret.
  268. * @param isInitiator true if we started the connection.
  269. */
  270. static inline void encrypt(uint32_t nonce,
  271. struct Message* msg,
  272. uint8_t secret[32],
  273. bool isInitiator)
  274. {
  275. union {
  276. uint32_t ints[2];
  277. uint8_t bytes[24];
  278. } nonceAs = { .ints = {0, 0} };
  279. nonceAs.ints[isInitiator] = Endian_hostToLittleEndian32(nonce);
  280. encryptRndNonce(nonceAs.bytes, msg, secret);
  281. }
  282. static inline void setRequiredPadding(struct CryptoAuth_Wrapper* wrapper)
  283. {
  284. uint32_t padding = (wrapper->nextNonce < 4) ? 36 : sizeof(union Headers_CryptoAuth) + 32;
  285. wrapper->externalInterface.requiredPadding =
  286. wrapper->wrappedInterface->requiredPadding + padding;
  287. wrapper->externalInterface.maxMessageLength =
  288. wrapper->wrappedInterface->maxMessageLength - padding;
  289. }
  290. static inline bool knowHerKey(struct CryptoAuth_Wrapper* wrapper)
  291. {
  292. return !Bits_isZero(wrapper->herPerminentPubKey, 32);
  293. }
  294. static void getIp6(struct CryptoAuth_Wrapper* wrapper, uint8_t* addr)
  295. {
  296. if (knowHerKey(wrapper)) {
  297. uint8_t ip6[16];
  298. AddressCalc_addressForPublicKey(ip6, wrapper->herPerminentPubKey);
  299. AddrTools_printIp(addr, ip6);
  300. }
  301. }
  302. #define cryptoAuthDebug(wrapper, format, ...) \
  303. { \
  304. uint8_t addr[40] = "unknown"; \
  305. getIp6((wrapper), addr); \
  306. Log_debug((wrapper)->context->logger, \
  307. "%p %s [%s]: " format, (void*)(wrapper), (wrapper)->name, addr, __VA_ARGS__); \
  308. }
  309. #define cryptoAuthDebug0(wrapper, format) \
  310. cryptoAuthDebug(wrapper, format "%s", "")
  311. static void reset(struct CryptoAuth_Wrapper* wrapper)
  312. {
  313. wrapper->nextNonce = 0;
  314. wrapper->isInitiator = false;
  315. Bits_memset(wrapper->ourTempPrivKey, 0, 32);
  316. Bits_memset(wrapper->ourTempPubKey, 0, 32);
  317. Bits_memset(wrapper->herTempPubKey, 0, 32);
  318. Bits_memset(wrapper->sharedSecret, 0, 32);
  319. wrapper->established = false;
  320. Bits_memset(&wrapper->replayProtector, 0, sizeof(struct ReplayProtector));
  321. }
  322. /**
  323. * If we don't know her key, the handshake has to be done backwards.
  324. * Reverse handshake requests are signaled by sending a non-obfuscated zero nonce.
  325. */
  326. static uint8_t genReverseHandshake(struct Message* message,
  327. struct CryptoAuth_Wrapper* wrapper,
  328. union Headers_CryptoAuth* header)
  329. {
  330. reset(wrapper);
  331. Message_shift(message, -Headers_CryptoAuth_SIZE, NULL);
  332. // Buffer the packet so it can be sent ASAP
  333. if (wrapper->bufferedMessage != NULL) {
  334. // Not exactly a drop but a message is not going to reach the destination.
  335. cryptoAuthDebug0(wrapper,
  336. "DROP Expelled a message because a session has not yet been setup");
  337. Allocator_free(wrapper->bufferedMessage->alloc);
  338. }
  339. cryptoAuthDebug0(wrapper, "Buffered a message");
  340. struct Allocator* bmalloc = Allocator_child(wrapper->externalInterface.allocator);
  341. wrapper->bufferedMessage = Message_clone(message, bmalloc);
  342. Assert_true(wrapper->nextNonce == 0);
  343. Message_shift(message, Headers_CryptoAuth_SIZE, NULL);
  344. header = (union Headers_CryptoAuth*) message->bytes;
  345. header->nonce = UINT32_MAX;
  346. message->length = Headers_CryptoAuth_SIZE;
  347. // sessionState must be 0, auth and 24 byte nonce are garbaged and public key is set
  348. // now garbage the authenticator and the encrypted key which are not used.
  349. Random_bytes(wrapper->context->rand, (uint8_t*) &header->handshake.authenticator, 48);
  350. // This is a special packet which the user should never see.
  351. Headers_setSetupPacket(&header->handshake.auth, 1);
  352. return wrapper->wrappedInterface->sendMessage(message, wrapper->wrappedInterface);
  353. }
  354. static uint8_t sendMessage(struct Message* message, struct Interface* interface);
  355. static uint8_t encryptHandshake(struct Message* message,
  356. struct CryptoAuth_Wrapper* wrapper,
  357. int setupMessage)
  358. {
  359. Message_shift(message, sizeof(union Headers_CryptoAuth), NULL);
  360. union Headers_CryptoAuth* header = (union Headers_CryptoAuth*) message->bytes;
  361. // garbage the auth challenge and set the nonce which follows it
  362. Random_bytes(wrapper->context->rand, (uint8_t*) &header->handshake.auth,
  363. sizeof(union Headers_AuthChallenge) + 24);
  364. // set the permanent key
  365. Bits_memcpyConst(&header->handshake.publicKey, wrapper->context->pub.publicKey, 32);
  366. if (!knowHerKey(wrapper)) {
  367. return genReverseHandshake(message, wrapper, header);
  368. } else if (!Bits_isZero(wrapper->herIp6, 16)) {
  369. // If someone starts a CA session and then discovers the key later and memcpy's it into the
  370. // result of getHerPublicKey() then we want to make sure they didn't memcpy in an invalid
  371. // key.
  372. uint8_t calculatedIp6[16];
  373. AddressCalc_addressForPublicKey(calculatedIp6, wrapper->herPerminentPubKey);
  374. Assert_always(!Bits_memcmp(wrapper->herIp6, calculatedIp6, 16));
  375. }
  376. if (wrapper->bufferedMessage) {
  377. // We wanted to send a message but we didn't know the peer's key so we buffered it
  378. // and sent a connectToMe.
  379. // Now we just discovered their key and we're sending a hello packet.
  380. // Lets send 2 hello packets instead and on one will attach our buffered message.
  381. // This can never happen when the machine is beyond the first hello packet because
  382. // it should have been sent either by this or in the recipet of a hello packet from
  383. // the other node.
  384. Assert_true(wrapper->nextNonce == 0);
  385. struct Message* bm = wrapper->bufferedMessage;
  386. wrapper->bufferedMessage = NULL;
  387. cryptoAuthDebug0(wrapper, "Sending buffered message");
  388. sendMessage(bm, &wrapper->externalInterface);
  389. Allocator_free(bm->alloc);
  390. }
  391. // Password auth
  392. uint8_t* passwordHash = NULL;
  393. struct CryptoAuth_Auth auth;
  394. if (wrapper->password != NULL) {
  395. passwordHash = hashPassword(&auth, wrapper->password, wrapper->authType);
  396. Bits_memcpyConst(header->handshake.auth.bytes,
  397. &auth.challenge,
  398. sizeof(union Headers_AuthChallenge));
  399. }
  400. header->handshake.auth.challenge.type = wrapper->authType;
  401. // Packet authentication option is deprecated, it must always be enabled.
  402. Headers_setPacketAuthRequired(&header->handshake.auth, 1);
  403. // This is a special packet which the user should never see.
  404. Headers_setSetupPacket(&header->handshake.auth, setupMessage);
  405. // Set the session state
  406. uint32_t sessionState_be = Endian_hostToBigEndian32(wrapper->nextNonce);
  407. header->nonce = sessionState_be;
  408. if (wrapper->nextNonce == 0 || wrapper->nextNonce == 2) {
  409. // If we're sending a hello or a key
  410. // Here we make up a temp keypair
  411. Random_bytes(wrapper->context->rand, wrapper->ourTempPrivKey, 32);
  412. crypto_scalarmult_curve25519_base(wrapper->ourTempPubKey, wrapper->ourTempPrivKey);
  413. #ifdef Log_KEYS
  414. uint8_t tempPrivateKeyHex[65];
  415. Hex_encode(tempPrivateKeyHex, 65, wrapper->ourTempPrivKey, 32);
  416. uint8_t tempPubKeyHex[65];
  417. Hex_encode(tempPubKeyHex, 65, header->handshake.encryptedTempKey, 32);
  418. Log_keys(wrapper->context->logger, "Generating temporary keypair\n"
  419. " myTempPrivateKey=%s\n"
  420. " myTempPublicKey=%s\n",
  421. tempPrivateKeyHex, tempPubKeyHex);
  422. #endif
  423. }
  424. Bits_memcpyConst(header->handshake.encryptedTempKey, wrapper->ourTempPubKey, 32);
  425. #ifdef Log_KEYS
  426. uint8_t tempKeyHex[65];
  427. Hex_encode(tempKeyHex, 65, header->handshake.encryptedTempKey, 32);
  428. Log_keys(wrapper->context->logger,
  429. "Wrapping temp public key:\n"
  430. " %s\n",
  431. tempKeyHex);
  432. #endif
  433. cryptoAuthDebug(wrapper, "Sending %s%s packet",
  434. ((wrapper->nextNonce & 1) ? "repeat " : ""),
  435. ((wrapper->nextNonce < 2) ? "hello" : "key"));
  436. uint8_t sharedSecret[32];
  437. if (wrapper->nextNonce < 2) {
  438. getSharedSecret(sharedSecret,
  439. wrapper->context->privateKey,
  440. wrapper->herPerminentPubKey,
  441. passwordHash,
  442. wrapper->context->logger);
  443. wrapper->isInitiator = true;
  444. Assert_true(wrapper->nextNonce <= 1);
  445. wrapper->nextNonce = 1;
  446. } else {
  447. // Handshake2
  448. // herTempPubKey was set by receiveMessage()
  449. Assert_true(!Bits_isZero(wrapper->herTempPubKey, 32));
  450. getSharedSecret(sharedSecret,
  451. wrapper->context->privateKey,
  452. wrapper->herTempPubKey,
  453. passwordHash,
  454. wrapper->context->logger);
  455. Assert_true(wrapper->nextNonce <= 3);
  456. wrapper->nextNonce = 3;
  457. #ifdef Log_KEYS
  458. uint8_t tempKeyHex[65];
  459. Hex_encode(tempKeyHex, 65, wrapper->herTempPubKey, 32);
  460. Log_keys(wrapper->context->logger,
  461. "Using their temp public key:\n"
  462. " %s\n",
  463. tempKeyHex);
  464. #endif
  465. }
  466. // Shift message over the encryptedTempKey field.
  467. Message_shift(message, 32 - Headers_CryptoAuth_SIZE, NULL);
  468. encryptRndNonce(header->handshake.nonce, message, sharedSecret);
  469. #ifdef Log_KEYS
  470. uint8_t sharedSecretHex[65];
  471. printHexKey(sharedSecretHex, sharedSecret);
  472. uint8_t nonceHex[49];
  473. Hex_encode(nonceHex, 49, header->handshake.nonce, 24);
  474. uint8_t cipherHex[65];
  475. printHexKey(cipherHex, message->bytes);
  476. Log_keys(wrapper->context->logger,
  477. "Encrypting message with:\n"
  478. " nonce: %s\n"
  479. " secret: %s\n"
  480. " cipher: %s\n",
  481. nonceHex, sharedSecretHex, cipherHex);
  482. #endif
  483. // Shift it back -- encryptRndNonce adds 16 bytes of authenticator.
  484. Message_shift(message, Headers_CryptoAuth_SIZE - 32 - 16, NULL);
  485. return wrapper->wrappedInterface->sendMessage(message, wrapper->wrappedInterface);
  486. }
  487. static inline uint8_t encryptMessage(struct Message* message,
  488. struct CryptoAuth_Wrapper* wrapper)
  489. {
  490. Assert_true(message->padding >= 36 || !"not enough padding");
  491. encrypt(wrapper->nextNonce,
  492. message,
  493. wrapper->sharedSecret,
  494. wrapper->isInitiator);
  495. Message_shift(message, 4, NULL);
  496. union Headers_CryptoAuth* header = (union Headers_CryptoAuth*) message->bytes;
  497. header->nonce = Endian_hostToBigEndian32(wrapper->nextNonce);
  498. wrapper->nextNonce++;
  499. return wrapper->wrappedInterface->sendMessage(message, wrapper->wrappedInterface);
  500. }
  501. static uint8_t sendMessage(struct Message* message, struct Interface* interface)
  502. {
  503. struct CryptoAuth_Wrapper* wrapper =
  504. Identity_check((struct CryptoAuth_Wrapper*) interface->senderContext);
  505. // If there has been no incoming traffic for a while, reset the connection to state 0.
  506. // This will prevent "connection in bad state" situations from lasting forever.
  507. // this will reset the session if it has timed out.
  508. CryptoAuth_resetIfTimeout(interface);
  509. // If the nonce wraps, start over.
  510. if (wrapper->nextNonce >= 0xfffffff0) {
  511. reset(wrapper);
  512. }
  513. #ifdef Log_DEBUG
  514. Assert_true(!((uintptr_t)message->bytes % 4) || !"alignment fault");
  515. #endif
  516. // nextNonce 0: sending hello, we are initiating connection.
  517. // nextNonce 1: sending another hello, nothing received yet.
  518. // nextNonce 2: sending key, hello received.
  519. // nextNonce 3: sending key again, no data packet recieved yet.
  520. // nextNonce >3: handshake complete
  521. //
  522. // if it's a blind handshake, every message will be empty and nextNonce will remain
  523. // zero until the first message is received back.
  524. if (wrapper->nextNonce < 5) {
  525. if (wrapper->nextNonce < 4) {
  526. return encryptHandshake(message, wrapper, 0);
  527. } else {
  528. cryptoAuthDebug0(wrapper, "Doing final step to send message. nonce=4");
  529. Assert_true(!Bits_isZero(wrapper->ourTempPrivKey, 32));
  530. Assert_true(!Bits_isZero(wrapper->herTempPubKey, 32));
  531. getSharedSecret(wrapper->sharedSecret,
  532. wrapper->ourTempPrivKey,
  533. wrapper->herTempPubKey,
  534. NULL,
  535. wrapper->context->logger);
  536. }
  537. }
  538. Assert_true(message->length > 0 && "Empty packet during handshake");
  539. return encryptMessage(message, wrapper);
  540. }
  541. /** Call the external interface and tell it that a message has been received. */
  542. static inline uint8_t callReceivedMessage(struct CryptoAuth_Wrapper* wrapper,
  543. struct Message* message)
  544. {
  545. wrapper->timeOfLastPacket = Time_currentTimeSeconds(wrapper->context->eventBase);
  546. uint8_t ret = 0;
  547. if (wrapper->externalInterface.receiveMessage != NULL) {
  548. ret = wrapper->externalInterface.receiveMessage(message, &wrapper->externalInterface);
  549. }
  550. return ret;
  551. }
  552. static inline bool decryptMessage(struct CryptoAuth_Wrapper* wrapper,
  553. uint32_t nonce,
  554. struct Message* content,
  555. uint8_t secret[32])
  556. {
  557. // Decrypt with authentication and replay prevention.
  558. if (decrypt(nonce, content, secret, wrapper->isInitiator)) {
  559. cryptoAuthDebug0(wrapper, "DROP authenticated decryption failed");
  560. return false;
  561. }
  562. if (!ReplayProtector_checkNonce(nonce, &wrapper->replayProtector)) {
  563. cryptoAuthDebug(wrapper, "DROP nonce checking failed nonce=[%u]", nonce);
  564. return false;
  565. }
  566. return true;
  567. }
  568. static uint8_t decryptHandshake(struct CryptoAuth_Wrapper* wrapper,
  569. const uint32_t nonce,
  570. struct Message* message,
  571. union Headers_CryptoAuth* header)
  572. {
  573. if (message->length < Headers_CryptoAuth_SIZE) {
  574. cryptoAuthDebug0(wrapper, "DROP runt");
  575. return Error_UNDERSIZE_MESSAGE;
  576. }
  577. // handshake
  578. // nextNonce 0: recieving hello.
  579. // nextNonce 1: recieving key, we sent hello.
  580. // nextNonce 2: recieving first data packet or duplicate hello.
  581. // nextNonce 3: recieving first data packet.
  582. // nextNonce >3: handshake complete
  583. if (knowHerKey(wrapper)) {
  584. if (Bits_memcmp(wrapper->herPerminentPubKey, header->handshake.publicKey, 32)) {
  585. cryptoAuthDebug0(wrapper, "DROP a packet with different public key than this session");
  586. return Error_AUTHENTICATION;
  587. }
  588. } else if (!Bits_isZero(wrapper->herIp6, 16)) {
  589. uint8_t calculatedIp6[16];
  590. AddressCalc_addressForPublicKey(calculatedIp6, header->handshake.publicKey);
  591. if (Bits_memcmp(wrapper->herIp6, calculatedIp6, 16)) {
  592. cryptoAuthDebug0(wrapper, "DROP packet with public key not matching ip6 for session");
  593. return Error_AUTHENTICATION;
  594. }
  595. }
  596. if (wrapper->nextNonce < 2 && nonce == UINT32_MAX && !wrapper->requireAuth) {
  597. // Reset without knowing key is allowed until state reaches 2.
  598. // this is because we don't know that the other end knows our key until we
  599. // have received a valid packet from them.
  600. // We can't allow the upper layer to see this message because it's not authenticated.
  601. if (!knowHerKey(wrapper)) {
  602. Bits_memcpyConst(wrapper->herPerminentPubKey, header->handshake.publicKey, 32);
  603. }
  604. Message_shift(message, -Headers_CryptoAuth_SIZE, NULL);
  605. message->length = 0;
  606. reset(wrapper);
  607. wrapper->user = NULL;
  608. cryptoAuthDebug0(wrapper, "Got a connect-to-me message, sending a hello");
  609. // Send an empty response (to initiate the connection).
  610. encryptHandshake(message, wrapper, 1);
  611. return Error_NONE;
  612. }
  613. String* user = NULL;
  614. uint8_t passwordHashStore[32];
  615. uint8_t* passwordHash = tryAuth(header, passwordHashStore, wrapper, &user);
  616. if (wrapper->requireAuth && !user) {
  617. cryptoAuthDebug0(wrapper, "DROP message because auth was not given");
  618. return Error_AUTHENTICATION;
  619. }
  620. if (passwordHash == NULL && header->handshake.auth.challenge.type != 0) {
  621. cryptoAuthDebug0(wrapper, "DROP message with unrecognized authenticator");
  622. return Error_AUTHENTICATION;
  623. }
  624. // What the nextNonce will become if this packet is valid.
  625. uint32_t nextNonce;
  626. // The secret for decrypting this message.
  627. uint8_t sharedSecret[32];
  628. uint8_t* herPermKey = NULL;
  629. if (nonce < 2) {
  630. if (nonce == 0) {
  631. cryptoAuthDebug(wrapper, "Received a hello packet, using auth: %d",
  632. (passwordHash != NULL));
  633. } else {
  634. cryptoAuthDebug0(wrapper, "Received a repeat hello packet");
  635. }
  636. // Decrypt message with perminent keys.
  637. if (!knowHerKey(wrapper) || wrapper->nextNonce == 0) {
  638. herPermKey = header->handshake.publicKey;
  639. #ifdef Log_DEBUG
  640. if (Bits_isZero(header->handshake.publicKey, 32)) {
  641. cryptoAuthDebug0(wrapper, "Node sent public key of ZERO!");
  642. }
  643. #endif
  644. } else {
  645. herPermKey = wrapper->herPerminentPubKey;
  646. if (Bits_memcmp(header->handshake.publicKey, herPermKey, 32)) {
  647. cryptoAuthDebug0(wrapper, "DROP packet contains different perminent key");
  648. return Error_AUTHENTICATION;
  649. }
  650. }
  651. getSharedSecret(sharedSecret,
  652. wrapper->context->privateKey,
  653. herPermKey,
  654. passwordHash,
  655. wrapper->context->logger);
  656. nextNonce = 2;
  657. } else {
  658. if (nonce == 2) {
  659. cryptoAuthDebug0(wrapper, "Received a key packet");
  660. } else if (nonce == 3) {
  661. cryptoAuthDebug0(wrapper, "Received a repeat key packet");
  662. } else {
  663. cryptoAuthDebug(wrapper, "Received a packet of unknown type! nonce=%u", nonce);
  664. }
  665. if (Bits_memcmp(header->handshake.publicKey, wrapper->herPerminentPubKey, 32)) {
  666. cryptoAuthDebug0(wrapper, "DROP packet contains different perminent key");
  667. return Error_AUTHENTICATION;
  668. }
  669. if (!wrapper->isInitiator) {
  670. cryptoAuthDebug0(wrapper, "DROP a stray key packet");
  671. return Error_AUTHENTICATION;
  672. }
  673. // We sent the hello, this is a key
  674. getSharedSecret(sharedSecret,
  675. wrapper->ourTempPrivKey,
  676. wrapper->herPerminentPubKey,
  677. passwordHash,
  678. wrapper->context->logger);
  679. nextNonce = 4;
  680. }
  681. // Shift it on top of the authenticator before the encrypted public key
  682. Message_shift(message, 48 - Headers_CryptoAuth_SIZE, NULL);
  683. #ifdef Log_KEYS
  684. uint8_t sharedSecretHex[65];
  685. printHexKey(sharedSecretHex, sharedSecret);
  686. uint8_t nonceHex[49];
  687. Hex_encode(nonceHex, 49, header->handshake.nonce, 24);
  688. uint8_t cipherHex[65];
  689. printHexKey(cipherHex, message->bytes);
  690. Log_keys(wrapper->context->logger,
  691. "Decrypting message with:\n"
  692. " nonce: %s\n"
  693. " secret: %s\n"
  694. " cipher: %s\n",
  695. nonceHex, sharedSecretHex, cipherHex);
  696. #endif
  697. // Decrypt her temp public key and the message.
  698. if (decryptRndNonce(header->handshake.nonce, message, sharedSecret) != 0) {
  699. // just in case
  700. Bits_memset(header, 0, Headers_CryptoAuth_SIZE);
  701. cryptoAuthDebug(wrapper, "DROP message with nonce [%d], decryption failed", nonce);
  702. return Error_AUTHENTICATION;
  703. }
  704. #ifdef Log_DEBUG
  705. Assert_true(!Bits_isZero(header->handshake.encryptedTempKey, 32));
  706. #endif
  707. #ifdef Log_KEYS
  708. uint8_t tempKeyHex[65];
  709. Hex_encode(tempKeyHex, 65, wrapper->tempKey, 32);
  710. Log_keys(wrapper->context->logger,
  711. "Unwrapping temp public key:\n"
  712. " %s\n",
  713. tempKeyHex);
  714. #endif
  715. Message_shift(message, -32, NULL);
  716. // Post-decryption checking
  717. if (nonce == 0) {
  718. // A new hello packet
  719. if (!Bits_memcmp(wrapper->herTempPubKey, header->handshake.encryptedTempKey, 32)) {
  720. // possible replay attack or duped packet
  721. cryptoAuthDebug0(wrapper, "DROP dupe hello packet with same temp key");
  722. return Error_AUTHENTICATION;
  723. }
  724. } else if (nonce == 2 && wrapper->nextNonce >= 4) {
  725. // we accept a new key packet and let it change the session since the other end might have
  726. // killed off the session while it was in the midst of setting up.
  727. if (!Bits_memcmp(wrapper->herTempPubKey, header->handshake.encryptedTempKey, 32)) {
  728. Assert_always(!Bits_isZero(wrapper->herTempPubKey, 32));
  729. cryptoAuthDebug0(wrapper, "DROP dupe key packet with same temp key");
  730. return Error_AUTHENTICATION;
  731. }
  732. } else if (nonce == 3 && wrapper->nextNonce >= 4) {
  733. // Got a repeat key packet, make sure the temp key is the same as the one we know.
  734. if (Bits_memcmp(wrapper->herTempPubKey, header->handshake.encryptedTempKey, 32)) {
  735. Assert_always(!Bits_isZero(wrapper->herTempPubKey, 32));
  736. cryptoAuthDebug0(wrapper, "DROP repeat key packet with different temp key");
  737. return Error_AUTHENTICATION;
  738. }
  739. }
  740. // If Alice sent a hello packet then Bob sent a hello packet and they crossed on the wire,
  741. // somebody has to yield and the other has to stand firm otherwise they will either deadlock
  742. // each believing their hello packet is superior or they will livelock, each switching to the
  743. // other's session and never synchronizing.
  744. // In this event whoever has the lower permanent public key wins.
  745. // If we receive a (possibly repeat) key packet
  746. if (nextNonce == 4) {
  747. if (wrapper->nextNonce <= 4) {
  748. // and have not yet begun sending "run" data
  749. Assert_always(wrapper->nextNonce <= nextNonce);
  750. wrapper->nextNonce = nextNonce;
  751. wrapper->user = user;
  752. Bits_memcpyConst(wrapper->herTempPubKey, header->handshake.encryptedTempKey, 32);
  753. } else {
  754. // It's a (possibly repeat) key packet and we have begun sending run data.
  755. // We will change the shared secret to the one specified in the new key packet but
  756. // intentionally avoid de-incrementing the nonce just in case
  757. getSharedSecret(wrapper->sharedSecret,
  758. wrapper->ourTempPrivKey,
  759. header->handshake.encryptedTempKey,
  760. NULL,
  761. wrapper->context->logger);
  762. cryptoAuthDebug0(wrapper, "New key packet but we are already sending data");
  763. }
  764. } else if (nextNonce == 2 && (!wrapper->isInitiator || wrapper->established)) {
  765. // This is a hello packet and we are either in ESTABLISHED state or we are
  766. // not the initiator of the connection.
  767. // If the case is that we are in ESTABLISHED state, the other side tore down the session
  768. // and we have not so lets tear it down.
  769. // If we are not in ESTABLISHED state then we don't allow resetting of the session unless
  770. // they are the sender of the hello packet or their permanent public key is lower.
  771. // this is a tie-breaker in case hello packets cross on the wire.
  772. if (wrapper->established) {
  773. reset(wrapper);
  774. }
  775. // We got a (possibly repeat) hello packet and we have not sent any hello packet,
  776. // new session.
  777. if (wrapper->nextNonce == 3 && nextNonce == 2) {
  778. // We sent a key packet so the next packet is a repeat key but we got another hello
  779. // We'll just keep steaming along sending repeat key packets
  780. nextNonce = 3;
  781. }
  782. Assert_always(wrapper->nextNonce <= nextNonce);
  783. wrapper->nextNonce = nextNonce;
  784. wrapper->user = user;
  785. Bits_memcpyConst(wrapper->herTempPubKey, header->handshake.encryptedTempKey, 32);
  786. } else if (nextNonce == 2
  787. && Bits_memcmp(header->handshake.publicKey, wrapper->context->pub.publicKey, 32) < 0)
  788. {
  789. // It's a hello and we are the initiator but their permant public key is numerically lower
  790. // than ours, this is so that in the event of two hello packets crossing on the wire, the
  791. // nodes will agree on who is the initiator.
  792. cryptoAuthDebug0(wrapper, "Incoming hello from node with lower key, resetting");
  793. reset(wrapper);
  794. Assert_always(wrapper->nextNonce <= nextNonce);
  795. wrapper->nextNonce = nextNonce;
  796. wrapper->user = user;
  797. Bits_memcpyConst(wrapper->herTempPubKey, header->handshake.encryptedTempKey, 32);
  798. } else {
  799. cryptoAuthDebug0(wrapper, "Incoming hello from node with higher key, not resetting");
  800. }
  801. if (herPermKey && herPermKey != wrapper->herPerminentPubKey) {
  802. Bits_memcpyConst(wrapper->herPerminentPubKey, herPermKey, 32);
  803. }
  804. // If this is a handshake which was initiated in reverse because we
  805. // didn't know the other node's key, now send what we were going to send.
  806. if (wrapper->bufferedMessage) {
  807. // This can only happen when we have received a (maybe repeat) hello packet.
  808. Assert_true(wrapper->nextNonce == 2);
  809. struct Message* bm = wrapper->bufferedMessage;
  810. wrapper->bufferedMessage = NULL;
  811. cryptoAuthDebug0(wrapper, "Sending buffered message");
  812. sendMessage(bm, &wrapper->externalInterface);
  813. Allocator_free(bm->alloc);
  814. }
  815. if (message->length == 0 && Headers_isSetupPacket(&header->handshake.auth)) {
  816. return Error_NONE;
  817. }
  818. Bits_memset(&wrapper->replayProtector, 0, sizeof(struct ReplayProtector));
  819. setRequiredPadding(wrapper);
  820. return callReceivedMessage(wrapper, message);
  821. }
  822. static uint8_t receiveMessage(struct Message* received, struct Interface* interface)
  823. {
  824. struct CryptoAuth_Wrapper* wrapper =
  825. Identity_check((struct CryptoAuth_Wrapper*) interface->receiverContext);
  826. union Headers_CryptoAuth* header = (union Headers_CryptoAuth*) received->bytes;
  827. if (received->length < 20) {
  828. cryptoAuthDebug0(wrapper, "DROP runt");
  829. return Error_UNDERSIZE_MESSAGE;
  830. }
  831. Assert_true(received->padding >= 12 || "need at least 12 bytes of padding in incoming message");
  832. #ifdef Log_DEBUG
  833. Assert_true(!((uintptr_t)received->bytes % 4) || !"alignment fault");
  834. #endif
  835. Message_shift(received, -4, NULL);
  836. uint32_t nonce = Endian_bigEndianToHost32(header->nonce);
  837. if (!wrapper->established) {
  838. if (nonce > 3 && nonce != UINT32_MAX) {
  839. if (wrapper->nextNonce < 3) {
  840. // This is impossible because we have not exchanged hello and key messages.
  841. cryptoAuthDebug0(wrapper, "DROP Received a run message to an un-setup session");
  842. return Error_UNDELIVERABLE;
  843. }
  844. cryptoAuthDebug(wrapper, "Trying final handshake step, nonce=%u\n", nonce);
  845. uint8_t secret[32];
  846. Assert_true(!Bits_isZero(wrapper->ourTempPrivKey, 32));
  847. Assert_true(!Bits_isZero(wrapper->herTempPubKey, 32));
  848. getSharedSecret(secret,
  849. wrapper->ourTempPrivKey,
  850. wrapper->herTempPubKey,
  851. NULL,
  852. wrapper->context->logger);
  853. // We'll optimistically advance the nextNonce value because decryptMessage()
  854. // passes the message on to the upper level and if this message causes a
  855. // response, we want the CA to be in ESTABLISHED state.
  856. // if the decryptMessage() call fails, we CryptoAuth_reset() it back.
  857. wrapper->nextNonce += 3;
  858. if (decryptMessage(wrapper, nonce, received, secret)) {
  859. cryptoAuthDebug0(wrapper, "Final handshake step succeeded");
  860. Bits_memcpyConst(wrapper->sharedSecret, secret, 32);
  861. // Now we're in run mode, no more handshake packets will be accepted
  862. Bits_memset(wrapper->ourTempPrivKey, 0, 32);
  863. Bits_memset(wrapper->ourTempPubKey, 0, 32);
  864. Bits_memset(wrapper->herTempPubKey, 0, 32);
  865. wrapper->established = true;
  866. return callReceivedMessage(wrapper, received);
  867. }
  868. CryptoAuth_reset(&wrapper->externalInterface);
  869. cryptoAuthDebug0(wrapper, "DROP Final handshake step failed");
  870. return Error_UNDELIVERABLE;
  871. }
  872. Message_shift(received, 4, NULL);
  873. return decryptHandshake(wrapper, nonce, received, header);
  874. } else if (nonce > 3 && nonce != UINT32_MAX) {
  875. Assert_true(!Bits_isZero(wrapper->sharedSecret, 32));
  876. if (decryptMessage(wrapper, nonce, received, wrapper->sharedSecret)) {
  877. return callReceivedMessage(wrapper, received);
  878. } else {
  879. cryptoAuthDebug0(wrapper, "DROP Failed to decrypt message");
  880. return Error_UNDELIVERABLE;
  881. }
  882. } else if (nonce < 2) {
  883. cryptoAuthDebug(wrapper, "hello packet during established session nonce=[%d]", nonce);
  884. Message_shift(received, 4, NULL);
  885. return decryptHandshake(wrapper, nonce, received, header);
  886. } else {
  887. // setup keys are already zeroed, not much we can do here.
  888. cryptoAuthDebug(wrapper, "DROP key packet during established session nonce=[%d]", nonce);
  889. return Error_UNDELIVERABLE;
  890. }
  891. Assert_always(0);
  892. }
  893. /////////////////////////////////////////////////////////////////////////////////////////////////
  894. struct CryptoAuth* CryptoAuth_new(struct Allocator* allocator,
  895. const uint8_t* privateKey,
  896. struct EventBase* eventBase,
  897. struct Log* logger,
  898. struct Random* rand)
  899. {
  900. struct CryptoAuth_pvt* ca = Allocator_calloc(allocator, sizeof(struct CryptoAuth_pvt), 1);
  901. ca->allocator = allocator;
  902. ca->passwords = Allocator_calloc(allocator, sizeof(struct CryptoAuth_Auth), 256);
  903. ca->passwordCount = 0;
  904. ca->passwordCapacity = 256;
  905. ca->eventBase = eventBase;
  906. ca->logger = logger;
  907. ca->pub.resetAfterInactivitySeconds = CryptoAuth_DEFAULT_RESET_AFTER_INACTIVITY_SECONDS;
  908. ca->rand = rand;
  909. Identity_set(ca);
  910. if (privateKey != NULL) {
  911. Bits_memcpyConst(ca->privateKey, privateKey, 32);
  912. } else {
  913. Random_bytes(rand, ca->privateKey, 32);
  914. }
  915. crypto_scalarmult_curve25519_base(ca->pub.publicKey, ca->privateKey);
  916. #ifdef Log_KEYS
  917. uint8_t publicKeyHex[65];
  918. printHexKey(publicKeyHex, ca->pub.publicKey);
  919. uint8_t privateKeyHex[65];
  920. printHexKey(privateKeyHex, ca->privateKey);
  921. Log_keys(logger,
  922. "Initialized CryptoAuth:\n myPrivateKey=%s\n myPublicKey=%s\n",
  923. privateKeyHex,
  924. publicKeyHex);
  925. #endif
  926. return &ca->pub;
  927. }
  928. int32_t CryptoAuth_addUser(String* password,
  929. uint8_t authType,
  930. String* user,
  931. struct CryptoAuth* ca)
  932. {
  933. struct CryptoAuth_pvt* context = Identity_check((struct CryptoAuth_pvt*) ca);
  934. if (authType != 1) {
  935. return CryptoAuth_addUser_INVALID_AUTHTYPE;
  936. }
  937. if (context->passwordCount == context->passwordCapacity) {
  938. // TODO: realloc password space and increase buffer.
  939. return CryptoAuth_addUser_OUT_OF_SPACE;
  940. }
  941. struct CryptoAuth_Auth a;
  942. hashPassword_sha256(&a, password);
  943. for (uint32_t i = 0; i < context->passwordCount; i++) {
  944. if (!Bits_memcmp(a.secret, context->passwords[i].secret, 32) ||
  945. String_equals(user, context->passwords[i].user)) {
  946. return CryptoAuth_addUser_DUPLICATE;
  947. }
  948. }
  949. a.user = String_new(user->bytes, context->allocator);
  950. Bits_memcpyConst(&context->passwords[context->passwordCount],
  951. &a,
  952. sizeof(struct CryptoAuth_Auth));
  953. context->passwordCount++;
  954. return 0;
  955. }
  956. int CryptoAuth_removeUsers(struct CryptoAuth* context, String* user)
  957. {
  958. struct CryptoAuth_pvt* ctx = Identity_check((struct CryptoAuth_pvt*) context);
  959. if (!user) {
  960. int count = ctx->passwordCount;
  961. Log_debug(ctx->logger, "Flushing [%d] users", count);
  962. ctx->passwordCount = 0;
  963. return count;
  964. }
  965. int count = 0;
  966. int i = 0;
  967. while (i < (int)ctx->passwordCount) {
  968. if (String_equals(ctx->passwords[i].user, user)) {
  969. Bits_memcpyConst(&ctx->passwords[i],
  970. &ctx->passwords[ctx->passwordCount--],
  971. sizeof(struct CryptoAuth_Auth));
  972. count++;
  973. } else {
  974. i++;
  975. }
  976. }
  977. Log_debug(ctx->logger, "Removing [%d] user(s) identified by [%s]", count, user->bytes);
  978. return count;
  979. }
  980. List* CryptoAuth_getUsers(struct CryptoAuth* context, struct Allocator* alloc)
  981. {
  982. struct CryptoAuth_pvt* ctx = Identity_check((struct CryptoAuth_pvt*) context);
  983. uint32_t count = ctx->passwordCount;
  984. List* users = NULL;
  985. for (uint32_t i = 0; i < count; i++ )
  986. {
  987. users = List_addString(users, String_clone(ctx->passwords[i].user, alloc), alloc);
  988. }
  989. return users;
  990. }
  991. String* CryptoAuth_getUser(struct Interface* interface)
  992. {
  993. struct CryptoAuth_Wrapper* wrapper =
  994. Identity_check((struct CryptoAuth_Wrapper*)interface->senderContext);
  995. String* user = wrapper->user;
  996. if (user) {
  997. // If the user was lost in flushusers, then we need to return null.
  998. for (uint32_t i = 0; i < wrapper->context->passwordCount; i++) {
  999. if (user == wrapper->context->passwords[i].user) {
  1000. return user;
  1001. }
  1002. }
  1003. // Null it since it's been removed.
  1004. wrapper->user = NULL;
  1005. }
  1006. return NULL;
  1007. }
  1008. struct Interface* CryptoAuth_wrapInterface(struct Interface* toWrap,
  1009. const uint8_t herPublicKey[32],
  1010. const uint8_t herIp6[16],
  1011. const bool requireAuth,
  1012. char* name,
  1013. struct CryptoAuth* ca)
  1014. {
  1015. struct CryptoAuth_pvt* context = Identity_check((struct CryptoAuth_pvt*) ca);
  1016. struct CryptoAuth_Wrapper* wrapper = Allocator_clone(toWrap->allocator,
  1017. (&(struct CryptoAuth_Wrapper) {
  1018. .user = NULL,
  1019. .nextNonce = 0,
  1020. .context = context,
  1021. .wrappedInterface = toWrap,
  1022. .requireAuth = requireAuth,
  1023. .name = name
  1024. }));
  1025. wrapper->timeOfLastPacket = Time_currentTimeSeconds(context->eventBase);
  1026. Identity_set(wrapper);
  1027. toWrap->receiverContext = wrapper;
  1028. toWrap->receiveMessage = receiveMessage;
  1029. struct Interface iface = {
  1030. .senderContext = wrapper,
  1031. .sendMessage = sendMessage,
  1032. .allocator = toWrap->allocator
  1033. };
  1034. Bits_memcpyConst(&wrapper->externalInterface, &iface, sizeof(struct Interface));
  1035. if (herPublicKey != NULL) {
  1036. Bits_memcpyConst(wrapper->herPerminentPubKey, herPublicKey, 32);
  1037. uint8_t calculatedIp6[16];
  1038. AddressCalc_addressForPublicKey(calculatedIp6, herPublicKey);
  1039. Bits_memcpyConst(wrapper->herIp6, calculatedIp6, 16);
  1040. if (herIp6 != NULL) {
  1041. Assert_always(!Bits_memcmp(calculatedIp6, herIp6, 16));
  1042. }
  1043. } else if (herIp6) {
  1044. Bits_memcpyConst(wrapper->herIp6, herIp6, 16);
  1045. }
  1046. return &wrapper->externalInterface;
  1047. }
  1048. void CryptoAuth_setAuth(const String* password,
  1049. const uint8_t authType,
  1050. struct Interface* wrappedInterface)
  1051. {
  1052. struct CryptoAuth_Wrapper* wrapper =
  1053. Identity_check((struct CryptoAuth_Wrapper*)wrappedInterface->senderContext);
  1054. wrapper->password = (password != NULL)
  1055. ? String_newBinary(password->bytes, password->len, wrappedInterface->allocator)
  1056. : NULL;
  1057. wrapper->authType = (password != NULL) ? authType : 0;
  1058. }
  1059. uint8_t* CryptoAuth_getHerPublicKey(struct Interface* interface)
  1060. {
  1061. return ((struct CryptoAuth_Wrapper*) interface->senderContext)->herPerminentPubKey;
  1062. }
  1063. void CryptoAuth_reset(struct Interface* interface)
  1064. {
  1065. struct CryptoAuth_Wrapper* wrapper =
  1066. Identity_check((struct CryptoAuth_Wrapper*)interface->senderContext);
  1067. reset(wrapper);
  1068. }
  1069. int CryptoAuth_getState(struct Interface* interface)
  1070. {
  1071. struct CryptoAuth_Wrapper* wrapper =
  1072. Identity_check((struct CryptoAuth_Wrapper*)interface->senderContext);
  1073. switch (wrapper->nextNonce) {
  1074. case 0:
  1075. return CryptoAuth_NEW;
  1076. case 1: // Sent a hello, waiting for the key
  1077. return CryptoAuth_HANDSHAKE1;
  1078. case 2: // Received a hello, sent a key packet.
  1079. case 3: // Received a hello, sent multiple key packets.
  1080. return CryptoAuth_HANDSHAKE2;
  1081. case 4:
  1082. // state 4 = waiting for first data packet to prove the handshake succeeded.
  1083. // At this point you have sent a challenge and received a response so it is safe
  1084. // to assume you are not being hit with replay packets.
  1085. //
  1086. // Sent a hello, received one or more keys, waiting for data.
  1087. // In this state data packets will be sent but no data packets have yet been received.
  1088. return CryptoAuth_HANDSHAKE3;
  1089. default:
  1090. // Received data.
  1091. return (wrapper->established) ? CryptoAuth_ESTABLISHED : CryptoAuth_HANDSHAKE3;
  1092. }
  1093. }
  1094. void CryptoAuth_resetIfTimeout(struct Interface* iface)
  1095. {
  1096. struct CryptoAuth_Wrapper* wrapper =
  1097. Identity_check((struct CryptoAuth_Wrapper*)iface->senderContext);
  1098. if (wrapper->nextNonce == 1) {
  1099. // Lets not reset the session, we just sent one or more hello packets and
  1100. // have not received a response, if they respond after we reset then we'll
  1101. // be in a tough state.
  1102. return;
  1103. }
  1104. uint64_t nowSecs = Time_currentTimeSeconds(wrapper->context->eventBase);
  1105. if (nowSecs - wrapper->timeOfLastPacket > wrapper->context->pub.resetAfterInactivitySeconds) {
  1106. cryptoAuthDebug(wrapper, "No traffic in [%d] seconds, resetting connection.",
  1107. (int) (nowSecs - wrapper->timeOfLastPacket));
  1108. wrapper->timeOfLastPacket = nowSecs;
  1109. reset(wrapper);
  1110. }
  1111. }
  1112. struct Interface* CryptoAuth_getConnectedInterface(struct Interface* iface)
  1113. {
  1114. if (iface->sendMessage == sendMessage) {
  1115. // internal (plaintext side)
  1116. struct CryptoAuth_Wrapper* wrapper =
  1117. Identity_check((struct CryptoAuth_Wrapper*)iface->senderContext);
  1118. return wrapper->wrappedInterface;
  1119. } else if (iface->receiveMessage == receiveMessage) {
  1120. struct CryptoAuth_Wrapper* wrapper =
  1121. Identity_check((struct CryptoAuth_Wrapper*)iface->receiverContext);
  1122. return &wrapper->externalInterface;
  1123. }
  1124. return NULL;
  1125. }
  1126. struct ReplayProtector* CryptoAuth_getReplayProtector(struct Interface* iface)
  1127. {
  1128. struct CryptoAuth_Wrapper* wrapper =
  1129. Identity_check((struct CryptoAuth_Wrapper*)iface->senderContext);
  1130. return &wrapper->replayProtector;
  1131. }
  1132. // For testing:
  1133. void CryptoAuth_encryptRndNonce(uint8_t nonce[24], struct Message* msg, uint8_t secret[32])
  1134. {
  1135. encryptRndNonce(nonce, msg, secret);
  1136. }
  1137. int CryptoAuth_decryptRndNonce(uint8_t nonce[24], struct Message* msg, uint8_t secret[32])
  1138. {
  1139. return decryptRndNonce(nonce, msg, secret);
  1140. }
  1141. uint8_t CryptoAuth_encryptHandshake(struct Message* message,
  1142. struct CryptoAuth_Wrapper* wrapper,
  1143. int setupMessage)
  1144. {
  1145. return encryptHandshake(message, wrapper, setupMessage);
  1146. }
  1147. uint8_t CryptoAuth_receiveMessage(struct Message* received, struct Interface* interface)
  1148. {
  1149. return receiveMessage(received, interface);
  1150. }