1
0

Core.c 16 KB

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