CryptoAuth.c 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106
  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/Object.h"
  21. #include "util/log/Log.h"
  22. #include "memory/Allocator.h"
  23. #include "util/Assert.h"
  24. #include "util/AddrTools.h"
  25. #include "util/Bits.h"
  26. #include "util/Endian.h"
  27. #include "util/Hex.h"
  28. #include "util/events/Time.h"
  29. #include "wire/Error.h"
  30. #include "wire/Headers.h"
  31. #include "wire/Message.h"
  32. #include "crypto_box_curve25519xsalsa20poly1305.h"
  33. #include "crypto_core_hsalsa20.h"
  34. #include "crypto_hash_sha256.h"
  35. #include "crypto_scalarmult_curve25519.h"
  36. #include "crypto_stream_salsa20.h"
  37. #include "crypto_stream_xsalsa20.h"
  38. #include <stdint.h>
  39. #include <stdbool.h>
  40. #ifdef WIN32
  41. #undef interface
  42. #endif
  43. /** The constant used in nacl. */
  44. static const uint8_t keyHashSigma[16] = "expand 32-byte k";
  45. static const uint8_t keyHashNonce[16] = {0};
  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. /**
  65. * Get a shared secret.
  66. *
  67. * @param outputSecret an array to place the shared secret in.
  68. * @param myPrivateKey
  69. * @param herPublicKey
  70. * @param logger
  71. * @param passwordHash a 32 byte value known to both ends, this must be provably pseudorandom
  72. * the first 32 bytes of a sha256 output from hashing a password is ok,
  73. * whatever she happens to send me in the Auth field is NOT ok.
  74. * If this field is null, the secret will be generated without the password.
  75. */
  76. static inline void getSharedSecret(uint8_t outputSecret[32],
  77. uint8_t myPrivateKey[32],
  78. uint8_t herPublicKey[32],
  79. uint8_t passwordHash[32],
  80. struct Log* logger)
  81. {
  82. if (passwordHash == NULL) {
  83. crypto_box_curve25519xsalsa20poly1305_beforenm(outputSecret, herPublicKey, myPrivateKey);
  84. } else {
  85. union {
  86. struct {
  87. uint8_t key[32];
  88. uint8_t passwd[32];
  89. } components;
  90. uint8_t bytes[64];
  91. } buff;
  92. crypto_scalarmult_curve25519(buff.components.key, myPrivateKey, herPublicKey);
  93. Bits_memcpyConst(buff.components.passwd, passwordHash, 32);
  94. crypto_hash_sha256(outputSecret, buff.bytes, 64);
  95. }
  96. #ifdef Log_KEYS
  97. uint8_t myPublicKeyHex[65];
  98. printHexPubKey(myPublicKeyHex, myPrivateKey);
  99. uint8_t herPublicKeyHex[65];
  100. printHexKey(herPublicKeyHex, herPublicKey);
  101. uint8_t passwordHashHex[65];
  102. printHexKey(passwordHashHex, passwordHash);
  103. uint8_t outputSecretHex[65] = "NULL";
  104. printHexKey(outputSecretHex, outputSecret);
  105. Log_keys(logger,
  106. "Generated a shared secret:\n"
  107. " myPublicKey=%s\n"
  108. " herPublicKey=%s\n"
  109. " passwordHash=%s\n"
  110. " outputSecret=%s\n",
  111. myPublicKeyHex, herPublicKeyHex, passwordHashHex, outputSecretHex);
  112. #endif
  113. }
  114. static inline void hashPassword_sha256(struct CryptoAuth_Auth* auth, const String* password)
  115. {
  116. uint8_t tempBuff[32];
  117. crypto_hash_sha256(auth->secret, (uint8_t*) password->bytes, password->len);
  118. crypto_hash_sha256(tempBuff, auth->secret, 32);
  119. Bits_memcpyConst(auth->challenge.bytes, tempBuff, Headers_AuthChallenge_SIZE);
  120. Headers_setAuthChallengeDerivations(&auth->challenge, 0);
  121. auth->challenge.challenge.type = 1;
  122. }
  123. static inline uint8_t* hashPassword(struct CryptoAuth_Auth* auth,
  124. const String* password,
  125. const uint8_t authType)
  126. {
  127. switch (authType) {
  128. case 1:
  129. hashPassword_sha256(auth, password);
  130. break;
  131. default:
  132. // Unsupported auth type.
  133. abort();
  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. void** 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. wrapper->authenticatePackets |= Headers_isPacketAuthRequired(&cauth->handshake.auth);
  189. return NULL;
  190. }
  191. /**
  192. * Decrypt and authenticate.
  193. *
  194. * @param nonce a 24 byte number, may be random, cannot repeat.
  195. * @param msg a message to encipher and authenticate.
  196. * @param secret a shared secret.
  197. * @return 0 if decryption is succeddful, otherwise -1.
  198. */
  199. static inline int decryptRndNonce(uint8_t nonce[24],
  200. struct Message* msg,
  201. uint8_t secret[32])
  202. {
  203. if (msg->length < 16) {
  204. return -1;
  205. }
  206. Assert_true(msg->padding >= 16);
  207. uint8_t* startAt = msg->bytes - 16;
  208. uint8_t paddingSpace[16];
  209. Bits_memcpyConst(paddingSpace, startAt, 16);
  210. Bits_memset(startAt, 0, 16);
  211. if (crypto_box_curve25519xsalsa20poly1305_open_afternm(
  212. startAt, startAt, msg->length + 16, nonce, secret) != 0)
  213. {
  214. return -1;
  215. }
  216. Bits_memcpyConst(startAt, paddingSpace, 16);
  217. Message_shift(msg, -16);
  218. return 0;
  219. }
  220. /**
  221. * Encrypt and authenticate.
  222. * Shifts the message by 16 bytes.
  223. *
  224. * @param nonce a 24 byte number, may be random, cannot repeat.
  225. * @param msg a message to encipher and authenticate.
  226. * @param secret a shared secret.
  227. */
  228. static inline void encryptRndNonce(uint8_t nonce[24],
  229. struct Message* msg,
  230. uint8_t secret[32])
  231. {
  232. Assert_true(msg->padding >= 32);
  233. uint8_t* startAt = msg->bytes - 32;
  234. // This function trashes 16 bytes of the padding so we will put it back
  235. uint8_t paddingSpace[16];
  236. Bits_memcpyConst(paddingSpace, startAt, 16);
  237. Bits_memset(startAt, 0, 32);
  238. crypto_box_curve25519xsalsa20poly1305_afternm(
  239. startAt, startAt, msg->length + 32, nonce, secret);
  240. Bits_memcpyConst(startAt, paddingSpace, 16);
  241. Message_shift(msg, 16);
  242. }
  243. /**
  244. * Encipher the content without any authentication.
  245. * Encryption is the same function as decryption.
  246. *
  247. * @param nonce a number which is used only once.
  248. * @param msg a message to encipher.
  249. * @param secret a shared secret.
  250. */
  251. static inline int cipher(uint8_t nonce[8],
  252. struct Message* msg,
  253. uint8_t secret[20])
  254. {
  255. return crypto_stream_salsa20_xor(msg->bytes, msg->bytes, msg->length, nonce, secret);
  256. }
  257. /**
  258. * Decrypt a packet.
  259. *
  260. * @param nonce a counter.
  261. * @param msg the message to decrypt, decrypted in place.
  262. * @param secret the shared secret.
  263. * @param isInitiator true if we started the connection.
  264. * @param authenticate if true then the packet will be authenticated as well at a 16 byte cost.
  265. * The packet must have been encrypted using authenticate.
  266. */
  267. static inline int decrypt(uint32_t nonce,
  268. struct Message* msg,
  269. uint8_t secret[32],
  270. bool isInitiator,
  271. bool authenticate)
  272. {
  273. union {
  274. uint32_t ints[2];
  275. uint8_t bytes[24];
  276. } nonceAs = { .ints = {0, 0} };
  277. nonceAs.ints[!isInitiator] = Endian_hostToLittleEndian32(nonce);
  278. if (authenticate) {
  279. return decryptRndNonce(nonceAs.bytes, msg, secret);
  280. } else {
  281. return cipher(nonceAs.bytes, msg, secret);
  282. }
  283. }
  284. /**
  285. * Encrypt a packet.
  286. *
  287. * @param nonce a counter.
  288. * @param msg the message to decrypt, decrypted in place.
  289. * @param secret the shared secret.
  290. * @param isInitiator true if we started the connection.
  291. * @param authenticate if true then the packet will be authenticated as well at a 16 byte cost.
  292. * The packet must have been encrypted using authenticate.
  293. */
  294. static inline void encrypt(uint32_t nonce,
  295. struct Message* msg,
  296. uint8_t secret[32],
  297. bool isInitiator,
  298. bool authenticate)
  299. {
  300. union {
  301. uint32_t ints[2];
  302. uint8_t bytes[24];
  303. } nonceAs = { .ints = {0, 0} };
  304. nonceAs.ints[isInitiator] = Endian_hostToLittleEndian32(nonce);
  305. if (authenticate) {
  306. encryptRndNonce(nonceAs.bytes, msg, secret);
  307. } else {
  308. cipher(nonceAs.bytes, msg, secret);
  309. }
  310. }
  311. static inline void setRequiredPadding(struct CryptoAuth_Wrapper* wrapper)
  312. {
  313. uint32_t padding = (wrapper->nextNonce < 4) ? 36 : sizeof(union Headers_CryptoAuth) + 32;
  314. wrapper->externalInterface.requiredPadding =
  315. wrapper->wrappedInterface->requiredPadding + padding;
  316. wrapper->externalInterface.maxMessageLength =
  317. wrapper->wrappedInterface->maxMessageLength - padding;
  318. }
  319. static inline bool knowHerKey(struct CryptoAuth_Wrapper* wrapper)
  320. {
  321. return !Bits_isZero(wrapper->herPerminentPubKey, 32);
  322. }
  323. static void getIp6(struct CryptoAuth_Wrapper* wrapper, uint8_t* addr)
  324. {
  325. if (knowHerKey(wrapper)) {
  326. uint8_t ip6[16];
  327. AddressCalc_addressForPublicKey(ip6, wrapper->herPerminentPubKey);
  328. AddrTools_printIp(addr, ip6);
  329. }
  330. }
  331. #define cryptoAuthDebug(wrapper, format, ...) \
  332. { \
  333. uint8_t addr[40] = "unknown"; \
  334. getIp6(wrapper, addr); \
  335. Log_debug(wrapper->context->logger, \
  336. "%p [%s]: " format, (void*)wrapper, addr, __VA_ARGS__); \
  337. }
  338. #define cryptoAuthDebug0(wrapper, format) \
  339. cryptoAuthDebug(wrapper, format "%s", "")
  340. /**
  341. * If we don't know her key, the handshake has to be done backwards.
  342. * Reverse handshake requests are signaled by sending a non-obfuscated zero nonce.
  343. */
  344. static uint8_t genReverseHandshake(struct Message* message,
  345. struct CryptoAuth_Wrapper* wrapper,
  346. union Headers_CryptoAuth* header)
  347. {
  348. wrapper->nextNonce = 0;
  349. Message_shift(message, -Headers_CryptoAuth_SIZE);
  350. // Buffer the packet so it can be sent ASAP
  351. if (wrapper->bufferedMessage == NULL) {
  352. cryptoAuthDebug0(wrapper, "Buffered a message");
  353. wrapper->bufferedMessage =
  354. Message_clone(message, wrapper->externalInterface.allocator);
  355. Assert_true(wrapper->nextNonce == 0);
  356. } else {
  357. cryptoAuthDebug0(wrapper, "Expelled a message because a session has not yet been setup");
  358. Message_copyOver(wrapper->bufferedMessage,
  359. message,
  360. wrapper->externalInterface.allocator);
  361. Assert_true(wrapper->nextNonce == 0);
  362. }
  363. wrapper->hasBufferedMessage = true;
  364. Message_shift(message, Headers_CryptoAuth_SIZE);
  365. header = (union Headers_CryptoAuth*) message->bytes;
  366. header->nonce = UINT32_MAX;
  367. message->length = Headers_CryptoAuth_SIZE;
  368. // sessionState must be 0, auth and 24 byte nonce are garbaged and public key is set
  369. // now garbage the authenticator and the encrypted key which are not used.
  370. Random_bytes(wrapper->context->rand, (uint8_t*) &header->handshake.authenticator, 48);
  371. return wrapper->wrappedInterface->sendMessage(message, wrapper->wrappedInterface);
  372. }
  373. static uint8_t encryptHandshake(struct Message* message, struct CryptoAuth_Wrapper* wrapper)
  374. {
  375. Message_shift(message, sizeof(union Headers_CryptoAuth));
  376. union Headers_CryptoAuth* header = (union Headers_CryptoAuth*) message->bytes;
  377. // garbage the auth field to frustrate DPI and set the nonce (next 24 bytes after the auth)
  378. Random_bytes(wrapper->context->rand,
  379. (uint8_t*) &header->handshake.auth,
  380. sizeof(union Headers_AuthChallenge) + 24);
  381. Bits_memcpyConst(&header->handshake.publicKey, wrapper->context->pub.publicKey, 32);
  382. if (!knowHerKey(wrapper)) {
  383. return genReverseHandshake(message, wrapper, header);
  384. }
  385. // Password auth
  386. uint8_t* passwordHash = NULL;
  387. struct CryptoAuth_Auth auth;
  388. if (wrapper->password != NULL) {
  389. passwordHash = hashPassword(&auth, wrapper->password, wrapper->authType);
  390. Bits_memcpyConst(header->handshake.auth.bytes,
  391. &auth.challenge,
  392. sizeof(union Headers_AuthChallenge));
  393. }
  394. header->handshake.auth.challenge.type = wrapper->authType;
  395. Headers_setPacketAuthRequired(&header->handshake.auth, wrapper->authenticatePackets);
  396. // set the session state
  397. uint32_t sessionState_be = Endian_hostToBigEndian32(wrapper->nextNonce);
  398. header->nonce = sessionState_be;
  399. if (wrapper->nextNonce == 0 || wrapper->nextNonce == 2) {
  400. // If we're sending a hello or a key
  401. Random_bytes(wrapper->context->rand, wrapper->secret, 32);
  402. crypto_scalarmult_curve25519_base(header->handshake.encryptedTempKey, wrapper->secret);
  403. #ifdef Log_KEYS
  404. uint8_t tempPrivateKeyHex[65];
  405. Hex_encode(tempPrivateKeyHex, 65, wrapper->secret, 32);
  406. uint8_t tempPubKeyHex[65];
  407. Hex_encode(tempPubKeyHex, 65, header->handshake.encryptedTempKey, 32);
  408. Log_keys(wrapper->context->logger, "Generating temporary keypair\n"
  409. " myTempPrivateKey=%s\n"
  410. " myTempPublicKey=%s\n",
  411. tempPrivateKeyHex, tempPubKeyHex);
  412. #endif
  413. if (wrapper->nextNonce == 0) {
  414. Bits_memcpyConst(wrapper->tempKey, header->handshake.encryptedTempKey, 32);
  415. }
  416. #ifdef Log_DEBUG
  417. Assert_true(!Bits_isZero(header->handshake.encryptedTempKey, 32));
  418. Assert_true(!Bits_isZero(wrapper->secret, 32));
  419. #endif
  420. } else if (wrapper->nextNonce == 3) {
  421. // Dupe key
  422. // If nextNonce is 1 then we have our pubkey stored in wrapper->tempKey,
  423. // If nextNonce is 3 we need to recalculate it each time
  424. // because tempKey the final secret.
  425. crypto_scalarmult_curve25519_base(header->handshake.encryptedTempKey,
  426. wrapper->secret);
  427. } else {
  428. // Dupe hello
  429. // wrapper->nextNonce == 1
  430. // Our public key is cached in wrapper->tempKey so lets copy it out.
  431. Bits_memcpyConst(header->handshake.encryptedTempKey, wrapper->tempKey, 32);
  432. }
  433. #ifdef Log_KEYS
  434. uint8_t tempKeyHex[65];
  435. Hex_encode(tempKeyHex, 65, header->handshake.encryptedTempKey, 32);
  436. Log_keys(wrapper->context->logger,
  437. "Wrapping temp public key:\n"
  438. " %s\n",
  439. tempKeyHex);
  440. #endif
  441. uint8_t sharedSecret[32];
  442. if (wrapper->nextNonce < 2) {
  443. if (wrapper->nextNonce == 0) {
  444. cryptoAuthDebug0(wrapper, "Sending hello packet");
  445. } else {
  446. cryptoAuthDebug0(wrapper, "Sending repeat hello packet");
  447. }
  448. getSharedSecret(sharedSecret,
  449. wrapper->context->privateKey,
  450. wrapper->herPerminentPubKey,
  451. passwordHash,
  452. wrapper->context->logger);
  453. wrapper->isInitiator = true;
  454. wrapper->nextNonce = 1;
  455. } else {
  456. if (wrapper->nextNonce == 2) {
  457. cryptoAuthDebug0(wrapper, "Sending key packet");
  458. } else {
  459. cryptoAuthDebug0(wrapper, "Sending repeat key packet");
  460. }
  461. // Handshake2 wrapper->tempKey holds her public temp key.
  462. // it was put there by receiveMessage()
  463. getSharedSecret(sharedSecret,
  464. wrapper->context->privateKey,
  465. wrapper->tempKey,
  466. passwordHash,
  467. wrapper->context->logger);
  468. wrapper->nextNonce = 3;
  469. #ifdef Log_KEYS
  470. uint8_t tempKeyHex[65];
  471. Hex_encode(tempKeyHex, 65, wrapper->tempKey, 32);
  472. Log_keys(wrapper->context->logger,
  473. "Using their temp public key:\n"
  474. " %s\n",
  475. tempKeyHex);
  476. #endif
  477. }
  478. // Shift message over the encryptedTempKey field.
  479. Message_shift(message, 32 - Headers_CryptoAuth_SIZE);
  480. encryptRndNonce(header->handshake.nonce, message, sharedSecret);
  481. #ifdef Log_KEYS
  482. uint8_t sharedSecretHex[65];
  483. printHexKey(sharedSecretHex, sharedSecret);
  484. uint8_t nonceHex[49];
  485. Hex_encode(nonceHex, 49, header->handshake.nonce, 24);
  486. uint8_t cipherHex[65];
  487. printHexKey(cipherHex, message->bytes);
  488. Log_keys(wrapper->context->logger,
  489. "Encrypting message with:\n"
  490. " nonce: %s\n"
  491. " secret: %s\n"
  492. " cipher: %s\n",
  493. nonceHex, sharedSecretHex, cipherHex);
  494. #endif
  495. #ifdef Log_DEBUG
  496. Assert_true(!Bits_isZero(header->handshake.encryptedTempKey, 32));
  497. #endif
  498. // Shift it back -- encryptRndNonce adds 16 bytes of authenticator.
  499. Message_shift(message, Headers_CryptoAuth_SIZE - 32 - 16);
  500. return wrapper->wrappedInterface->sendMessage(message, wrapper->wrappedInterface);
  501. }
  502. static inline uint8_t encryptMessage(struct Message* message,
  503. struct CryptoAuth_Wrapper* wrapper)
  504. {
  505. Assert_true(message->padding >= 36 || !"not enough padding");
  506. encrypt(wrapper->nextNonce,
  507. message,
  508. wrapper->secret,
  509. wrapper->isInitiator,
  510. wrapper->authenticatePackets);
  511. Message_shift(message, 4);
  512. union Headers_CryptoAuth* header = (union Headers_CryptoAuth*) message->bytes;
  513. header->nonce = Endian_hostToBigEndian32(wrapper->nextNonce);
  514. wrapper->nextNonce++;
  515. return wrapper->wrappedInterface->sendMessage(message, wrapper->wrappedInterface);
  516. }
  517. static uint8_t sendMessage(struct Message* message, struct Interface* interface)
  518. {
  519. struct CryptoAuth_Wrapper* wrapper =
  520. Identity_cast((struct CryptoAuth_Wrapper*) interface->senderContext);
  521. // If there has been no incoming traffic for a while, reset the connection to state 0.
  522. // This will prevent "connection in bad state" situations from lasting forever.
  523. // this will reset the session if it has timed out.
  524. CryptoAuth_getState(interface);
  525. #ifdef Log_DEBUG
  526. Assert_true(!((uintptr_t)message->bytes % 4) || !"alignment fault");
  527. #endif
  528. // nextNonce 0: sending hello, we are initiating connection.
  529. // nextNonce 1: sending another hello, nothing received yet.
  530. // nextNonce 2: sending key, hello received.
  531. // nextNonce 3: sending key again, no data packet recieved yet.
  532. // nextNonce >3: handshake complete
  533. //
  534. // if it's a blind handshake, every message will be empty and nextNonce will remain
  535. // zero until the first message is received back.
  536. if (wrapper->nextNonce < 5) {
  537. if (wrapper->nextNonce < 4) {
  538. return encryptHandshake(message, wrapper);
  539. } else {
  540. cryptoAuthDebug0(wrapper, "Doing final step to send message. nonce=4");
  541. uint8_t secret[32];
  542. getSharedSecret(secret,
  543. wrapper->secret,
  544. wrapper->tempKey,
  545. NULL,
  546. wrapper->context->logger);
  547. Bits_memcpyConst(wrapper->secret, secret, 32);
  548. }
  549. }
  550. return encryptMessage(message, wrapper);
  551. }
  552. /** Call the external interface and tell it that a message has been received. */
  553. static inline uint8_t callReceivedMessage(struct CryptoAuth_Wrapper* wrapper,
  554. struct Message* message)
  555. {
  556. if (wrapper->authenticatePackets) {
  557. wrapper->timeOfLastPacket = Time_currentTimeSeconds(wrapper->context->eventBase);
  558. }
  559. uint8_t ret = 0;
  560. if (wrapper->externalInterface.receiveMessage != NULL) {
  561. ret = wrapper->externalInterface.receiveMessage(message, &wrapper->externalInterface);
  562. }
  563. return ret;
  564. }
  565. static inline bool decryptMessage(struct CryptoAuth_Wrapper* wrapper,
  566. uint32_t nonce,
  567. struct Message* content,
  568. uint8_t secret[32])
  569. {
  570. if (wrapper->authenticatePackets) {
  571. // Decrypt with authentication and replay prevention.
  572. int ret = decrypt(nonce, content, secret, wrapper->isInitiator, true);
  573. if (ret) {
  574. cryptoAuthDebug(wrapper, "Authenticated decryption failed returning %u", ret);
  575. return false;
  576. }
  577. ret = !ReplayProtector_checkNonce(nonce, &wrapper->replayProtector);
  578. if (ret) {
  579. cryptoAuthDebug0(wrapper, "Nonce checking failed");
  580. return false;
  581. }
  582. } else {
  583. decrypt(nonce, content, secret, wrapper->isInitiator, false);
  584. }
  585. return true;
  586. }
  587. static uint8_t decryptHandshake(struct CryptoAuth_Wrapper* wrapper,
  588. const uint32_t nonce,
  589. struct Message* message,
  590. union Headers_CryptoAuth* header)
  591. {
  592. if (message->length < Headers_CryptoAuth_SIZE) {
  593. cryptoAuthDebug0(wrapper, "Dropped runt packet");
  594. return Error_UNDERSIZE_MESSAGE;
  595. }
  596. // handshake
  597. // nextNonce 0: recieving hello.
  598. // nextNonce 1: recieving key, we sent hello.
  599. // nextNonce 2: recieving first data packet or duplicate hello.
  600. // nextNonce 3: recieving first data packet.
  601. // nextNonce >3: handshake complete
  602. if (wrapper->nextNonce < 2 && nonce == UINT32_MAX && !wrapper->requireAuth) {
  603. // Reset without knowing key is allowed until state reaches 2.
  604. // this is because we don't know that the other end knows our key until we
  605. // have received a valid packet from them.
  606. // We can't allow the upper layer to see this message because it's not authenticated.
  607. if (!knowHerKey(wrapper)) {
  608. Bits_memcpyConst(wrapper->herPerminentPubKey, header->handshake.publicKey, 32);
  609. }
  610. Message_shift(message, -Headers_CryptoAuth_SIZE);
  611. message->length = 0;
  612. wrapper->nextNonce = 0;
  613. wrapper->user = NULL;
  614. cryptoAuthDebug0(wrapper, "Got a connect-to-me message, sending a hello");
  615. // Send an empty response (to initiate the connection).
  616. encryptHandshake(message, wrapper);
  617. return Error_NONE;
  618. }
  619. void* user = NULL;
  620. uint8_t passwordHashStore[32];
  621. uint8_t* passwordHash = tryAuth(header, passwordHashStore, wrapper, &user);
  622. if (wrapper->requireAuth && !user) {
  623. cryptoAuthDebug0(wrapper, "Dropping message because auth was not given");
  624. return Error_AUTHENTICATION;
  625. }
  626. if (passwordHash == NULL && header->handshake.auth.challenge.type != 0) {
  627. cryptoAuthDebug0(wrapper,
  628. "Dropping message because it contans an authenticator which is unrecognized");
  629. return Error_AUTHENTICATION;
  630. }
  631. // What the nextNonce will become if this packet is valid.
  632. uint32_t nextNonce;
  633. // The secret for decrypting this message.
  634. uint8_t sharedSecret[32];
  635. uint8_t* herPermKey = NULL;
  636. if (nonce < 2) {
  637. if (nonce == 0) {
  638. cryptoAuthDebug(wrapper, "Received a hello packet, using auth: %d",
  639. (passwordHash != NULL));
  640. } else {
  641. cryptoAuthDebug0(wrapper, "Received a repeat hello packet");
  642. }
  643. // Decrypt message with perminent keys.
  644. if (!knowHerKey(wrapper) || wrapper->nextNonce == 0) {
  645. herPermKey = header->handshake.publicKey;
  646. #ifdef Log_DEBUG
  647. if (Bits_isZero(header->handshake.publicKey, 32)) {
  648. cryptoAuthDebug0(wrapper, "Node sent public key of ZERO!");
  649. }
  650. #endif
  651. } else {
  652. herPermKey = wrapper->herPerminentPubKey;
  653. if (Bits_memcmp(header->handshake.publicKey, herPermKey, 32)) {
  654. cryptoAuthDebug0(wrapper, "Packet contains different perminent key");
  655. return Error_AUTHENTICATION;
  656. }
  657. }
  658. getSharedSecret(sharedSecret,
  659. wrapper->context->privateKey,
  660. herPermKey,
  661. passwordHash,
  662. wrapper->context->logger);
  663. nextNonce = 2;
  664. } else {
  665. if (nonce == 2) {
  666. cryptoAuthDebug0(wrapper, "Received a key packet");
  667. } else if (nonce == 3) {
  668. cryptoAuthDebug0(wrapper, "Received a repeat key packet");
  669. } else {
  670. cryptoAuthDebug(wrapper, "Received a packet of unknown type! nonce=%u", nonce);
  671. }
  672. if (Bits_memcmp(header->handshake.publicKey, wrapper->herPerminentPubKey, 32)) {
  673. cryptoAuthDebug0(wrapper, "Packet contains different perminent key");
  674. return Error_AUTHENTICATION;
  675. }
  676. // We sent the hello, this is a key
  677. getSharedSecret(sharedSecret,
  678. wrapper->secret,
  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);
  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. cryptoAuthDebug0(wrapper, "Dropped message because authenticated decryption failed");
  705. return Error_AUTHENTICATION;
  706. }
  707. wrapper->user = user;
  708. Bits_memcpyConst(wrapper->tempKey, header->handshake.encryptedTempKey, 32);
  709. #ifdef Log_DEBUG
  710. Assert_true(!Bits_isZero(header->handshake.encryptedTempKey, 32));
  711. #endif
  712. #ifdef Log_KEYS
  713. uint8_t tempKeyHex[65];
  714. Hex_encode(tempKeyHex, 65, wrapper->tempKey, 32);
  715. Log_keys(wrapper->context->logger,
  716. "Unwrapping temp public key:\n"
  717. " %s\n",
  718. tempKeyHex);
  719. #endif
  720. Message_shift(message, -32);
  721. wrapper->nextNonce = nextNonce;
  722. if (nextNonce == 2) {
  723. wrapper->isInitiator = false;
  724. }
  725. if (herPermKey && herPermKey != wrapper->herPerminentPubKey) {
  726. Bits_memcpyConst(wrapper->herPerminentPubKey, herPermKey, 32);
  727. }
  728. // If this is a handshake which was initiated in reverse because we
  729. // didn't know the other node's key, now send what we were going to send.
  730. if (wrapper->hasBufferedMessage && message->length == 0) {
  731. cryptoAuthDebug0(wrapper, "Sending buffered message");
  732. sendMessage(wrapper->bufferedMessage, &wrapper->externalInterface);
  733. wrapper->hasBufferedMessage = false;
  734. return Error_NONE;
  735. } else if (wrapper->hasBufferedMessage) {
  736. cryptoAuthDebug0(wrapper, "There is a buffered message");
  737. }
  738. Bits_memset(&wrapper->replayProtector, 0, sizeof(struct ReplayProtector));
  739. setRequiredPadding(wrapper);
  740. return callReceivedMessage(wrapper, message);
  741. }
  742. static uint8_t receiveMessage(struct Message* received, struct Interface* interface)
  743. {
  744. struct CryptoAuth_Wrapper* wrapper =
  745. Identity_cast((struct CryptoAuth_Wrapper*) interface->receiverContext);
  746. union Headers_CryptoAuth* header = (union Headers_CryptoAuth*) received->bytes;
  747. if (received->length < (wrapper->authenticatePackets ? 20 : 4)) {
  748. cryptoAuthDebug0(wrapper, "Dropped runt");
  749. return Error_UNDERSIZE_MESSAGE;
  750. }
  751. Assert_true(received->padding >= 12 || "need at least 12 bytes of padding in incoming message");
  752. #ifdef Log_DEBUG
  753. Assert_true(!((uintptr_t)received->bytes % 4) || !"alignment fault");
  754. #endif
  755. Message_shift(received, -4);
  756. uint32_t nonce = Endian_bigEndianToHost32(header->nonce);
  757. if (wrapper->nextNonce < 5) {
  758. if (nonce > 3 && nonce != UINT32_MAX && knowHerKey(wrapper)) {
  759. cryptoAuthDebug(wrapper, "Trying final handshake step, nonce=%u\n", nonce);
  760. uint8_t secret[32];
  761. getSharedSecret(secret,
  762. wrapper->secret,
  763. wrapper->tempKey,
  764. NULL,
  765. wrapper->context->logger);
  766. // We'll optimistically advance the nextNonce value because decryptMessage()
  767. // passes the message on to the upper level and if this message causes a
  768. // response, we want the CA to be in ESTABLISHED state.
  769. // if the decryptMessage() call fails, we CryptoAuth_reset() it back.
  770. wrapper->nextNonce += 3;
  771. if (decryptMessage(wrapper, nonce, received, secret)) {
  772. cryptoAuthDebug0(wrapper, "Final handshake step succeeded");
  773. Bits_memcpyConst(wrapper->secret, secret, 32);
  774. return callReceivedMessage(wrapper, received);
  775. }
  776. CryptoAuth_reset(&wrapper->externalInterface);
  777. cryptoAuthDebug0(wrapper, "Final handshake step failed");
  778. return Error_UNDELIVERABLE;
  779. }
  780. } else if (nonce > 4) {
  781. if (decryptMessage(wrapper, nonce, received, wrapper->secret)) {
  782. return callReceivedMessage(wrapper, received);
  783. } else {
  784. cryptoAuthDebug0(wrapper, "Failed to decrypt message");
  785. return Error_UNDELIVERABLE;
  786. }
  787. } else {
  788. cryptoAuthDebug0(wrapper, "Received handshake message during established connection");
  789. }
  790. Message_shift(received, 4);
  791. return decryptHandshake(wrapper, nonce, received, header);
  792. }
  793. /////////////////////////////////////////////////////////////////////////////////////////////////
  794. struct CryptoAuth* CryptoAuth_new(struct Allocator* allocator,
  795. const uint8_t* privateKey,
  796. struct EventBase* eventBase,
  797. struct Log* logger,
  798. struct Random* rand)
  799. {
  800. struct CryptoAuth_pvt* ca = Allocator_calloc(allocator, sizeof(struct CryptoAuth_pvt), 1);
  801. ca->allocator = allocator;
  802. ca->passwords = Allocator_calloc(allocator, sizeof(struct CryptoAuth_Auth), 256);
  803. ca->passwordCount = 0;
  804. ca->passwordCapacity = 256;
  805. ca->eventBase = eventBase;
  806. ca->logger = logger;
  807. ca->pub.resetAfterInactivitySeconds = CryptoAuth_DEFAULT_RESET_AFTER_INACTIVITY_SECONDS;
  808. ca->rand = rand;
  809. Identity_set(ca);
  810. if (privateKey != NULL) {
  811. Bits_memcpyConst(ca->privateKey, privateKey, 32);
  812. } else {
  813. Random_bytes(rand, ca->privateKey, 32);
  814. }
  815. crypto_scalarmult_curve25519_base(ca->pub.publicKey, ca->privateKey);
  816. #ifdef Log_KEYS
  817. uint8_t publicKeyHex[65];
  818. printHexKey(publicKeyHex, ca->pub.publicKey);
  819. uint8_t privateKeyHex[65];
  820. printHexKey(privateKeyHex, ca->privateKey);
  821. Log_keys(logger,
  822. "Initialized CryptoAuth:\n myPrivateKey=%s\n myPublicKey=%s\n",
  823. privateKeyHex,
  824. publicKeyHex);
  825. #endif
  826. return &ca->pub;
  827. }
  828. int32_t CryptoAuth_addUser(String* password,
  829. uint8_t authType,
  830. void* user,
  831. struct CryptoAuth* ca)
  832. {
  833. struct CryptoAuth_pvt* context = Identity_cast((struct CryptoAuth_pvt*) ca);
  834. if (authType != 1) {
  835. return CryptoAuth_addUser_INVALID_AUTHTYPE;
  836. }
  837. if (context->passwordCount == context->passwordCapacity) {
  838. // TODO: realloc password space and increase buffer.
  839. return CryptoAuth_addUser_OUT_OF_SPACE;
  840. }
  841. struct CryptoAuth_Auth a;
  842. hashPassword_sha256(&a, password);
  843. for (uint32_t i = 0; i < context->passwordCount; i++) {
  844. if (!Bits_memcmp(a.secret, context->passwords[i].secret, 32)) {
  845. return CryptoAuth_addUser_DUPLICATE;
  846. }
  847. }
  848. a.user = user;
  849. Bits_memcpyConst(&context->passwords[context->passwordCount],
  850. &a,
  851. sizeof(struct CryptoAuth_Auth));
  852. context->passwordCount++;
  853. return 0;
  854. }
  855. int CryptoAuth_removeUsers(struct CryptoAuth* context, void* uid)
  856. {
  857. struct CryptoAuth_pvt* ctx = Identity_cast((struct CryptoAuth_pvt*) context);
  858. if (!uid) {
  859. int count = ctx->passwordCount;
  860. Log_debug(ctx->logger, "Flushing [%d] users", count);
  861. ctx->passwordCount = 0;
  862. return count;
  863. }
  864. int count = 0;
  865. int i = 0;
  866. while (i < (int)ctx->passwordCount) {
  867. if (ctx->passwords[i].user == uid) {
  868. Bits_memcpyConst(&ctx->passwords[i],
  869. &ctx->passwords[ctx->passwordCount--],
  870. sizeof(struct CryptoAuth_Auth));
  871. count++;
  872. } else {
  873. i++;
  874. }
  875. }
  876. Log_debug(ctx->logger, "Removing [%d] user(s) identified by [%p]", count, uid);
  877. return count;
  878. }
  879. void* CryptoAuth_getUser(struct Interface* interface)
  880. {
  881. struct CryptoAuth_Wrapper* wrapper =
  882. Identity_cast((struct CryptoAuth_Wrapper*)interface->senderContext);
  883. void* user = wrapper->user;
  884. if (user) {
  885. // If the user was lost in flushusers, then we need to return null.
  886. for (uint32_t i = 0; i < wrapper->context->passwordCount; i++) {
  887. if (user == wrapper->context->passwords[i].user) {
  888. return user;
  889. }
  890. }
  891. // Null it since it's been removed.
  892. wrapper->user = NULL;
  893. }
  894. return NULL;
  895. }
  896. struct Interface* CryptoAuth_wrapInterface(struct Interface* toWrap,
  897. const uint8_t herPublicKey[32],
  898. const bool requireAuth,
  899. bool authenticatePackets,
  900. struct CryptoAuth* ca)
  901. {
  902. struct CryptoAuth_pvt* context = Identity_cast((struct CryptoAuth_pvt*) ca);
  903. struct CryptoAuth_Wrapper* wrapper = Allocator_clone(toWrap->allocator,
  904. (&(struct CryptoAuth_Wrapper) {
  905. .user = NULL,
  906. .nextNonce = 0,
  907. .context = context,
  908. .wrappedInterface = toWrap,
  909. .requireAuth = requireAuth,
  910. .authenticatePackets = authenticatePackets,
  911. .timeOfLastPacket = Time_currentTimeSeconds(context->eventBase)
  912. }));
  913. Identity_set(wrapper);
  914. toWrap->receiverContext = wrapper;
  915. toWrap->receiveMessage = receiveMessage;
  916. struct Interface iface = {
  917. .senderContext = wrapper,
  918. .sendMessage = sendMessage,
  919. .allocator = toWrap->allocator
  920. };
  921. Bits_memcpyConst(&wrapper->externalInterface, &iface, sizeof(struct Interface));
  922. if (herPublicKey != NULL) {
  923. Bits_memcpyConst(wrapper->herPerminentPubKey, herPublicKey, 32);
  924. }
  925. return &wrapper->externalInterface;
  926. }
  927. void CryptoAuth_setAuth(const String* password,
  928. const uint8_t authType,
  929. struct Interface* wrappedInterface)
  930. {
  931. struct CryptoAuth_Wrapper* wrapper =
  932. Identity_cast((struct CryptoAuth_Wrapper*)wrappedInterface->senderContext);
  933. wrapper->password = (password != NULL)
  934. ? String_newBinary(password->bytes, password->len, wrappedInterface->allocator)
  935. : NULL;
  936. wrapper->authType = (password != NULL) ? authType : 0;
  937. }
  938. uint8_t* CryptoAuth_getHerPublicKey(struct Interface* interface)
  939. {
  940. return ((struct CryptoAuth_Wrapper*) interface->senderContext)->herPerminentPubKey;
  941. }
  942. void CryptoAuth_reset(struct Interface* interface)
  943. {
  944. struct CryptoAuth_Wrapper* wrapper =
  945. Identity_cast((struct CryptoAuth_Wrapper*)interface->senderContext);
  946. wrapper->nextNonce = 0;
  947. wrapper->isInitiator = false;
  948. Bits_memset(&wrapper->replayProtector, 0, sizeof(struct ReplayProtector));
  949. }
  950. int CryptoAuth_getState(struct Interface* interface)
  951. {
  952. struct CryptoAuth_Wrapper* wrapper =
  953. Identity_cast((struct CryptoAuth_Wrapper*)interface->senderContext);
  954. uint64_t nowSecs = Time_currentTimeSeconds(wrapper->context->eventBase);
  955. if (nowSecs - wrapper->timeOfLastPacket > wrapper->context->pub.resetAfterInactivitySeconds) {
  956. cryptoAuthDebug(wrapper, "No traffic in [%d] seconds, resetting connection.",
  957. (int) (nowSecs - wrapper->timeOfLastPacket));
  958. wrapper->timeOfLastPacket = nowSecs;
  959. CryptoAuth_reset(interface);
  960. }
  961. switch (wrapper->nextNonce) {
  962. case 0:
  963. return CryptoAuth_NEW;
  964. case 1: // Sent a hello, waiting for the key
  965. return CryptoAuth_HANDSHAKE1;
  966. case 2: // Received a hello, sent a key packet.
  967. case 3: // Received a hello, sent multiple key packets.
  968. return CryptoAuth_HANDSHAKE2;
  969. case 4:
  970. // state 4 = waiting for first data packet to prove the handshake succeeded.
  971. // At this point you have sent a challenge and received a response so it is safe
  972. // to assume you are not being hit with replay packets.
  973. return CryptoAuth_HANDSHAKE3;
  974. default:
  975. return CryptoAuth_ESTABLISHED;
  976. }
  977. }
  978. struct Interface* CryptoAuth_getConnectedInterface(struct Interface* iface)
  979. {
  980. if (iface->sendMessage == sendMessage) {
  981. // internal (plaintext side)
  982. struct CryptoAuth_Wrapper* wrapper =
  983. Identity_cast((struct CryptoAuth_Wrapper*)iface->senderContext);
  984. return wrapper->wrappedInterface;
  985. } else if (iface->receiveMessage == receiveMessage) {
  986. struct CryptoAuth_Wrapper* wrapper =
  987. Identity_cast((struct CryptoAuth_Wrapper*)iface->receiverContext);
  988. return &wrapper->externalInterface;
  989. }
  990. return NULL;
  991. }