CryptoAuth.c 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305
  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_true(!"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_ifParanoid(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_true(!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_ifParanoid(!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. Assert_true(!((uintptr_t)message->bytes % 4) || !"alignment fault");
  514. // nextNonce 0: sending hello, we are initiating connection.
  515. // nextNonce 1: sending another hello, nothing received yet.
  516. // nextNonce 2: sending key, hello received.
  517. // nextNonce 3: sending key again, no data packet recieved yet.
  518. // nextNonce >3: handshake complete
  519. //
  520. // if it's a blind handshake, every message will be empty and nextNonce will remain
  521. // zero until the first message is received back.
  522. if (wrapper->nextNonce < 5) {
  523. if (wrapper->nextNonce < 4) {
  524. return encryptHandshake(message, wrapper, 0);
  525. } else {
  526. cryptoAuthDebug0(wrapper, "Doing final step to send message. nonce=4");
  527. Assert_ifParanoid(!Bits_isZero(wrapper->ourTempPrivKey, 32));
  528. Assert_ifParanoid(!Bits_isZero(wrapper->herTempPubKey, 32));
  529. getSharedSecret(wrapper->sharedSecret,
  530. wrapper->ourTempPrivKey,
  531. wrapper->herTempPubKey,
  532. NULL,
  533. wrapper->context->logger);
  534. }
  535. }
  536. Assert_true(message->length > 0 && "Empty packet during handshake");
  537. return encryptMessage(message, wrapper);
  538. }
  539. /** Call the external interface and tell it that a message has been received. */
  540. static inline uint8_t callReceivedMessage(struct CryptoAuth_Wrapper* wrapper,
  541. struct Message* message)
  542. {
  543. wrapper->timeOfLastPacket = Time_currentTimeSeconds(wrapper->context->eventBase);
  544. uint8_t ret = 0;
  545. if (wrapper->externalInterface.receiveMessage != NULL) {
  546. ret = wrapper->externalInterface.receiveMessage(message, &wrapper->externalInterface);
  547. }
  548. return ret;
  549. }
  550. static inline bool decryptMessage(struct CryptoAuth_Wrapper* wrapper,
  551. uint32_t nonce,
  552. struct Message* content,
  553. uint8_t secret[32])
  554. {
  555. // Decrypt with authentication and replay prevention.
  556. if (decrypt(nonce, content, secret, wrapper->isInitiator)) {
  557. cryptoAuthDebug0(wrapper, "DROP authenticated decryption failed");
  558. return false;
  559. }
  560. if (!ReplayProtector_checkNonce(nonce, &wrapper->replayProtector)) {
  561. cryptoAuthDebug(wrapper, "DROP nonce checking failed nonce=[%u]", nonce);
  562. return false;
  563. }
  564. return true;
  565. }
  566. static uint8_t decryptHandshake(struct CryptoAuth_Wrapper* wrapper,
  567. const uint32_t nonce,
  568. struct Message* message,
  569. union Headers_CryptoAuth* header)
  570. {
  571. if (message->length < Headers_CryptoAuth_SIZE) {
  572. cryptoAuthDebug0(wrapper, "DROP runt");
  573. return Error_UNDERSIZE_MESSAGE;
  574. }
  575. // handshake
  576. // nextNonce 0: recieving hello.
  577. // nextNonce 1: recieving key, we sent hello.
  578. // nextNonce 2: recieving first data packet or duplicate hello.
  579. // nextNonce 3: recieving first data packet.
  580. // nextNonce >3: handshake complete
  581. if (knowHerKey(wrapper)) {
  582. if (Bits_memcmp(wrapper->herPerminentPubKey, header->handshake.publicKey, 32)) {
  583. cryptoAuthDebug0(wrapper, "DROP a packet with different public key than this session");
  584. return Error_AUTHENTICATION;
  585. }
  586. } else if (!Bits_isZero(wrapper->herIp6, 16)) {
  587. uint8_t calculatedIp6[16];
  588. AddressCalc_addressForPublicKey(calculatedIp6, header->handshake.publicKey);
  589. if (Bits_memcmp(wrapper->herIp6, calculatedIp6, 16)) {
  590. cryptoAuthDebug0(wrapper, "DROP packet with public key not matching ip6 for session");
  591. return Error_AUTHENTICATION;
  592. }
  593. }
  594. if (wrapper->nextNonce < 2 && nonce == UINT32_MAX && !wrapper->requireAuth) {
  595. // Reset without knowing key is allowed until state reaches 2.
  596. // this is because we don't know that the other end knows our key until we
  597. // have received a valid packet from them.
  598. // We can't allow the upper layer to see this message because it's not authenticated.
  599. if (!knowHerKey(wrapper)) {
  600. Bits_memcpyConst(wrapper->herPerminentPubKey, header->handshake.publicKey, 32);
  601. }
  602. Message_shift(message, -Headers_CryptoAuth_SIZE, NULL);
  603. message->length = 0;
  604. reset(wrapper);
  605. wrapper->user = NULL;
  606. cryptoAuthDebug0(wrapper, "Got a connect-to-me message, sending a hello");
  607. // Send an empty response (to initiate the connection).
  608. encryptHandshake(message, wrapper, 1);
  609. return Error_NONE;
  610. }
  611. String* user = NULL;
  612. uint8_t passwordHashStore[32];
  613. uint8_t* passwordHash = tryAuth(header, passwordHashStore, wrapper, &user);
  614. if (wrapper->requireAuth && !user) {
  615. cryptoAuthDebug0(wrapper, "DROP message because auth was not given");
  616. return Error_AUTHENTICATION;
  617. }
  618. if (passwordHash == NULL && header->handshake.auth.challenge.type != 0) {
  619. cryptoAuthDebug0(wrapper, "DROP message with unrecognized authenticator");
  620. return Error_AUTHENTICATION;
  621. }
  622. // What the nextNonce will become if this packet is valid.
  623. uint32_t nextNonce;
  624. // The secret for decrypting this message.
  625. uint8_t sharedSecret[32];
  626. uint8_t* herPermKey = NULL;
  627. if (nonce < 2) {
  628. if (nonce == 0) {
  629. cryptoAuthDebug(wrapper, "Received a hello packet, using auth: %d",
  630. (passwordHash != NULL));
  631. } else {
  632. cryptoAuthDebug0(wrapper, "Received a repeat hello packet");
  633. }
  634. // Decrypt message with perminent keys.
  635. if (!knowHerKey(wrapper) || wrapper->nextNonce == 0) {
  636. herPermKey = header->handshake.publicKey;
  637. #ifdef Log_DEBUG
  638. if (Bits_isZero(header->handshake.publicKey, 32)) {
  639. cryptoAuthDebug0(wrapper, "Node sent public key of ZERO!");
  640. }
  641. #endif
  642. } else {
  643. herPermKey = wrapper->herPerminentPubKey;
  644. if (Bits_memcmp(header->handshake.publicKey, herPermKey, 32)) {
  645. cryptoAuthDebug0(wrapper, "DROP packet contains different perminent key");
  646. return Error_AUTHENTICATION;
  647. }
  648. }
  649. getSharedSecret(sharedSecret,
  650. wrapper->context->privateKey,
  651. herPermKey,
  652. passwordHash,
  653. wrapper->context->logger);
  654. nextNonce = 2;
  655. } else {
  656. if (nonce == 2) {
  657. cryptoAuthDebug0(wrapper, "Received a key packet");
  658. } else if (nonce == 3) {
  659. cryptoAuthDebug0(wrapper, "Received a repeat key packet");
  660. } else {
  661. cryptoAuthDebug(wrapper, "Received a packet of unknown type! nonce=%u", nonce);
  662. }
  663. if (Bits_memcmp(header->handshake.publicKey, wrapper->herPerminentPubKey, 32)) {
  664. cryptoAuthDebug0(wrapper, "DROP packet contains different perminent key");
  665. return Error_AUTHENTICATION;
  666. }
  667. if (!wrapper->isInitiator) {
  668. cryptoAuthDebug0(wrapper, "DROP a stray key packet");
  669. return Error_AUTHENTICATION;
  670. }
  671. // We sent the hello, this is a key
  672. getSharedSecret(sharedSecret,
  673. wrapper->ourTempPrivKey,
  674. wrapper->herPerminentPubKey,
  675. passwordHash,
  676. wrapper->context->logger);
  677. nextNonce = 4;
  678. }
  679. // Shift it on top of the authenticator before the encrypted public key
  680. Message_shift(message, 48 - Headers_CryptoAuth_SIZE, NULL);
  681. #ifdef Log_KEYS
  682. uint8_t sharedSecretHex[65];
  683. printHexKey(sharedSecretHex, sharedSecret);
  684. uint8_t nonceHex[49];
  685. Hex_encode(nonceHex, 49, header->handshake.nonce, 24);
  686. uint8_t cipherHex[65];
  687. printHexKey(cipherHex, message->bytes);
  688. Log_keys(wrapper->context->logger,
  689. "Decrypting message with:\n"
  690. " nonce: %s\n"
  691. " secret: %s\n"
  692. " cipher: %s\n",
  693. nonceHex, sharedSecretHex, cipherHex);
  694. #endif
  695. // Decrypt her temp public key and the message.
  696. if (decryptRndNonce(header->handshake.nonce, message, sharedSecret) != 0) {
  697. // just in case
  698. Bits_memset(header, 0, Headers_CryptoAuth_SIZE);
  699. cryptoAuthDebug(wrapper, "DROP message with nonce [%d], decryption failed", nonce);
  700. return Error_AUTHENTICATION;
  701. }
  702. Assert_ifParanoid(!Bits_isZero(header->handshake.encryptedTempKey, 32));
  703. #ifdef Log_KEYS
  704. uint8_t tempKeyHex[65];
  705. Hex_encode(tempKeyHex, 65, header->handshake.encryptedTempKey, 32);
  706. Log_keys(wrapper->context->logger,
  707. "Unwrapping temp public key:\n"
  708. " %s\n",
  709. tempKeyHex);
  710. #endif
  711. Message_shift(message, -32, NULL);
  712. // Post-decryption checking
  713. if (nonce == 0) {
  714. // A new hello packet
  715. if (!Bits_memcmp(wrapper->herTempPubKey, header->handshake.encryptedTempKey, 32)) {
  716. // possible replay attack or duped packet
  717. cryptoAuthDebug0(wrapper, "DROP dupe hello packet with same temp key");
  718. return Error_AUTHENTICATION;
  719. }
  720. } else if (nonce == 2 && wrapper->nextNonce >= 4) {
  721. // we accept a new key packet and let it change the session since the other end might have
  722. // killed off the session while it was in the midst of setting up.
  723. if (!Bits_memcmp(wrapper->herTempPubKey, header->handshake.encryptedTempKey, 32)) {
  724. Assert_true(!Bits_isZero(wrapper->herTempPubKey, 32));
  725. cryptoAuthDebug0(wrapper, "DROP dupe key packet with same temp key");
  726. return Error_AUTHENTICATION;
  727. }
  728. } else if (nonce == 3 && wrapper->nextNonce >= 4) {
  729. // Got a repeat key packet, make sure the temp key is the same as the one we know.
  730. if (Bits_memcmp(wrapper->herTempPubKey, header->handshake.encryptedTempKey, 32)) {
  731. Assert_true(!Bits_isZero(wrapper->herTempPubKey, 32));
  732. cryptoAuthDebug0(wrapper, "DROP repeat key packet with different temp key");
  733. return Error_AUTHENTICATION;
  734. }
  735. }
  736. // If Alice sent a hello packet then Bob sent a hello packet and they crossed on the wire,
  737. // somebody has to yield and the other has to stand firm otherwise they will either deadlock
  738. // each believing their hello packet is superior or they will livelock, each switching to the
  739. // other's session and never synchronizing.
  740. // In this event whoever has the lower permanent public key wins.
  741. // If we receive a (possibly repeat) key packet
  742. if (nextNonce == 4) {
  743. if (wrapper->nextNonce <= 4) {
  744. // and have not yet begun sending "run" data
  745. Assert_true(wrapper->nextNonce <= nextNonce);
  746. wrapper->nextNonce = nextNonce;
  747. wrapper->user = user;
  748. Bits_memcpyConst(wrapper->herTempPubKey, header->handshake.encryptedTempKey, 32);
  749. } else {
  750. // It's a (possibly repeat) key packet and we have begun sending run data.
  751. // We will change the shared secret to the one specified in the new key packet but
  752. // intentionally avoid de-incrementing the nonce just in case
  753. getSharedSecret(wrapper->sharedSecret,
  754. wrapper->ourTempPrivKey,
  755. header->handshake.encryptedTempKey,
  756. NULL,
  757. wrapper->context->logger);
  758. cryptoAuthDebug0(wrapper, "New key packet but we are already sending data");
  759. }
  760. } else if (nextNonce == 2 && (!wrapper->isInitiator || wrapper->established)) {
  761. // This is a hello packet and we are either in ESTABLISHED state or we are
  762. // not the initiator of the connection.
  763. // If the case is that we are in ESTABLISHED state, the other side tore down the session
  764. // and we have not so lets tear it down.
  765. // If we are not in ESTABLISHED state then we don't allow resetting of the session unless
  766. // they are the sender of the hello packet or their permanent public key is lower.
  767. // this is a tie-breaker in case hello packets cross on the wire.
  768. if (wrapper->established) {
  769. reset(wrapper);
  770. }
  771. // We got a (possibly repeat) hello packet and we have not sent any hello packet,
  772. // new session.
  773. if (wrapper->nextNonce == 3 && nextNonce == 2) {
  774. // We sent a key packet so the next packet is a repeat key but we got another hello
  775. // We'll just keep steaming along sending repeat key packets
  776. nextNonce = 3;
  777. }
  778. Assert_true(wrapper->nextNonce <= nextNonce);
  779. wrapper->nextNonce = nextNonce;
  780. wrapper->user = user;
  781. Bits_memcpyConst(wrapper->herTempPubKey, header->handshake.encryptedTempKey, 32);
  782. } else if (nextNonce == 2
  783. && Bits_memcmp(header->handshake.publicKey, wrapper->context->pub.publicKey, 32) < 0)
  784. {
  785. // It's a hello and we are the initiator but their permant public key is numerically lower
  786. // than ours, this is so that in the event of two hello packets crossing on the wire, the
  787. // nodes will agree on who is the initiator.
  788. cryptoAuthDebug0(wrapper, "Incoming hello from node with lower key, resetting");
  789. reset(wrapper);
  790. Assert_true(wrapper->nextNonce <= nextNonce);
  791. wrapper->nextNonce = nextNonce;
  792. wrapper->user = user;
  793. Bits_memcpyConst(wrapper->herTempPubKey, header->handshake.encryptedTempKey, 32);
  794. } else {
  795. cryptoAuthDebug0(wrapper, "Incoming hello from node with higher key, not resetting");
  796. }
  797. if (herPermKey && herPermKey != wrapper->herPerminentPubKey) {
  798. Bits_memcpyConst(wrapper->herPerminentPubKey, herPermKey, 32);
  799. }
  800. // If this is a handshake which was initiated in reverse because we
  801. // didn't know the other node's key, now send what we were going to send.
  802. if (wrapper->bufferedMessage) {
  803. // This can only happen when we have received a (maybe repeat) hello packet.
  804. Assert_true(wrapper->nextNonce == 2);
  805. struct Message* bm = wrapper->bufferedMessage;
  806. wrapper->bufferedMessage = NULL;
  807. cryptoAuthDebug0(wrapper, "Sending buffered message");
  808. sendMessage(bm, &wrapper->externalInterface);
  809. Allocator_free(bm->alloc);
  810. }
  811. if (message->length == 0 && Headers_isSetupPacket(&header->handshake.auth)) {
  812. return Error_NONE;
  813. }
  814. Bits_memset(&wrapper->replayProtector, 0, sizeof(struct ReplayProtector));
  815. setRequiredPadding(wrapper);
  816. return callReceivedMessage(wrapper, message);
  817. }
  818. static uint8_t receiveMessage(struct Message* received, struct Interface* interface)
  819. {
  820. struct CryptoAuth_Wrapper* wrapper =
  821. Identity_check((struct CryptoAuth_Wrapper*) interface->receiverContext);
  822. union Headers_CryptoAuth* header = (union Headers_CryptoAuth*) received->bytes;
  823. if (received->length < 20) {
  824. cryptoAuthDebug0(wrapper, "DROP runt");
  825. return Error_UNDERSIZE_MESSAGE;
  826. }
  827. Assert_true(received->padding >= 12 || "need at least 12 bytes of padding in incoming message");
  828. Assert_true(!((uintptr_t)received->bytes % 4) || !"alignment fault");
  829. Message_shift(received, -4, NULL);
  830. uint32_t nonce = Endian_bigEndianToHost32(header->nonce);
  831. if (!wrapper->established) {
  832. if (nonce > 3 && nonce != UINT32_MAX) {
  833. if (wrapper->nextNonce < 3) {
  834. // This is impossible because we have not exchanged hello and key messages.
  835. cryptoAuthDebug0(wrapper, "DROP Received a run message to an un-setup session");
  836. return Error_UNDELIVERABLE;
  837. }
  838. cryptoAuthDebug(wrapper, "Trying final handshake step, nonce=%u\n", nonce);
  839. uint8_t secret[32];
  840. Assert_ifParanoid(!Bits_isZero(wrapper->ourTempPrivKey, 32));
  841. Assert_ifParanoid(!Bits_isZero(wrapper->herTempPubKey, 32));
  842. getSharedSecret(secret,
  843. wrapper->ourTempPrivKey,
  844. wrapper->herTempPubKey,
  845. NULL,
  846. wrapper->context->logger);
  847. // We'll optimistically advance the nextNonce value because decryptMessage()
  848. // passes the message on to the upper level and if this message causes a
  849. // response, we want the CA to be in ESTABLISHED state.
  850. // if the decryptMessage() call fails, we CryptoAuth_reset() it back.
  851. wrapper->nextNonce += 3;
  852. if (decryptMessage(wrapper, nonce, received, secret)) {
  853. cryptoAuthDebug0(wrapper, "Final handshake step succeeded");
  854. Bits_memcpyConst(wrapper->sharedSecret, secret, 32);
  855. // Now we're in run mode, no more handshake packets will be accepted
  856. Bits_memset(wrapper->ourTempPrivKey, 0, 32);
  857. Bits_memset(wrapper->ourTempPubKey, 0, 32);
  858. Bits_memset(wrapper->herTempPubKey, 0, 32);
  859. wrapper->established = true;
  860. return callReceivedMessage(wrapper, received);
  861. }
  862. CryptoAuth_reset(&wrapper->externalInterface);
  863. cryptoAuthDebug0(wrapper, "DROP Final handshake step failed");
  864. return Error_UNDELIVERABLE;
  865. }
  866. Message_shift(received, 4, NULL);
  867. return decryptHandshake(wrapper, nonce, received, header);
  868. } else if (nonce > 3 && nonce != UINT32_MAX) {
  869. Assert_ifParanoid(!Bits_isZero(wrapper->sharedSecret, 32));
  870. if (decryptMessage(wrapper, nonce, received, wrapper->sharedSecret)) {
  871. return callReceivedMessage(wrapper, received);
  872. } else {
  873. cryptoAuthDebug0(wrapper, "DROP Failed to decrypt message");
  874. return Error_UNDELIVERABLE;
  875. }
  876. } else if (nonce < 2) {
  877. cryptoAuthDebug(wrapper, "hello packet during established session nonce=[%d]", nonce);
  878. Message_shift(received, 4, NULL);
  879. return decryptHandshake(wrapper, nonce, received, header);
  880. } else {
  881. // setup keys are already zeroed, not much we can do here.
  882. cryptoAuthDebug(wrapper, "DROP key packet during established session nonce=[%d]", nonce);
  883. return Error_UNDELIVERABLE;
  884. }
  885. Assert_true(0);
  886. }
  887. /////////////////////////////////////////////////////////////////////////////////////////////////
  888. struct CryptoAuth* CryptoAuth_new(struct Allocator* allocator,
  889. const uint8_t* privateKey,
  890. struct EventBase* eventBase,
  891. struct Log* logger,
  892. struct Random* rand)
  893. {
  894. struct CryptoAuth_pvt* ca = Allocator_calloc(allocator, sizeof(struct CryptoAuth_pvt), 1);
  895. ca->allocator = allocator;
  896. ca->passwords = Allocator_calloc(allocator, sizeof(struct CryptoAuth_Auth), 256);
  897. ca->passwordCount = 0;
  898. ca->passwordCapacity = 256;
  899. ca->eventBase = eventBase;
  900. ca->logger = logger;
  901. ca->pub.resetAfterInactivitySeconds = CryptoAuth_DEFAULT_RESET_AFTER_INACTIVITY_SECONDS;
  902. ca->rand = rand;
  903. Identity_set(ca);
  904. if (privateKey != NULL) {
  905. Bits_memcpyConst(ca->privateKey, privateKey, 32);
  906. } else {
  907. Random_bytes(rand, ca->privateKey, 32);
  908. }
  909. crypto_scalarmult_curve25519_base(ca->pub.publicKey, ca->privateKey);
  910. #ifdef Log_KEYS
  911. uint8_t publicKeyHex[65];
  912. printHexKey(publicKeyHex, ca->pub.publicKey);
  913. uint8_t privateKeyHex[65];
  914. printHexKey(privateKeyHex, ca->privateKey);
  915. Log_keys(logger,
  916. "Initialized CryptoAuth:\n myPrivateKey=%s\n myPublicKey=%s\n",
  917. privateKeyHex,
  918. publicKeyHex);
  919. #endif
  920. return &ca->pub;
  921. }
  922. int32_t CryptoAuth_addUser(String* password,
  923. uint8_t authType,
  924. String* user,
  925. struct CryptoAuth* ca)
  926. {
  927. struct CryptoAuth_pvt* context = Identity_check((struct CryptoAuth_pvt*) ca);
  928. if (authType != 1) {
  929. return CryptoAuth_addUser_INVALID_AUTHTYPE;
  930. }
  931. if (context->passwordCount == context->passwordCapacity) {
  932. // TODO(cjd): realloc password space and increase buffer.
  933. return CryptoAuth_addUser_OUT_OF_SPACE;
  934. }
  935. struct CryptoAuth_Auth a;
  936. hashPassword_sha256(&a, password);
  937. for (uint32_t i = 0; i < context->passwordCount; i++) {
  938. if (!Bits_memcmp(a.secret, context->passwords[i].secret, 32) ||
  939. String_equals(user, context->passwords[i].user)) {
  940. return CryptoAuth_addUser_DUPLICATE;
  941. }
  942. }
  943. a.user = String_new(user->bytes, context->allocator);
  944. Bits_memcpyConst(&context->passwords[context->passwordCount],
  945. &a,
  946. sizeof(struct CryptoAuth_Auth));
  947. context->passwordCount++;
  948. return 0;
  949. }
  950. int CryptoAuth_removeUsers(struct CryptoAuth* context, String* user)
  951. {
  952. struct CryptoAuth_pvt* ctx = Identity_check((struct CryptoAuth_pvt*) context);
  953. if (!user) {
  954. int count = ctx->passwordCount;
  955. Log_debug(ctx->logger, "Flushing [%d] users", count);
  956. ctx->passwordCount = 0;
  957. return count;
  958. }
  959. int count = 0;
  960. int i = 0;
  961. while (i < (int)ctx->passwordCount) {
  962. if (String_equals(ctx->passwords[i].user, user)) {
  963. Bits_memcpyConst(&ctx->passwords[i],
  964. &ctx->passwords[ctx->passwordCount--],
  965. sizeof(struct CryptoAuth_Auth));
  966. count++;
  967. } else {
  968. i++;
  969. }
  970. }
  971. Log_debug(ctx->logger, "Removing [%d] user(s) identified by [%s]", count, user->bytes);
  972. return count;
  973. }
  974. List* CryptoAuth_getUsers(struct CryptoAuth* context, struct Allocator* alloc)
  975. {
  976. struct CryptoAuth_pvt* ctx = Identity_check((struct CryptoAuth_pvt*) context);
  977. uint32_t count = ctx->passwordCount;
  978. List* users = NULL;
  979. for (uint32_t i = 0; i < count; i++ )
  980. {
  981. users = List_addString(users, String_clone(ctx->passwords[i].user, alloc), alloc);
  982. }
  983. return users;
  984. }
  985. String* CryptoAuth_getUser(struct Interface* interface)
  986. {
  987. struct CryptoAuth_Wrapper* wrapper =
  988. Identity_check((struct CryptoAuth_Wrapper*)interface->senderContext);
  989. String* user = wrapper->user;
  990. if (user) {
  991. // If the user was lost in flushusers, then we need to return null.
  992. for (uint32_t i = 0; i < wrapper->context->passwordCount; i++) {
  993. if (user == wrapper->context->passwords[i].user) {
  994. return user;
  995. }
  996. }
  997. // Null it since it's been removed.
  998. wrapper->user = NULL;
  999. }
  1000. return NULL;
  1001. }
  1002. struct Interface* CryptoAuth_wrapInterface(struct Interface* toWrap,
  1003. const uint8_t herPublicKey[32],
  1004. const uint8_t herIp6[16],
  1005. const bool requireAuth,
  1006. char* name,
  1007. struct CryptoAuth* ca)
  1008. {
  1009. struct CryptoAuth_pvt* context = Identity_check((struct CryptoAuth_pvt*) ca);
  1010. struct CryptoAuth_Wrapper* wrapper = Allocator_clone(toWrap->allocator,
  1011. (&(struct CryptoAuth_Wrapper) {
  1012. .user = NULL,
  1013. .nextNonce = 0,
  1014. .context = context,
  1015. .wrappedInterface = toWrap,
  1016. .requireAuth = requireAuth,
  1017. .name = name
  1018. }));
  1019. wrapper->timeOfLastPacket = Time_currentTimeSeconds(context->eventBase);
  1020. Identity_set(wrapper);
  1021. toWrap->receiverContext = wrapper;
  1022. toWrap->receiveMessage = receiveMessage;
  1023. struct Interface iface = {
  1024. .senderContext = wrapper,
  1025. .sendMessage = sendMessage,
  1026. .allocator = toWrap->allocator
  1027. };
  1028. Bits_memcpyConst(&wrapper->externalInterface, &iface, sizeof(struct Interface));
  1029. if (herPublicKey != NULL) {
  1030. Bits_memcpyConst(wrapper->herPerminentPubKey, herPublicKey, 32);
  1031. uint8_t calculatedIp6[16];
  1032. AddressCalc_addressForPublicKey(calculatedIp6, herPublicKey);
  1033. Bits_memcpyConst(wrapper->herIp6, calculatedIp6, 16);
  1034. if (herIp6 != NULL) {
  1035. Assert_true(!Bits_memcmp(calculatedIp6, herIp6, 16));
  1036. }
  1037. } else if (herIp6) {
  1038. Bits_memcpyConst(wrapper->herIp6, herIp6, 16);
  1039. }
  1040. return &wrapper->externalInterface;
  1041. }
  1042. void CryptoAuth_setAuth(const String* password,
  1043. const uint8_t authType,
  1044. struct Interface* wrappedInterface)
  1045. {
  1046. struct CryptoAuth_Wrapper* wrapper =
  1047. Identity_check((struct CryptoAuth_Wrapper*)wrappedInterface->senderContext);
  1048. wrapper->password = (password != NULL)
  1049. ? String_newBinary(password->bytes, password->len, wrappedInterface->allocator)
  1050. : NULL;
  1051. wrapper->authType = (password != NULL) ? authType : 0;
  1052. }
  1053. uint8_t* CryptoAuth_getHerPublicKey(struct Interface* interface)
  1054. {
  1055. return ((struct CryptoAuth_Wrapper*) interface->senderContext)->herPerminentPubKey;
  1056. }
  1057. void CryptoAuth_reset(struct Interface* interface)
  1058. {
  1059. struct CryptoAuth_Wrapper* wrapper =
  1060. Identity_check((struct CryptoAuth_Wrapper*)interface->senderContext);
  1061. reset(wrapper);
  1062. }
  1063. int CryptoAuth_getState(struct Interface* interface)
  1064. {
  1065. struct CryptoAuth_Wrapper* wrapper =
  1066. Identity_check((struct CryptoAuth_Wrapper*)interface->senderContext);
  1067. switch (wrapper->nextNonce) {
  1068. case 0:
  1069. return CryptoAuth_NEW;
  1070. case 1: // Sent a hello, waiting for the key
  1071. return CryptoAuth_HANDSHAKE1;
  1072. case 2: // Received a hello, sent a key packet.
  1073. case 3: // Received a hello, sent multiple key packets.
  1074. return CryptoAuth_HANDSHAKE2;
  1075. case 4:
  1076. // state 4 = waiting for first data packet to prove the handshake succeeded.
  1077. // At this point you have sent a challenge and received a response so it is safe
  1078. // to assume you are not being hit with replay packets.
  1079. //
  1080. // Sent a hello, received one or more keys, waiting for data.
  1081. // In this state data packets will be sent but no data packets have yet been received.
  1082. return CryptoAuth_HANDSHAKE3;
  1083. default:
  1084. // Received data.
  1085. return (wrapper->established) ? CryptoAuth_ESTABLISHED : CryptoAuth_HANDSHAKE3;
  1086. }
  1087. }
  1088. void CryptoAuth_resetIfTimeout(struct Interface* iface)
  1089. {
  1090. struct CryptoAuth_Wrapper* wrapper =
  1091. Identity_check((struct CryptoAuth_Wrapper*)iface->senderContext);
  1092. if (wrapper->nextNonce == 1) {
  1093. // Lets not reset the session, we just sent one or more hello packets and
  1094. // have not received a response, if they respond after we reset then we'll
  1095. // be in a tough state.
  1096. return;
  1097. }
  1098. uint64_t nowSecs = Time_currentTimeSeconds(wrapper->context->eventBase);
  1099. if (nowSecs - wrapper->timeOfLastPacket > wrapper->context->pub.resetAfterInactivitySeconds) {
  1100. cryptoAuthDebug(wrapper, "No traffic in [%d] seconds, resetting connection.",
  1101. (int) (nowSecs - wrapper->timeOfLastPacket));
  1102. wrapper->timeOfLastPacket = nowSecs;
  1103. reset(wrapper);
  1104. }
  1105. }
  1106. struct Interface* CryptoAuth_getConnectedInterface(struct Interface* iface)
  1107. {
  1108. if (iface->sendMessage == sendMessage) {
  1109. // internal (plaintext side)
  1110. struct CryptoAuth_Wrapper* wrapper =
  1111. Identity_check((struct CryptoAuth_Wrapper*)iface->senderContext);
  1112. return wrapper->wrappedInterface;
  1113. } else if (iface->receiveMessage == receiveMessage) {
  1114. struct CryptoAuth_Wrapper* wrapper =
  1115. Identity_check((struct CryptoAuth_Wrapper*)iface->receiverContext);
  1116. return &wrapper->externalInterface;
  1117. }
  1118. return NULL;
  1119. }
  1120. struct ReplayProtector* CryptoAuth_getReplayProtector(struct Interface* iface)
  1121. {
  1122. struct CryptoAuth_Wrapper* wrapper =
  1123. Identity_check((struct CryptoAuth_Wrapper*)iface->senderContext);
  1124. return &wrapper->replayProtector;
  1125. }
  1126. // For testing:
  1127. void CryptoAuth_encryptRndNonce(uint8_t nonce[24], struct Message* msg, uint8_t secret[32])
  1128. {
  1129. encryptRndNonce(nonce, msg, secret);
  1130. }
  1131. int CryptoAuth_decryptRndNonce(uint8_t nonce[24], struct Message* msg, uint8_t secret[32])
  1132. {
  1133. return decryptRndNonce(nonce, msg, secret);
  1134. }
  1135. uint8_t CryptoAuth_encryptHandshake(struct Message* message,
  1136. struct CryptoAuth_Wrapper* wrapper,
  1137. int setupMessage)
  1138. {
  1139. return encryptHandshake(message, wrapper, setupMessage);
  1140. }
  1141. uint8_t CryptoAuth_receiveMessage(struct Message* received, struct Interface* interface)
  1142. {
  1143. return receiveMessage(received, interface);
  1144. }