Core.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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/standard/BencMessageReader.h"
  24. #include "crypto/AddressCalc.h"
  25. #include "crypto/random/Random.h"
  26. #include "crypto/random/libuv/LibuvEntropyProvider.h"
  27. #include "dht/Pathfinder.h"
  28. #include "exception/Jmp.h"
  29. #include "interface/Iface.h"
  30. #include "util/events/UDPAddrIface.h"
  31. #include "interface/tuntap/TUNInterface.h"
  32. #include "interface/UDPInterface_admin.h"
  33. #ifdef HAS_ETH_INTERFACE
  34. #include "interface/ETHInterface_admin.h"
  35. #endif
  36. #include "net/InterfaceController_admin.h"
  37. #include "interface/addressable/PacketHeaderToUDPAddrIface.h"
  38. #include "interface/FramingIface.h"
  39. #include "interface/RainflyClient.h"
  40. #include "interface/RainflyClient_admin.h"
  41. #include "interface/DNSServer.h"
  42. #include "memory/Allocator.h"
  43. #include "memory/MallocAllocator.h"
  44. #include "memory/Allocator_admin.h"
  45. #include "net/SwitchPinger_admin.h"
  46. #include "tunnel/IpTunnel_admin.h"
  47. #include "util/events/EventBase.h"
  48. #include "util/events/Pipe.h"
  49. #include "util/events/Timeout.h"
  50. #include "util/Hex.h"
  51. #include "util/log/FileWriterLog.h"
  52. #include "util/log/IndirectLog.h"
  53. #include "util/platform/netdev/NetDev.h"
  54. #include "util/Security_admin.h"
  55. #include "util/Security.h"
  56. #include "util/version/Version.h"
  57. #include "net/SessionManager_admin.h"
  58. #include "wire/SwitchHeader.h"
  59. #include "wire/CryptoHeader.h"
  60. #include "wire/Headers.h"
  61. #include "net/NetCore.h"
  62. #include <crypto_scalarmult_curve25519.h>
  63. #include <stdlib.h>
  64. #include <unistd.h>
  65. // Failsafe: abort if more than 2^23 bytes are allocated (8MB)
  66. #define ALLOCATOR_FAILSAFE (1<<23)
  67. /**
  68. * The worst possible packet overhead.
  69. * assuming the packet needs to be handed off to another node
  70. * because we have no route to the destination.
  71. * and the CryptoAuths to both the destination and the handoff node are both timed out.
  72. */
  73. #define WORST_CASE_OVERHEAD ( \
  74. /* TODO(cjd): Headers_IPv4_SIZE */ 20 \
  75. + Headers_UDPHeader_SIZE \
  76. + 4 /* Nonce */ \
  77. + 16 /* Poly1305 authenticator */ \
  78. + SwitchHeader_SIZE \
  79. + CryptoHeader_SIZE \
  80. + Headers_IP6Header_SIZE \
  81. + CryptoHeader_SIZE \
  82. )
  83. /** The default MTU, assuming the external MTU is 1492 (common for PPPoE DSL) */
  84. #define DEFAULT_MTU ( \
  85. 1492 \
  86. - WORST_CASE_OVERHEAD \
  87. + Headers_IP6Header_SIZE /* The OS subtracts the IP6 header. */ \
  88. + CryptoHeader_SIZE /* Linux won't let set the MTU below 1280.
  89. TODO(cjd): make sure we never hand off to a node for which the CA session is expired. */ \
  90. )
  91. static void adminPing(Dict* input, void* vadmin, String* txid, struct Allocator* requestAlloc)
  92. {
  93. Dict d = Dict_CONST(String_CONST("q"), String_OBJ(String_CONST("pong")), NULL);
  94. Admin_sendMessage(&d, txid, (struct Admin*) vadmin);
  95. }
  96. static void adminPid(Dict* input, void* vadmin, String* txid, struct Allocator* requestAlloc)
  97. {
  98. int pid = getpid();
  99. Dict d = Dict_CONST(String_CONST("pid"), Int_OBJ(pid), NULL);
  100. Admin_sendMessage(&d, txid, (struct Admin*) vadmin);
  101. }
  102. struct Context
  103. {
  104. struct Allocator* alloc;
  105. struct Admin* admin;
  106. struct Log* logger;
  107. struct Hermes* hermes;
  108. struct EventBase* base;
  109. struct NetCore* nc;
  110. struct IpTunnel* ipTunnel;
  111. String* exitTxid;
  112. Identity
  113. };
  114. static void shutdown(void* vcontext)
  115. {
  116. struct Context* context = Identity_check((struct Context*) vcontext);
  117. Allocator_free(context->alloc);
  118. }
  119. static void onAngelExitResponse(Dict* message, void* vcontext)
  120. {
  121. struct Context* context = Identity_check((struct Context*) vcontext);
  122. Log_info(context->logger, "Angel stopped");
  123. Log_info(context->logger, "Exiting");
  124. Dict d = Dict_CONST(String_CONST("error"), String_OBJ(String_CONST("none")), NULL);
  125. Admin_sendMessage(&d, context->exitTxid, context->admin);
  126. Timeout_setTimeout(shutdown, context, 1, context->base, context->alloc);
  127. }
  128. static void adminExit(Dict* input, void* vcontext, String* txid, struct Allocator* requestAlloc)
  129. {
  130. struct Context* context = Identity_check((struct Context*) vcontext);
  131. Log_info(context->logger, "Got request to exit");
  132. Log_info(context->logger, "Stopping angel");
  133. context->exitTxid = String_clone(txid, context->alloc);
  134. Dict angelExit = Dict_CONST(String_CONST("q"), String_OBJ(String_CONST("Angel_exit")), NULL);
  135. Hermes_callAngel(&angelExit,
  136. onAngelExitResponse,
  137. context,
  138. context->alloc,
  139. NULL,
  140. context->hermes);
  141. }
  142. static void angelDied(struct Pipe* p, int status)
  143. {
  144. exit(1);
  145. }
  146. static void sendResponse(String* error,
  147. struct Admin* admin,
  148. String* txid,
  149. struct Allocator* tempAlloc)
  150. {
  151. Dict* output = Dict_new(tempAlloc);
  152. Dict_putString(output, String_CONST("error"), error, tempAlloc);
  153. Admin_sendMessage(output, txid, admin);
  154. }
  155. static void initTunnel2(String* desiredDeviceName,
  156. struct Context* ctx,
  157. uint8_t addressPrefix,
  158. struct Except* eh)
  159. {
  160. Log_debug(ctx->logger, "Initializing TUN device [%s]",
  161. (desiredDeviceName) ? desiredDeviceName->bytes : "<auto>");
  162. char assignedTunName[TUNInterface_IFNAMSIZ];
  163. char* desiredName = (desiredDeviceName) ? desiredDeviceName->bytes : NULL;
  164. struct Iface* tun = TUNInterface_new(
  165. desiredName, assignedTunName, 0, ctx->base, ctx->logger, eh, ctx->alloc);
  166. Iface_plumb(tun, &ctx->nc->tunAdapt->tunIf);
  167. IpTunnel_setTunName(assignedTunName, ctx->ipTunnel);
  168. struct Sockaddr* myAddr =
  169. Sockaddr_fromBytes(ctx->nc->myAddress->ip6.bytes, Sockaddr_AF_INET6, ctx->alloc);
  170. NetDev_addAddress(assignedTunName, myAddr, addressPrefix, ctx->logger, eh);
  171. NetDev_setMTU(assignedTunName, DEFAULT_MTU, ctx->logger, eh);
  172. }
  173. static void initTunnel(Dict* args, void* vcontext, String* txid, struct Allocator* requestAlloc)
  174. {
  175. struct Context* const ctx = Identity_check((struct Context*) vcontext);
  176. struct Jmp jmp;
  177. Jmp_try(jmp) {
  178. String* desiredName = Dict_getString(args, String_CONST("desiredTunName"));
  179. initTunnel2(desiredName, ctx, 8, &jmp.handler);
  180. } Jmp_catch {
  181. String* error = String_printf(requestAlloc, "Failed to configure tunnel [%s]", jmp.message);
  182. sendResponse(error, ctx->admin, txid, requestAlloc);
  183. return;
  184. }
  185. sendResponse(String_CONST("none"), ctx->admin, txid, requestAlloc);
  186. }
  187. static Dict* getInitialConfig(struct Iface* iface,
  188. struct EventBase* eventBase,
  189. struct Allocator* alloc,
  190. struct Except* eh)
  191. {
  192. struct Message* m = InterfaceWaiter_waitForData(iface, eventBase, alloc, eh);
  193. return BencMessageReader_read(m, alloc, eh);
  194. }
  195. /** This is a response from a call which is intended only to send information to the angel. */
  196. static void angelResponse(Dict* resp, void* vNULL)
  197. {
  198. // do nothing
  199. }
  200. void Core_init(struct Allocator* alloc,
  201. struct Log* logger,
  202. struct EventBase* eventBase,
  203. struct Iface* angelIface,
  204. struct Random* rand,
  205. struct Except* eh)
  206. {
  207. struct Allocator* tempAlloc = Allocator_child(alloc);
  208. Dict* config = getInitialConfig(angelIface, eventBase, tempAlloc, eh);
  209. struct Hermes* hermes = Hermes_new(angelIface, eventBase, logger, alloc);
  210. String* privateKeyHex = Dict_getString(config, String_CONST("privateKey"));
  211. Dict* adminConf = Dict_getDict(config, String_CONST("admin"));
  212. String* pass = Dict_getString(adminConf, String_CONST("pass"));
  213. String* bind = Dict_getString(adminConf, String_CONST("bind"));
  214. if (!(pass && privateKeyHex && bind)) {
  215. if (!pass) {
  216. Except_throw(eh, "Expected 'pass'");
  217. }
  218. if (!bind) {
  219. Except_throw(eh, "Expected 'bind'");
  220. }
  221. if (!privateKeyHex) {
  222. Except_throw(eh, "Expected 'privateKey'");
  223. }
  224. Except_throw(eh, "Expected 'pass', 'privateKey' and 'bind' in configuration.");
  225. }
  226. Log_keys(logger, "Starting core with admin password [%s]", pass->bytes);
  227. uint8_t privateKey[32];
  228. if (privateKeyHex->len != 64
  229. || Hex_decode(privateKey, 32, (uint8_t*) privateKeyHex->bytes, 64) != 32)
  230. {
  231. Except_throw(eh, "privateKey must be 64 bytes of hex.");
  232. }
  233. struct Sockaddr_storage bindAddr;
  234. if (Sockaddr_parse(bind->bytes, &bindAddr)) {
  235. Except_throw(eh, "bind address [%s] unparsable", bind->bytes);
  236. }
  237. struct UDPAddrIface* udpAdmin = UDPAddrIface_new(eventBase, &bindAddr.addr, alloc, eh, logger);
  238. struct Admin* admin = Admin_new(&udpAdmin->generic, logger, eventBase, pass);
  239. char* boundAddr = Sockaddr_print(udpAdmin->generic.addr, tempAlloc);
  240. Dict adminResponse = Dict_CONST(
  241. String_CONST("bind"), String_OBJ(String_CONST(boundAddr)), NULL
  242. );
  243. Dict response = Dict_CONST(
  244. String_CONST("error"), String_OBJ(String_CONST("none")), Dict_CONST(
  245. String_CONST("admin"), Dict_OBJ(&adminResponse), NULL
  246. ));
  247. // This always times out because the angel doesn't respond.
  248. Hermes_callAngel(&response, angelResponse, NULL, alloc, eh, hermes);
  249. // --------------------- Setup the Logger --------------------- //
  250. Dict* logging = Dict_getDict(config, String_CONST("logging"));
  251. String* logTo = Dict_getString(logging, String_CONST("logTo"));
  252. if (logTo && String_equals(logTo, String_CONST("stdout"))) {
  253. // do nothing, continue logging to stdout.
  254. } else {
  255. struct Log* adminLogger = AdminLog_registerNew(admin, alloc, rand, eventBase);
  256. IndirectLog_set(logger, adminLogger);
  257. logger = adminLogger;
  258. }
  259. struct NetCore* nc = NetCore_new(privateKey, alloc, eventBase, rand, logger);
  260. struct IpTunnel* ipTunnel = IpTunnel_new(logger, eventBase, alloc, rand, hermes);
  261. Iface_plumb(&nc->tunAdapt->ipTunnelIf, &ipTunnel->tunInterface);
  262. Iface_plumb(&nc->upper->ipTunnelIf, &ipTunnel->nodeInterface);
  263. Pathfinder_register(alloc, logger, eventBase, rand, admin, nc->ee);
  264. // ------------------- DNS -------------------------//
  265. struct Sockaddr_storage rainflyAddr;
  266. Assert_true(!Sockaddr_parse("::", &rainflyAddr));
  267. struct UDPAddrIface* rainflyIface =
  268. UDPAddrIface_new(eventBase, &rainflyAddr.addr, alloc, eh, logger);
  269. struct RainflyClient* rainfly =
  270. RainflyClient_new(&rainflyIface->generic, eventBase, rand, logger);
  271. Assert_true(!Sockaddr_parse("[fc00::1]:53", &rainflyAddr));
  272. struct PacketHeaderToUDPAddrIface* magicUDP =
  273. PacketHeaderToUDPAddrIface_new(alloc, &rainflyAddr.addr);
  274. // Iface_plumb(&magicUDP->headerIf, &dtAAAAAAAAAAAAAA->magicIf);
  275. DNSServer_new(&magicUDP->udpIf, logger, rainfly);
  276. // ------------------- Register RPC functions ----------------------- //
  277. InterfaceController_admin_register(nc->ifController, admin, alloc);
  278. SwitchPinger_admin_register(nc->sp, admin, alloc);
  279. UDPInterface_admin_register(eventBase, alloc, logger, admin, nc->ifController);
  280. #ifdef HAS_ETH_INTERFACE
  281. ETHInterface_admin_register(eventBase, alloc, logger, admin, nc->ifController, hermes);
  282. #endif
  283. AuthorizedPasswords_init(admin, nc->ca, alloc);
  284. Admin_registerFunction("ping", adminPing, admin, false, NULL, admin);
  285. // Core_admin_register(myAddr, logger, ipTun, alloc, admin, eventBase);
  286. Security_admin_register(alloc, logger, admin);
  287. IpTunnel_admin_register(ipTunnel, admin, alloc);
  288. SessionManager_admin_register(nc->sm, admin, alloc);
  289. RainflyClient_admin_register(rainfly, admin, alloc);
  290. Allocator_admin_register(alloc, admin);
  291. struct Context* ctx = Allocator_calloc(alloc, sizeof(struct Context), 1);
  292. Identity_set(ctx);
  293. ctx->alloc = alloc;
  294. ctx->admin = admin;
  295. ctx->logger = logger;
  296. ctx->hermes = hermes;
  297. ctx->base = eventBase;
  298. ctx->ipTunnel = ipTunnel;
  299. ctx->nc = nc;
  300. Admin_registerFunction("Core_exit", adminExit, ctx, true, NULL, admin);
  301. Admin_registerFunction("Core_pid", adminPid, admin, false, NULL, admin);
  302. Admin_registerFunction("Core_initTunnel", initTunnel, ctx, true,
  303. ((struct Admin_FunctionArg[]) {
  304. { .name = "desiredTunName", .required = 0, .type = "String" }
  305. }), admin);
  306. }
  307. int Core_main(int argc, char** argv)
  308. {
  309. struct Except* eh = NULL;
  310. if (argc != 3) {
  311. Except_throw(eh, "This is internal to cjdns and shouldn't started manually.");
  312. }
  313. struct Allocator* alloc = MallocAllocator_new(ALLOCATOR_FAILSAFE);
  314. struct Log* preLogger = FileWriterLog_new(stderr, alloc);
  315. struct EventBase* eventBase = EventBase_new(alloc);
  316. // -------------------- Setup the Pre-Logger ---------------------- //
  317. struct Log* logger = IndirectLog_new(alloc);
  318. IndirectLog_set(logger, preLogger);
  319. // -------------------- Setup the PRNG ---------------------- //
  320. struct Random* rand = LibuvEntropyProvider_newDefaultRandom(eventBase, logger, eh, alloc);
  321. // -------------------- Change Canary Value ---------------------- //
  322. Allocator_setCanary(alloc, (unsigned long)Random_uint64(rand));
  323. // The first read inside of getInitialConfig() will begin it waiting.
  324. struct Pipe* angelPipe = Pipe_named(argv[2], eventBase, eh, alloc);
  325. angelPipe->logger = logger;
  326. angelPipe->onClose = angelDied;
  327. struct Iface* angelIface = FramingIface_new(65535, &angelPipe->iface, alloc);
  328. Core_init(alloc, logger, eventBase, angelIface, rand, eh);
  329. EventBase_beginLoop(eventBase);
  330. return 0;
  331. }