Core.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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 "admin/Admin.h"
  16. #include "admin/AdminLog.h"
  17. #include "admin/angel/Angel.h"
  18. #include "admin/angel/Core.h"
  19. #include "admin/angel/InterfaceWaiter.h"
  20. #include "admin/angel/Hermes.h"
  21. #include "admin/AuthorizedPasswords.h"
  22. #include "benc/Int.h"
  23. #include "benc/serialization/BencSerializer.h"
  24. #include "benc/serialization/standard/StandardBencSerializer.h"
  25. #include "crypto/AddressCalc.h"
  26. #include "crypto/random/Random.h"
  27. #include "crypto/random/libuv/LibuvEntropyProvider.h"
  28. #include "dht/ReplyModule.h"
  29. #include "dht/EncodingSchemeModule.h"
  30. #include "dht/SerializationModule.h"
  31. #include "dht/dhtcore/RouterModule.h"
  32. #include "dht/dhtcore/RouterModule_admin.h"
  33. #include "dht/dhtcore/RumorMill.h"
  34. #include "dht/dhtcore/SearchRunner.h"
  35. #include "dht/dhtcore/SearchRunner_admin.h"
  36. #include "dht/dhtcore/NodeStore_admin.h"
  37. #include "dht/dhtcore/Janitor.h"
  38. #include "exception/Jmp.h"
  39. #include "interface/addressable/AddrInterface.h"
  40. #include "interface/addressable/UDPAddrInterface.h"
  41. #include "interface/UDPInterface_admin.h"
  42. #ifdef HAS_ETH_INTERFACE
  43. #include "interface/ETHInterface_admin.h"
  44. #endif
  45. #include "interface/tuntap/TUNInterface.h"
  46. #include "interface/InterfaceConnector.h"
  47. #include "interface/InterfaceController_admin.h"
  48. #include "interface/FramingInterface.h"
  49. #include "interface/ICMP6Generator.h"
  50. #include "interface/RainflyClient.h"
  51. #include "interface/RainflyClient_admin.h"
  52. #include "interface/DNSServer.h"
  53. #include "interface/addressable/PacketHeaderToUDPAddrInterface.h"
  54. #include "io/ArrayReader.h"
  55. #include "io/ArrayWriter.h"
  56. #include "io/FileWriter.h"
  57. #include "io/Reader.h"
  58. #include "io/Writer.h"
  59. #include "memory/Allocator.h"
  60. #include "memory/MallocAllocator.h"
  61. #include "memory/Allocator_admin.h"
  62. #include "net/Ducttape.h"
  63. #include "net/DefaultInterfaceController.h"
  64. #include "net/SwitchPinger.h"
  65. #include "net/SwitchPinger_admin.h"
  66. #include "switch/SwitchCore.h"
  67. #include "tunnel/IpTunnel.h"
  68. #include "tunnel/IpTunnel_admin.h"
  69. #include "util/events/Timeout.h"
  70. #include "util/events/EventBase.h"
  71. #include "util/events/Pipe.h"
  72. #include "util/events/Timeout.h"
  73. #include "util/Hex.h"
  74. #include "util/log/FileWriterLog.h"
  75. #include "util/log/IndirectLog.h"
  76. #include "util/platform/netdev/NetDev.h"
  77. #include "util/Security_admin.h"
  78. #include "util/Security.h"
  79. #include "util/version/Version.h"
  80. #include "interface/SessionManager_admin.h"
  81. #include <crypto_scalarmult_curve25519.h>
  82. #include <stdlib.h>
  83. #include <unistd.h>
  84. // Failsafe: abort if more than 2^23 bytes are allocated (8MB)
  85. #define ALLOCATOR_FAILSAFE (1<<23)
  86. /** The number of nodes which we will keep track of. */
  87. #define NODE_STORE_SIZE 256
  88. /** The number of milliseconds between attempting local maintenance searches. */
  89. #define LOCAL_MAINTENANCE_SEARCH_MILLISECONDS 1000
  90. /**
  91. * The number of milliseconds to pass between global maintainence searches.
  92. * These are searches for random targets which are used to discover new nodes.
  93. */
  94. #define GLOBAL_MAINTENANCE_SEARCH_MILLISECONDS 30000
  95. #define RUMORMILL_CAPACITY 64
  96. /**
  97. * The worst possible packet overhead.
  98. * assuming the packet needs to be handed off to another node
  99. * because we have no route to the destination.
  100. * and the CryptoAuths to both the destination and the handoff node are both timed out.
  101. */
  102. #define WORST_CASE_OVERHEAD ( \
  103. /* TODO: Headers_IPv4_SIZE */ 20 \
  104. + Headers_UDPHeader_SIZE \
  105. + 4 /* Nonce */ \
  106. + 16 /* Poly1305 authenticator */ \
  107. + Headers_SwitchHeader_SIZE \
  108. + Headers_CryptoAuth_SIZE \
  109. + Headers_IP6Header_SIZE \
  110. + Headers_CryptoAuth_SIZE \
  111. )
  112. /** The default MTU, assuming the external MTU is 1492 (common for PPPoE DSL) */
  113. #define DEFAULT_MTU ( \
  114. 1492 \
  115. - WORST_CASE_OVERHEAD \
  116. + Headers_IP6Header_SIZE /* The OS subtracts the IP6 header. */ \
  117. + Headers_CryptoAuth_SIZE /* Linux won't let set the MTU below 1280.
  118. TODO: make sure we never hand off to a node for which the CA session is expired. */ \
  119. )
  120. static void parsePrivateKey(uint8_t privateKey[32],
  121. struct Address* addr,
  122. struct Except* eh)
  123. {
  124. crypto_scalarmult_curve25519_base(addr->key, privateKey);
  125. AddressCalc_addressForPublicKey(addr->ip6.bytes, addr->key);
  126. if (!AddressCalc_validAddress(addr->ip6.bytes)) {
  127. Except_throw(eh, "Ip address outside of the FC00/8 range, invalid private key.");
  128. }
  129. }
  130. static void adminPing(Dict* input, void* vadmin, String* txid, struct Allocator* requestAlloc)
  131. {
  132. Dict d = Dict_CONST(String_CONST("q"), String_OBJ(String_CONST("pong")), NULL);
  133. Admin_sendMessage(&d, txid, (struct Admin*) vadmin);
  134. }
  135. struct Context
  136. {
  137. struct Allocator* allocator;
  138. struct Admin* admin;
  139. struct Log* logger;
  140. struct Hermes* hermes;
  141. struct EventBase* base;
  142. String* exitTxid;
  143. };
  144. static void shutdown(void* vcontext)
  145. {
  146. struct Context* context = vcontext;
  147. Allocator_free(context->allocator);
  148. }
  149. static void onAngelExitResponse(Dict* message, void* vcontext)
  150. {
  151. struct Context* context = vcontext;
  152. Log_info(context->logger, "Angel stopped");
  153. Log_info(context->logger, "Exiting");
  154. Dict d = Dict_CONST(String_CONST("error"), String_OBJ(String_CONST("none")), NULL);
  155. Admin_sendMessage(&d, context->exitTxid, context->admin);
  156. Timeout_setTimeout(shutdown, context, 1, context->base, context->allocator);
  157. }
  158. static void adminExit(Dict* input, void* vcontext, String* txid, struct Allocator* requestAlloc)
  159. {
  160. struct Context* context = vcontext;
  161. Log_info(context->logger, "Got request to exit");
  162. Log_info(context->logger, "Stopping angel");
  163. context->exitTxid = String_clone(txid, context->allocator);
  164. Dict angelExit = Dict_CONST(String_CONST("q"), String_OBJ(String_CONST("Angel_exit")), NULL);
  165. Hermes_callAngel(&angelExit,
  166. onAngelExitResponse,
  167. context,
  168. context->allocator,
  169. NULL,
  170. context->hermes);
  171. }
  172. static void angelDied(struct Pipe* p, int status)
  173. {
  174. exit(1);
  175. }
  176. struct Core_Context
  177. {
  178. struct Sockaddr* ipAddr;
  179. struct Ducttape* ducttape;
  180. struct Log* logger;
  181. struct Allocator* alloc;
  182. struct Admin* admin;
  183. struct EventBase* eventBase;
  184. struct IpTunnel* ipTunnel;
  185. };
  186. static void sendResponse(String* error,
  187. struct Admin* admin,
  188. String* txid,
  189. struct Allocator* tempAlloc)
  190. {
  191. Dict* output = Dict_new(tempAlloc);
  192. Dict_putString(output, String_CONST("error"), error, tempAlloc);
  193. Admin_sendMessage(output, txid, admin);
  194. }
  195. static void initTunnel(Dict* args, void* vcontext, String* txid, struct Allocator* requestAlloc)
  196. {
  197. struct Core_Context* const ctx = (struct Core_Context*) vcontext;
  198. struct Jmp jmp;
  199. Jmp_try(jmp) {
  200. Core_initTunnel(Dict_getString(args, String_CONST("desiredTunName")),
  201. ctx->ipAddr,
  202. 8,
  203. ctx->ducttape,
  204. ctx->logger,
  205. ctx->ipTunnel,
  206. ctx->eventBase,
  207. ctx->alloc,
  208. &jmp.handler);
  209. } Jmp_catch {
  210. String* error = String_printf(requestAlloc, "Failed to configure tunnel [%s]", jmp.message);
  211. sendResponse(error, ctx->admin, txid, requestAlloc);
  212. return;
  213. }
  214. sendResponse(String_CONST("none"), ctx->admin, txid, requestAlloc);
  215. }
  216. void Core_admin_register(struct Sockaddr* ipAddr,
  217. struct Ducttape* dt,
  218. struct Log* logger,
  219. struct IpTunnel* ipTunnel,
  220. struct Allocator* alloc,
  221. struct Admin* admin,
  222. struct EventBase* eventBase)
  223. {
  224. struct Core_Context* ctx = Allocator_malloc(alloc, sizeof(struct Core_Context));
  225. ctx->ipAddr = ipAddr;
  226. ctx->ducttape = dt;
  227. ctx->logger = logger;
  228. ctx->alloc = alloc;
  229. ctx->admin = admin;
  230. ctx->eventBase = eventBase;
  231. ctx->ipTunnel = ipTunnel;
  232. struct Admin_FunctionArg args[] = {
  233. { .name = "desiredTunName", .required = 0, .type = "String" }
  234. };
  235. Admin_registerFunction("Core_initTunnel", initTunnel, ctx, true, args, admin);
  236. }
  237. static Dict* getInitialConfig(struct Interface* iface,
  238. struct EventBase* eventBase,
  239. struct Allocator* alloc,
  240. struct Except* eh)
  241. {
  242. struct Message* m = InterfaceWaiter_waitForData(iface, eventBase, alloc, eh);
  243. struct Reader* reader = ArrayReader_new(m->bytes, m->length, alloc);
  244. Dict* config = Dict_new(alloc);
  245. if (StandardBencSerializer_get()->parseDictionary(reader, alloc, config)) {
  246. Except_throw(eh, "Failed to parse initial configuration.");
  247. }
  248. return config;
  249. }
  250. void Core_initTunnel(String* desiredDeviceName,
  251. struct Sockaddr* addr,
  252. uint8_t addressPrefix,
  253. struct Ducttape* dt,
  254. struct Log* logger,
  255. struct IpTunnel* ipTunnel,
  256. struct EventBase* eventBase,
  257. struct Allocator* alloc,
  258. struct Except* eh)
  259. {
  260. Log_debug(logger, "Initializing TUN device [%s]",
  261. (desiredDeviceName) ? desiredDeviceName->bytes : "<auto>");
  262. char assignedTunName[TUNInterface_IFNAMSIZ];
  263. char* desiredName = (desiredDeviceName) ? desiredDeviceName->bytes : NULL;
  264. struct Interface* tun =
  265. TUNInterface_new(desiredName, assignedTunName, eventBase, logger, eh, alloc);
  266. IpTunnel_setTunName(assignedTunName, ipTunnel);
  267. Ducttape_setUserInterface(dt, tun);
  268. NetDev_addAddress(assignedTunName, addr, addressPrefix, logger, eh);
  269. NetDev_setMTU(assignedTunName, DEFAULT_MTU, logger, eh);
  270. }
  271. /** This is a response from a call which is intended only to send information to the angel. */
  272. static void angelResponse(Dict* resp, void* vNULL)
  273. {
  274. // do nothing
  275. }
  276. void Core_init(struct Allocator* alloc,
  277. struct Log* logger,
  278. struct EventBase* eventBase,
  279. struct Interface* angelIface,
  280. struct Random* rand,
  281. struct Except* eh)
  282. {
  283. struct Allocator* tempAlloc = Allocator_child(alloc);
  284. Dict* config = getInitialConfig(angelIface, eventBase, tempAlloc, eh);
  285. struct Hermes* hermes = Hermes_new(angelIface, eventBase, logger, alloc);
  286. String* privateKeyHex = Dict_getString(config, String_CONST("privateKey"));
  287. Dict* adminConf = Dict_getDict(config, String_CONST("admin"));
  288. String* pass = Dict_getString(adminConf, String_CONST("pass"));
  289. String* bind = Dict_getString(adminConf, String_CONST("bind"));
  290. if (!(pass && privateKeyHex && bind)) {
  291. if (!pass) {
  292. Except_throw(eh, "Expected 'pass'");
  293. }
  294. if (!bind) {
  295. Except_throw(eh, "Expected 'bind'");
  296. }
  297. if (!privateKeyHex) {
  298. Except_throw(eh, "Expected 'privateKey'");
  299. }
  300. Except_throw(eh, "Expected 'pass', 'privateKey' and 'bind' in configuration.");
  301. }
  302. Log_keys(logger, "Starting core with admin password [%s]", pass->bytes);
  303. uint8_t privateKey[32];
  304. if (privateKeyHex->len != 64
  305. || Hex_decode(privateKey, 32, (uint8_t*) privateKeyHex->bytes, 64) != 32)
  306. {
  307. Except_throw(eh, "privateKey must be 64 bytes of hex.");
  308. }
  309. struct Sockaddr_storage bindAddr;
  310. if (Sockaddr_parse(bind->bytes, &bindAddr)) {
  311. Except_throw(eh, "bind address [%s] unparsable", bind->bytes);
  312. }
  313. struct AddrInterface* udpAdmin =
  314. UDPAddrInterface_new(eventBase, &bindAddr.addr, alloc, eh, logger);
  315. struct Admin* admin = Admin_new(udpAdmin, alloc, logger, eventBase, pass);
  316. char* boundAddr = Sockaddr_print(udpAdmin->addr, tempAlloc);
  317. Dict adminResponse = Dict_CONST(
  318. String_CONST("bind"), String_OBJ(String_CONST(boundAddr)), NULL
  319. );
  320. Dict response = Dict_CONST(
  321. String_CONST("error"), String_OBJ(String_CONST("none")), Dict_CONST(
  322. String_CONST("admin"), Dict_OBJ(&adminResponse), NULL
  323. ));
  324. // This always times out because the angel doesn't respond.
  325. Hermes_callAngel(&response, angelResponse, NULL, alloc, eh, hermes);
  326. // --------------------- Setup the Logger --------------------- //
  327. Dict* logging = Dict_getDict(config, String_CONST("logging"));
  328. String* logTo = Dict_getString(logging, String_CONST("logTo"));
  329. if (logTo && String_equals(logTo, String_CONST("stdout"))) {
  330. // do nothing, continue logging to stdout.
  331. } else {
  332. struct Log* adminLogger = AdminLog_registerNew(admin, alloc, rand);
  333. IndirectLog_set(logger, adminLogger);
  334. logger = adminLogger;
  335. }
  336. // CryptoAuth
  337. struct Address addr = { .protocolVersion = Version_CURRENT_PROTOCOL };
  338. parsePrivateKey(privateKey, &addr, eh);
  339. struct CryptoAuth* cryptoAuth = CryptoAuth_new(alloc, privateKey, eventBase, logger, rand);
  340. struct Sockaddr* myAddr = Sockaddr_fromBytes(addr.ip6.bytes, Sockaddr_AF_INET6, alloc);
  341. struct SwitchCore* switchCore = SwitchCore_new(logger, alloc);
  342. struct DHTModuleRegistry* registry = DHTModuleRegistry_new(alloc);
  343. ReplyModule_register(registry, alloc);
  344. struct NodeStore* nodeStore = NodeStore_new(&addr, NODE_STORE_SIZE, alloc, logger);
  345. struct RouterModule* routerModule = RouterModule_register(registry,
  346. alloc,
  347. addr.key,
  348. eventBase,
  349. logger,
  350. rand,
  351. nodeStore);
  352. struct RumorMill* rumorMill = RumorMill_new(alloc, &addr, RUMORMILL_CAPACITY);
  353. struct RumorMill* nodesOfInterest = RumorMill_new(alloc, &addr, RUMORMILL_CAPACITY);
  354. struct SearchRunner* searchRunner = SearchRunner_new(nodeStore,
  355. logger,
  356. eventBase,
  357. routerModule,
  358. addr.ip6.bytes,
  359. rumorMill,
  360. alloc);
  361. Janitor_new(LOCAL_MAINTENANCE_SEARCH_MILLISECONDS,
  362. GLOBAL_MAINTENANCE_SEARCH_MILLISECONDS,
  363. routerModule,
  364. nodeStore,
  365. searchRunner,
  366. rumorMill,
  367. nodesOfInterest,
  368. logger,
  369. alloc,
  370. eventBase,
  371. rand);
  372. EncodingSchemeModule_register(registry, logger, alloc);
  373. SerializationModule_register(registry, logger, alloc);
  374. struct IpTunnel* ipTun = IpTunnel_new(logger, eventBase, alloc, rand, hermes);
  375. struct Ducttape* dt = Ducttape_register(privateKey,
  376. registry,
  377. routerModule,
  378. searchRunner,
  379. nodesOfInterest,
  380. switchCore,
  381. eventBase,
  382. alloc,
  383. logger,
  384. ipTun,
  385. rand);
  386. struct SwitchPinger* sp =
  387. SwitchPinger_new(&dt->switchPingerIf, eventBase, rand, logger, &addr, alloc);
  388. // Interfaces.
  389. struct InterfaceController* ifController =
  390. DefaultInterfaceController_new(cryptoAuth,
  391. switchCore,
  392. routerModule,
  393. rumorMill,
  394. logger,
  395. eventBase,
  396. sp,
  397. rand,
  398. alloc);
  399. // ------------------- DNS -------------------------//
  400. struct Sockaddr_storage rainflyAddr;
  401. Assert_true(!Sockaddr_parse("::", &rainflyAddr));
  402. struct AddrInterface* rainflyIface =
  403. UDPAddrInterface_new(eventBase, &rainflyAddr.addr, alloc, eh, logger);
  404. struct RainflyClient* rainfly = RainflyClient_new(rainflyIface, eventBase, rand, logger);
  405. Assert_true(!Sockaddr_parse("[fc00::1]:53", &rainflyAddr));
  406. struct AddrInterface* magicUDP =
  407. PacketHeaderToUDPAddrInterface_new(&dt->magicInterface, alloc, &rainflyAddr.addr);
  408. DNSServer_new(magicUDP, logger, rainfly);
  409. // ------------------- Register RPC functions ----------------------- //
  410. InterfaceController_admin_register(ifController, admin, alloc);
  411. SwitchPinger_admin_register(sp, admin, alloc);
  412. UDPInterface_admin_register(eventBase, alloc, logger, admin, ifController);
  413. #ifdef HAS_ETH_INTERFACE
  414. ETHInterface_admin_register(eventBase, alloc, logger, admin, ifController);
  415. #endif
  416. NodeStore_admin_register(nodeStore, admin, alloc);
  417. RouterModule_admin_register(routerModule, admin, alloc);
  418. SearchRunner_admin_register(searchRunner, admin, alloc);
  419. AuthorizedPasswords_init(admin, cryptoAuth, alloc);
  420. Admin_registerFunction("ping", adminPing, admin, false, NULL, admin);
  421. Core_admin_register(myAddr, dt, logger, ipTun, alloc, admin, eventBase);
  422. Security_admin_register(alloc, logger, admin);
  423. IpTunnel_admin_register(ipTun, admin, alloc);
  424. SessionManager_admin_register(dt->sessionManager, admin, alloc);
  425. RainflyClient_admin_register(rainfly, admin, alloc);
  426. Allocator_admin_register(alloc, admin);
  427. struct Context* ctx = Allocator_clone(alloc, (&(struct Context) {
  428. .allocator = alloc,
  429. .admin = admin,
  430. .logger = logger,
  431. .hermes = hermes,
  432. .base = eventBase,
  433. }));
  434. Admin_registerFunction("Core_exit", adminExit, ctx, true, NULL, admin);
  435. }
  436. int Core_main(int argc, char** argv)
  437. {
  438. struct Except* eh = NULL;
  439. if (argc != 3) {
  440. Except_throw(eh, "This is internal to cjdns and shouldn't started manually.");
  441. }
  442. struct Allocator* alloc = MallocAllocator_new(ALLOCATOR_FAILSAFE);
  443. struct Log* preLogger = FileWriterLog_new(stderr, alloc);
  444. struct EventBase* eventBase = EventBase_new(alloc);
  445. // -------------------- Setup the Pre-Logger ---------------------- //
  446. struct Log* logger = IndirectLog_new(alloc);
  447. IndirectLog_set(logger, preLogger);
  448. // -------------------- Setup the PRNG ---------------------- //
  449. struct Random* rand = LibuvEntropyProvider_newDefaultRandom(eventBase, logger, eh, alloc);
  450. // -------------------- Change Canary Value ---------------------- //
  451. Allocator_setCanary(alloc, (unsigned long)Random_uint64(rand));
  452. // The first read inside of getInitialConfig() will begin it waiting.
  453. struct Pipe* angelPipe = Pipe_named(argv[2], eventBase, eh, alloc);
  454. angelPipe->logger = logger;
  455. angelPipe->onClose = angelDied;
  456. struct Interface* angelIface = FramingInterface_new(65535, &angelPipe->iface, alloc);
  457. Core_init(alloc, logger, eventBase, angelIface, rand, eh);
  458. EventBase_beginLoop(eventBase);
  459. return 0;
  460. }