Core.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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/Core.h"
  18. #include "admin/angel/InterfaceWaiter.h"
  19. #include "admin/AuthorizedPasswords.h"
  20. #include "benc/Int.h"
  21. #include "benc/serialization/standard/BencMessageReader.h"
  22. #include "benc/serialization/standard/BencMessageWriter.h"
  23. #include "crypto/AddressCalc.h"
  24. #include "crypto/random/Random.h"
  25. #include "crypto/random/libuv/LibuvEntropyProvider.h"
  26. #include "dht/Pathfinder.h"
  27. #include "exception/Jmp.h"
  28. #include "interface/Iface.h"
  29. #include "util/events/UDPAddrIface.h"
  30. #include "interface/tuntap/TUNInterface.h"
  31. #include "interface/UDPInterface_admin.h"
  32. #ifdef HAS_ETH_INTERFACE
  33. #include "interface/ETHInterface_admin.h"
  34. #endif
  35. #include "net/InterfaceController_admin.h"
  36. #include "interface/addressable/PacketHeaderToUDPAddrIface.h"
  37. #include "interface/FramingIface.h"
  38. #include "memory/Allocator.h"
  39. #include "memory/MallocAllocator.h"
  40. #include "memory/Allocator_admin.h"
  41. #include "net/SwitchPinger_admin.h"
  42. #include "tunnel/IpTunnel_admin.h"
  43. #include "util/events/EventBase.h"
  44. #include "util/events/Pipe.h"
  45. #include "util/events/Timeout.h"
  46. #include "util/Hex.h"
  47. #include "util/log/FileWriterLog.h"
  48. #include "util/log/IndirectLog.h"
  49. #include "util/platform/netdev/NetDev.h"
  50. #include "util/Security_admin.h"
  51. #include "util/Security.h"
  52. #include "util/version/Version.h"
  53. #include "net/SessionManager_admin.h"
  54. #include "wire/SwitchHeader.h"
  55. #include "wire/CryptoHeader.h"
  56. #include "wire/Headers.h"
  57. #include "net/NetCore.h"
  58. #include <crypto_scalarmult_curve25519.h>
  59. #include <stdlib.h>
  60. #include <unistd.h>
  61. // Failsafe: abort if more than 2^23 bytes are allocated (8MB)
  62. #define ALLOCATOR_FAILSAFE (1<<23)
  63. // TODO(cjd): we need to begin detecting MTU and informing the OS properly!
  64. /**
  65. * The worst possible packet overhead, we're in session setup with the endpoint.
  66. */
  67. #define WORST_CASE_OVERHEAD ( \
  68. Headers_IP4Header_SIZE \
  69. + Headers_UDPHeader_SIZE \
  70. + 4 /* Nonce */ \
  71. + 16 /* Poly1305 authenticator */ \
  72. + SwitchHeader_SIZE \
  73. + CryptoHeader_SIZE \
  74. + 4 /* Handle */ \
  75. + DataHeader_SIZE \
  76. )
  77. /** The default MTU, assuming the external MTU is 1492 (common for PPPoE DSL) */
  78. #define DEFAULT_MTU ( 1492 - WORST_CASE_OVERHEAD )
  79. static void adminPing(Dict* input, void* vadmin, String* txid, struct Allocator* requestAlloc)
  80. {
  81. Dict d = Dict_CONST(String_CONST("q"), String_OBJ(String_CONST("pong")), NULL);
  82. Admin_sendMessage(&d, txid, (struct Admin*) vadmin);
  83. }
  84. static void adminPid(Dict* input, void* vadmin, String* txid, struct Allocator* requestAlloc)
  85. {
  86. int pid = getpid();
  87. Dict d = Dict_CONST(String_CONST("pid"), Int_OBJ(pid), NULL);
  88. Admin_sendMessage(&d, txid, (struct Admin*) vadmin);
  89. }
  90. struct Context
  91. {
  92. struct Allocator* alloc;
  93. struct Admin* admin;
  94. struct Log* logger;
  95. struct EventBase* base;
  96. struct NetCore* nc;
  97. struct IpTunnel* ipTunnel;
  98. Identity
  99. };
  100. static void shutdown(void* vcontext)
  101. {
  102. struct Context* context = Identity_check((struct Context*) vcontext);
  103. Allocator_free(context->alloc);
  104. }
  105. static void adminExit(Dict* input, void* vcontext, String* txid, struct Allocator* requestAlloc)
  106. {
  107. struct Context* context = Identity_check((struct Context*) vcontext);
  108. Log_info(context->logger, "Got request to exit");
  109. Dict d = Dict_CONST(String_CONST("error"), String_OBJ(String_CONST("none")), NULL);
  110. Admin_sendMessage(&d, txid, context->admin);
  111. Timeout_setTimeout(shutdown, context, 1, context->base, context->alloc);
  112. }
  113. static void sendResponse(String* error,
  114. struct Admin* admin,
  115. String* txid,
  116. struct Allocator* tempAlloc)
  117. {
  118. Dict* output = Dict_new(tempAlloc);
  119. Dict_putString(output, String_CONST("error"), error, tempAlloc);
  120. Admin_sendMessage(output, txid, admin);
  121. }
  122. static void initTunnel2(String* desiredDeviceName,
  123. struct Context* ctx,
  124. uint8_t addressPrefix,
  125. struct Except* eh)
  126. {
  127. Log_debug(ctx->logger, "Initializing TUN device [%s]",
  128. (desiredDeviceName) ? desiredDeviceName->bytes : "<auto>");
  129. char assignedTunName[TUNInterface_IFNAMSIZ];
  130. char* desiredName = (desiredDeviceName) ? desiredDeviceName->bytes : NULL;
  131. struct Iface* tun = TUNInterface_new(
  132. desiredName, assignedTunName, 0, ctx->base, ctx->logger, eh, ctx->alloc);
  133. Iface_plumb(tun, &ctx->nc->tunAdapt->tunIf);
  134. IpTunnel_setTunName(assignedTunName, ctx->ipTunnel);
  135. struct Sockaddr* myAddr =
  136. Sockaddr_fromBytes(ctx->nc->myAddress->ip6.bytes, Sockaddr_AF_INET6, ctx->alloc);
  137. NetDev_addAddress(assignedTunName, myAddr, addressPrefix, ctx->logger, eh);
  138. NetDev_setMTU(assignedTunName, DEFAULT_MTU, ctx->logger, eh);
  139. }
  140. static void initTunnel(Dict* args, void* vcontext, String* txid, struct Allocator* requestAlloc)
  141. {
  142. struct Context* const ctx = Identity_check((struct Context*) vcontext);
  143. struct Jmp jmp;
  144. Jmp_try(jmp) {
  145. String* desiredName = Dict_getString(args, String_CONST("desiredTunName"));
  146. initTunnel2(desiredName, ctx, 8, &jmp.handler);
  147. } Jmp_catch {
  148. String* error = String_printf(requestAlloc, "Failed to configure tunnel [%s]", jmp.message);
  149. sendResponse(error, ctx->admin, txid, requestAlloc);
  150. return;
  151. }
  152. sendResponse(String_CONST("none"), ctx->admin, txid, requestAlloc);
  153. }
  154. void Core_init(struct Allocator* alloc,
  155. struct Log* logger,
  156. struct EventBase* eventBase,
  157. uint8_t privateKey[32],
  158. struct Admin* admin,
  159. struct Random* rand,
  160. struct Except* eh)
  161. {
  162. struct Security* sec = Security_new(alloc, logger, eventBase);
  163. struct NetCore* nc = NetCore_new(privateKey, alloc, eventBase, rand, logger);
  164. struct IpTunnel* ipTunnel = IpTunnel_new(logger, eventBase, alloc, rand);
  165. Iface_plumb(&nc->tunAdapt->ipTunnelIf, &ipTunnel->tunInterface);
  166. Iface_plumb(&nc->upper->ipTunnelIf, &ipTunnel->nodeInterface);
  167. Pathfinder_register(alloc, logger, eventBase, rand, admin, nc->ee);
  168. // ------------------- Register RPC functions ----------------------- //
  169. InterfaceController_admin_register(nc->ifController, admin, alloc);
  170. SwitchPinger_admin_register(nc->sp, admin, alloc);
  171. UDPInterface_admin_register(eventBase, alloc, logger, admin, nc->ifController);
  172. #ifdef HAS_ETH_INTERFACE
  173. ETHInterface_admin_register(eventBase, alloc, logger, admin, nc->ifController);
  174. #endif
  175. AuthorizedPasswords_init(admin, nc->ca, alloc);
  176. Admin_registerFunction("ping", adminPing, admin, false, NULL, admin);
  177. Security_admin_register(alloc, logger, sec, admin);
  178. IpTunnel_admin_register(ipTunnel, admin, alloc);
  179. SessionManager_admin_register(nc->sm, admin, alloc);
  180. Allocator_admin_register(alloc, admin);
  181. struct Context* ctx = Allocator_calloc(alloc, sizeof(struct Context), 1);
  182. Identity_set(ctx);
  183. ctx->alloc = alloc;
  184. ctx->admin = admin;
  185. ctx->logger = logger;
  186. ctx->base = eventBase;
  187. ctx->ipTunnel = ipTunnel;
  188. ctx->nc = nc;
  189. Admin_registerFunction("Core_exit", adminExit, ctx, true, NULL, admin);
  190. Admin_registerFunction("Core_pid", adminPid, admin, false, NULL, admin);
  191. Admin_registerFunction("Core_initTunnel", initTunnel, ctx, true,
  192. ((struct Admin_FunctionArg[]) {
  193. { .name = "desiredTunName", .required = 0, .type = "String" }
  194. }), admin);
  195. }
  196. int Core_main(int argc, char** argv)
  197. {
  198. struct Except* eh = NULL;
  199. if (argc != 3) {
  200. Except_throw(eh, "This is internal to cjdns and shouldn't started manually.");
  201. }
  202. struct Allocator* alloc = MallocAllocator_new(ALLOCATOR_FAILSAFE);
  203. struct Log* preLogger = FileWriterLog_new(stderr, alloc);
  204. struct EventBase* eventBase = EventBase_new(alloc);
  205. // -------------------- Setup the Pre-Logger ---------------------- //
  206. struct Log* logger = IndirectLog_new(alloc);
  207. IndirectLog_set(logger, preLogger);
  208. // -------------------- Setup the PRNG ---------------------- //
  209. struct Random* rand = LibuvEntropyProvider_newDefaultRandom(eventBase, logger, eh, alloc);
  210. // -------------------- Change Canary Value ---------------------- //
  211. Allocator_setCanary(alloc, (unsigned long)Random_uint64(rand));
  212. struct Allocator* tempAlloc = Allocator_child(alloc);
  213. struct Pipe* clientPipe = Pipe_named(argv[2], eventBase, eh, tempAlloc);
  214. clientPipe->logger = logger;
  215. Log_debug(logger, "Getting pre-configuration from client");
  216. struct Message* preConf =
  217. InterfaceWaiter_waitForData(&clientPipe->iface, eventBase, tempAlloc, eh);
  218. Log_debug(logger, "Finished getting pre-configuration from client");
  219. Dict* config = BencMessageReader_read(preConf, tempAlloc, eh);
  220. String* privateKeyHex = Dict_getString(config, String_CONST("privateKey"));
  221. Dict* adminConf = Dict_getDict(config, String_CONST("admin"));
  222. String* pass = Dict_getString(adminConf, String_CONST("pass"));
  223. String* bind = Dict_getString(adminConf, String_CONST("bind"));
  224. if (!(pass && privateKeyHex && bind)) {
  225. if (!pass) {
  226. Except_throw(eh, "Expected 'pass'");
  227. }
  228. if (!bind) {
  229. Except_throw(eh, "Expected 'bind'");
  230. }
  231. if (!privateKeyHex) {
  232. Except_throw(eh, "Expected 'privateKey'");
  233. }
  234. Except_throw(eh, "Expected 'pass', 'privateKey' and 'bind' in configuration.");
  235. }
  236. Log_keys(logger, "Starting core with admin password [%s]", pass->bytes);
  237. uint8_t privateKey[32];
  238. if (privateKeyHex->len != 64
  239. || Hex_decode(privateKey, 32, (uint8_t*) privateKeyHex->bytes, 64) != 32)
  240. {
  241. Except_throw(eh, "privateKey must be 64 bytes of hex.");
  242. }
  243. struct Sockaddr_storage bindAddr;
  244. if (Sockaddr_parse(bind->bytes, &bindAddr)) {
  245. Except_throw(eh, "bind address [%s] unparsable", bind->bytes);
  246. }
  247. // --------------------- Bind Admin UDP --------------------- //
  248. struct UDPAddrIface* udpAdmin = UDPAddrIface_new(eventBase, &bindAddr.addr, alloc, eh, logger);
  249. // --------------------- Setup Admin --------------------- //
  250. struct Admin* admin = Admin_new(&udpAdmin->generic, logger, eventBase, pass);
  251. // --------------------- Setup the Logger --------------------- //
  252. Dict* logging = Dict_getDict(config, String_CONST("logging"));
  253. String* logTo = Dict_getString(logging, String_CONST("logTo"));
  254. if (logTo && String_equals(logTo, String_CONST("stdout"))) {
  255. // do nothing, continue logging to stdout.
  256. } else {
  257. struct Log* adminLogger = AdminLog_registerNew(admin, alloc, rand, eventBase);
  258. IndirectLog_set(logger, adminLogger);
  259. logger = adminLogger;
  260. }
  261. // --------------------- Inform client of UDP Addr --------------------- //
  262. char* boundAddr = Sockaddr_print(udpAdmin->generic.addr, tempAlloc);
  263. Dict adminResponse = Dict_CONST(
  264. String_CONST("bind"), String_OBJ(String_CONST(boundAddr)), NULL
  265. );
  266. Dict response = Dict_CONST(
  267. String_CONST("error"), String_OBJ(String_CONST("none")), Dict_CONST(
  268. String_CONST("admin"), Dict_OBJ(&adminResponse), NULL
  269. ));
  270. // This always times out because the angel doesn't respond.
  271. struct Message* clientResponse = Message_new(0, 512, tempAlloc);
  272. BencMessageWriter_write(&response, clientResponse, eh);
  273. Iface_CALL(clientPipe->iface.send, clientResponse, &clientPipe->iface);
  274. Allocator_free(tempAlloc);
  275. Core_init(alloc, logger, eventBase, privateKey, admin, rand, eh);
  276. EventBase_beginLoop(eventBase);
  277. return 0;
  278. }