1
0

CryptoAuth.c 50 KB

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