Admin.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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 <https://www.gnu.org/licenses/>.
  14. */
  15. #include "admin/Admin.h"
  16. #include "benc/String.h"
  17. #include "benc/Int.h"
  18. #include "benc/Dict.h"
  19. #include "benc/serialization/standard/BencMessageWriter.h"
  20. #include "benc/serialization/standard/BencMessageReader.h"
  21. #include "memory/Allocator.h"
  22. #include "util/Assert.h"
  23. #include "util/Bits.h"
  24. #include "util/Hex.h"
  25. #include "util/log/Log.h"
  26. #include "util/events/Time.h"
  27. #include "util/events/Timeout.h"
  28. #include "util/Identity.h"
  29. #include "util/platform/Sockaddr.h"
  30. #include "util/Defined.h"
  31. #include <crypto_hash_sha256.h>
  32. #include <crypto_verify_32.h>
  33. #include <stdlib.h>
  34. #include <stdio.h>
  35. static String* TYPE = String_CONST_SO("type");
  36. static String* REQUIRED = String_CONST_SO("required");
  37. static String* STRING = String_CONST_SO("String");
  38. static String* INTEGER = String_CONST_SO("Int");
  39. static String* DICT = String_CONST_SO("Dict");
  40. static String* LIST = String_CONST_SO("List");
  41. static String* TXID = String_CONST_SO("txid");
  42. /** Number of milliseconds before a session times out and outgoing messages are failed. */
  43. #define TIMEOUT_MILLISECONDS 30000
  44. /** map values for tracking time of last message by source address */
  45. struct MapValue
  46. {
  47. /** time when the last incoming message was received. */
  48. uint64_t timeOfLastMessage;
  49. /** used to allocate the memory for the key (Sockaddr) and value (this). */
  50. struct Allocator* allocator;
  51. };
  52. //////// generate time-of-last-message-by-address map
  53. #define Map_USE_HASH
  54. #define Map_USE_COMPARATOR
  55. #define Map_NAME LastMessageTimeByAddr
  56. #define Map_KEY_TYPE struct Sockaddr*
  57. #define Map_VALUE_TYPE struct MapValue*
  58. #include "util/Map.h"
  59. static inline uint32_t Map_LastMessageTimeByAddr_hash(struct Sockaddr** key)
  60. {
  61. return Sockaddr_hash(*key);
  62. }
  63. static inline int Map_LastMessageTimeByAddr_compare(struct Sockaddr** keyA, struct Sockaddr** keyB)
  64. {
  65. return Sockaddr_compare(*keyA, *keyB);
  66. }
  67. /////// end map
  68. struct Function
  69. {
  70. String* name;
  71. Admin_Function call;
  72. void* context;
  73. bool needsAuth;
  74. Dict* args;
  75. };
  76. struct Admin_pvt
  77. {
  78. struct Admin pub;
  79. struct Iface iface;
  80. struct EventBase* eventBase;
  81. struct Function* functions;
  82. int functionCount;
  83. struct Allocator* allocator;
  84. String* password;
  85. struct Log* logger;
  86. struct Map_LastMessageTimeByAddr map;
  87. /** non-null if we are currently in an admin request. */
  88. struct Message* currentRequest;
  89. /** non-zero if this session able to receive asynchronous messages. */
  90. int asyncEnabled;
  91. /** Length of addresses of clients which communicate with admin. */
  92. uint32_t addrLen;
  93. struct Message* tempSendMsg;
  94. Identity
  95. };
  96. static void sendMessage(struct Message* message, struct Sockaddr* dest, struct Admin_pvt* admin)
  97. {
  98. // stack overflow when used with admin logger.
  99. //Log_keys(admin->logger, "sending message to angel [%s]", message->bytes);
  100. struct AddrIface_Header aihdr = { .recvTime_high = 0 };
  101. Assert_true(dest->addrLen < AddrIface_Header_SIZE);
  102. Bits_memcpy(&aihdr.addr, dest, dest->addrLen);
  103. Message_push(message, &aihdr, AddrIface_Header_SIZE, NULL);
  104. Iface_send(&admin->iface, message);
  105. }
  106. static void sendBenc(Dict* message,
  107. struct Sockaddr* dest,
  108. struct Allocator* alloc,
  109. struct Admin_pvt* admin)
  110. {
  111. Message_reset(admin->tempSendMsg);
  112. BencMessageWriter_write(message, admin->tempSendMsg, NULL);
  113. struct Message* msg = Message_new(0, admin->tempSendMsg->length + 256, alloc);
  114. Message_push(msg, admin->tempSendMsg->bytes, admin->tempSendMsg->length, NULL);
  115. sendMessage(msg, dest, admin);
  116. }
  117. /**
  118. * If no incoming data has been sent by this address in TIMEOUT_MILLISECONDS
  119. * then Admin_sendMessage() should fail so that it doesn't endlessly send
  120. * udp packets into outer space after a logging client disconnects.
  121. */
  122. static int checkAddress(struct Admin_pvt* admin, int index, uint64_t now)
  123. {
  124. uint64_t diff = now - admin->map.values[index]->timeOfLastMessage;
  125. // check for backwards time
  126. if (diff > TIMEOUT_MILLISECONDS && diff < ((uint64_t)INT64_MAX)) {
  127. Allocator_free(admin->map.values[index]->allocator);
  128. Map_LastMessageTimeByAddr_remove(index, &admin->map);
  129. return -1;
  130. }
  131. return 0;
  132. }
  133. static void clearExpiredAddresses(void* vAdmin)
  134. {
  135. struct Admin_pvt* admin = Identity_check((struct Admin_pvt*) vAdmin);
  136. uint64_t now = Time_currentTimeMilliseconds(admin->eventBase);
  137. int count = 0;
  138. for (int i = admin->map.count - 1; i >= 0; i--) {
  139. if (checkAddress(admin, i, now)) {
  140. count++;
  141. }
  142. }
  143. Log_debug(admin->logger, "Cleared [%d] expired sessions", count);
  144. }
  145. /**
  146. * public function to send responses
  147. */
  148. int Admin_sendMessage(Dict* message, String* txid, struct Admin* adminPub)
  149. {
  150. struct Admin_pvt* admin = Identity_check((struct Admin_pvt*) adminPub);
  151. if (!admin) {
  152. return 0;
  153. }
  154. Identity_check(admin);
  155. Assert_true(txid && txid->len >= admin->addrLen);
  156. struct Sockaddr_storage addr;
  157. Bits_memcpy(&addr, txid->bytes, admin->addrLen);
  158. // if this is an async call, check if we've got any input from that client.
  159. // if the client is nresponsive then fail the call so logs don't get sent
  160. // out forever after a disconnection.
  161. if (!admin->currentRequest) {
  162. struct Sockaddr* addrPtr = (struct Sockaddr*) &addr.addr;
  163. int index = Map_LastMessageTimeByAddr_indexForKey(&addrPtr, &admin->map);
  164. uint64_t now = Time_currentTimeMilliseconds(admin->eventBase);
  165. if (index < 0 || checkAddress(admin, index, now)) {
  166. return Admin_sendMessage_CHANNEL_CLOSED;
  167. }
  168. }
  169. struct Allocator* alloc = Allocator_child(admin->allocator);
  170. // Bounce back the user-supplied txid.
  171. String* userTxid =
  172. String_newBinary(&txid->bytes[admin->addrLen], txid->len - admin->addrLen, alloc);
  173. if (txid->len > admin->addrLen) {
  174. Dict_putString(message, TXID, userTxid, alloc);
  175. }
  176. sendBenc(message, &addr.addr, alloc, admin);
  177. Dict_remove(message, TXID);
  178. Allocator_free(alloc);
  179. return 0;
  180. }
  181. static inline bool authValid(Dict* message, struct Message* messageBytes, struct Admin_pvt* admin)
  182. {
  183. String* cookieStr = Dict_getStringC(message, "cookie");
  184. uint32_t cookie = (cookieStr != NULL) ? strtoll(cookieStr->bytes, NULL, 10) : 0;
  185. if (!cookie) {
  186. int64_t* cookieInt = Dict_getIntC(message, "cookie");
  187. cookie = (cookieInt) ? *cookieInt : 0;
  188. }
  189. uint64_t nowSecs = Time_currentTimeSeconds(admin->eventBase);
  190. String* submittedHash = Dict_getStringC(message, "hash");
  191. if (cookie > nowSecs || cookie < nowSecs - 20 || !submittedHash || submittedHash->len != 64) {
  192. return false;
  193. }
  194. uint8_t* hashPtr = CString_strstr(messageBytes->bytes, submittedHash->bytes);
  195. if (!hashPtr || !admin->password) {
  196. return false;
  197. }
  198. uint8_t passAndCookie[64];
  199. snprintf((char*) passAndCookie, 64, "%s%u", admin->password->bytes, cookie);
  200. uint8_t hash[32];
  201. crypto_hash_sha256(hash, passAndCookie, CString_strlen((char*) passAndCookie));
  202. Hex_encode(hashPtr, 64, hash, 32);
  203. crypto_hash_sha256(hash, messageBytes->bytes, messageBytes->length);
  204. Hex_encode(hashPtr, 64, hash, 32);
  205. int res = crypto_verify_32(hashPtr, submittedHash->bytes);
  206. res |= crypto_verify_32(hashPtr + 32, submittedHash->bytes + 32);
  207. return res == 0;
  208. }
  209. static bool checkArgs(Dict* args,
  210. struct Function* func,
  211. String* txid,
  212. struct Allocator* requestAlloc,
  213. struct Admin_pvt* admin)
  214. {
  215. struct Dict_Entry* entry = *func->args;
  216. String* error = NULL;
  217. while (entry != NULL) {
  218. String* key = (String*) entry->key;
  219. Assert_ifParanoid(entry->val->type == Object_DICT);
  220. Dict* value = entry->val->as.dictionary;
  221. entry = entry->next;
  222. if (*Dict_getIntC(value, "required") == 0) {
  223. continue;
  224. }
  225. String* type = Dict_getStringC(value, "type");
  226. if ((type == STRING && !Dict_getString(args, key))
  227. || (type == DICT && !Dict_getDict(args, key))
  228. || (type == INTEGER && !Dict_getInt(args, key))
  229. || (type == LIST && !Dict_getList(args, key)))
  230. {
  231. error = String_printf(requestAlloc,
  232. "Entry [%s] is required and must be of type [%s]",
  233. key->bytes,
  234. type->bytes);
  235. break;
  236. }
  237. }
  238. if (error) {
  239. Dict d = Dict_CONST(String_CONST("error"), String_OBJ(error), NULL);
  240. Admin_sendMessage(&d, txid, &admin->pub);
  241. }
  242. return !error;
  243. }
  244. static void asyncEnabled(Dict* args, void* vAdmin, String* txid, struct Allocator* requestAlloc)
  245. {
  246. struct Admin_pvt* admin = Identity_check((struct Admin_pvt*) vAdmin);
  247. int64_t enabled = admin->asyncEnabled;
  248. Dict d = Dict_CONST(String_CONST("asyncEnabled"), Int_OBJ(enabled), NULL);
  249. Admin_sendMessage(&d, txid, &admin->pub);
  250. }
  251. #define ENTRIES_PER_PAGE 8
  252. static void availableFunctions(Dict* args, void* vAdmin, String* txid, struct Allocator* tempAlloc)
  253. {
  254. struct Admin_pvt* admin = Identity_check((struct Admin_pvt*) vAdmin);
  255. int64_t* page = Dict_getIntC(args, "page");
  256. uint32_t i = (page) ? *page * ENTRIES_PER_PAGE : 0;
  257. Dict* d = Dict_new(tempAlloc);
  258. Dict* functions = Dict_new(tempAlloc);
  259. int count = 0;
  260. for (; i < (uint32_t)admin->functionCount && count++ < ENTRIES_PER_PAGE; i++) {
  261. Dict_putDict(functions, admin->functions[i].name, admin->functions[i].args, tempAlloc);
  262. }
  263. if (count >= ENTRIES_PER_PAGE) {
  264. Dict_putIntC(d, "more", 1, tempAlloc);
  265. }
  266. Dict_putDictC(d, "availableFunctions", functions, tempAlloc);
  267. Admin_sendMessage(d, txid, &admin->pub);
  268. }
  269. static void handleRequest(Dict* messageDict,
  270. struct Message* message,
  271. struct Sockaddr* src,
  272. struct Allocator* allocator,
  273. struct Admin_pvt* admin)
  274. {
  275. String* query = Dict_getStringC(messageDict, "q");
  276. if (!query) {
  277. Log_info(admin->logger, "Got a non-query from admin interface");
  278. return;
  279. }
  280. // txid becomes the user supplied txid combined with the channel num.
  281. String* userTxid = Dict_getString(messageDict, TXID);
  282. uint32_t txidlen = ((userTxid) ? userTxid->len : 0) + src->addrLen;
  283. String* txid = String_newBinary(NULL, txidlen, allocator);
  284. Bits_memcpy(txid->bytes, src, src->addrLen);
  285. if (userTxid) {
  286. Bits_memcpy(txid->bytes + src->addrLen, userTxid->bytes, userTxid->len);
  287. }
  288. // If they're asking for a cookie then lets give them one.
  289. String* cookie = String_CONST("cookie");
  290. if (String_equals(query, cookie)) {
  291. //Log_debug(admin->logger, "Got a request for a cookie");
  292. Dict* d = Dict_new(allocator);
  293. char bytes[32];
  294. snprintf(bytes, 32, "%u", (uint32_t) Time_currentTimeSeconds(admin->eventBase));
  295. String* theCookie = &(String) { .len = CString_strlen(bytes), .bytes = bytes };
  296. Dict_putString(d, cookie, theCookie, allocator);
  297. Admin_sendMessage(d, txid, &admin->pub);
  298. return;
  299. }
  300. // If this is a permitted query, make sure the cookie is right.
  301. String* auth = String_CONST("auth");
  302. bool authed = false;
  303. if (String_equals(query, auth)) {
  304. if (!authValid(messageDict, message, admin)) {
  305. Dict* d = Dict_new(allocator);
  306. Dict_putStringCC(d, "error", "Auth failed.", allocator);
  307. Admin_sendMessage(d, txid, &admin->pub);
  308. return;
  309. }
  310. query = Dict_getStringC(messageDict, "aq");
  311. authed = true;
  312. }
  313. // Then sent a valid authed query, lets track their address so they can receive
  314. // asynchronous messages.
  315. int index = Map_LastMessageTimeByAddr_indexForKey(&src, &admin->map);
  316. uint64_t now = Time_currentTimeMilliseconds(admin->eventBase);
  317. admin->asyncEnabled = 1;
  318. if (index >= 0) {
  319. admin->map.values[index]->timeOfLastMessage = now;
  320. } else if (authed) {
  321. struct Allocator* entryAlloc = Allocator_child(admin->allocator);
  322. struct MapValue* mv = Allocator_calloc(entryAlloc, sizeof(struct MapValue), 1);
  323. mv->timeOfLastMessage = now;
  324. mv->allocator = entryAlloc;
  325. struct Sockaddr* storedAddr = Sockaddr_clone(src, entryAlloc);
  326. Map_LastMessageTimeByAddr_put(&storedAddr, &mv, &admin->map);
  327. } else {
  328. admin->asyncEnabled = 0;
  329. }
  330. Dict* args = Dict_getDictC(messageDict, "args");
  331. bool noFunctionsCalled = true;
  332. for (int i = 0; i < admin->functionCount; i++) {
  333. if (String_equals(query, admin->functions[i].name)
  334. && (authed || !admin->functions[i].needsAuth))
  335. {
  336. if (checkArgs(args, &admin->functions[i], txid, message->alloc, admin)) {
  337. admin->functions[i].call(args, admin->functions[i].context, txid, message->alloc);
  338. }
  339. noFunctionsCalled = false;
  340. }
  341. }
  342. if (noFunctionsCalled) {
  343. Dict d = Dict_CONST(
  344. String_CONST("error"),
  345. String_OBJ(String_CONST("No functions matched your request, "
  346. "try Admin_availableFunctions()")),
  347. NULL
  348. );
  349. Admin_sendMessage(&d, txid, &admin->pub);
  350. }
  351. return;
  352. }
  353. static void handleMessage(struct Message* message,
  354. struct Sockaddr* src,
  355. struct Allocator* alloc,
  356. struct Admin_pvt* admin)
  357. {
  358. if (Defined(Log_KEYS)) {
  359. uint8_t lastChar = message->bytes[message->length - 1];
  360. message->bytes[message->length - 1] = '\0';
  361. Log_keys(admin->logger, "Got message from [%s] [%s]",
  362. Sockaddr_print(src, alloc), message->bytes);
  363. message->bytes[message->length - 1] = lastChar;
  364. }
  365. // handle non empty message data
  366. if (message->length > Admin_MAX_REQUEST_SIZE) {
  367. #define TOO_BIG "d5:error16:Request too big.e"
  368. #define TOO_BIG_STRLEN (sizeof(TOO_BIG) - 1)
  369. Bits_memcpy(message->bytes, TOO_BIG, TOO_BIG_STRLEN);
  370. message->length = TOO_BIG_STRLEN;
  371. sendMessage(message, src, admin);
  372. return;
  373. }
  374. int origMessageLen = message->length;
  375. Dict* messageDict = NULL;
  376. char* err = BencMessageReader_readNoExcept(message, alloc, &messageDict);
  377. if (err) {
  378. Log_warn(admin->logger,
  379. "Unparsable data from [%s] content: [%s] error: [%s]",
  380. Sockaddr_print(src, alloc), message->bytes, err);
  381. return;
  382. }
  383. if (message->length) {
  384. Log_warn(admin->logger,
  385. "Message from [%s] contained garbage after byte [%d] content: [%s]",
  386. Sockaddr_print(src, alloc), message->length, message->bytes);
  387. return;
  388. }
  389. // put the data back in the front of the message because it is used by the auth checker.
  390. Message_shift(message, origMessageLen, NULL);
  391. handleRequest(messageDict, message, src, alloc, admin);
  392. }
  393. static Iface_DEFUN receiveMessage(struct Message* message, struct Iface* iface)
  394. {
  395. struct Admin_pvt* admin = Identity_containerOf(iface, struct Admin_pvt, iface);
  396. struct AddrIface_Header aihdr;
  397. Message_pop(message, &aihdr, AddrIface_Header_SIZE, NULL);
  398. Assert_true(aihdr.addr.addr.addrLen == admin->addrLen);
  399. struct Allocator* alloc = Allocator_child(admin->allocator);
  400. admin->currentRequest = message;
  401. handleMessage(message, &aihdr.addr.addr, alloc, admin);
  402. admin->currentRequest = NULL;
  403. Allocator_free(alloc);
  404. return NULL;
  405. }
  406. void Admin_registerFunctionWithArgCount(char* name,
  407. Admin_Function callback,
  408. void* callbackContext,
  409. bool needsAuth,
  410. struct Admin_FunctionArg* arguments,
  411. int argCount,
  412. struct Admin* adminPub)
  413. {
  414. struct Admin_pvt* admin = Identity_check((struct Admin_pvt*) adminPub);
  415. String* str = String_new(name, admin->allocator);
  416. admin->functions =
  417. Allocator_realloc(admin->allocator,
  418. admin->functions,
  419. sizeof(struct Function) * (admin->functionCount + 1));
  420. struct Function* fu = &admin->functions[admin->functionCount];
  421. admin->functionCount++;
  422. fu->name = str;
  423. fu->call = callback;
  424. fu->context = callbackContext;
  425. fu->needsAuth = needsAuth;
  426. fu->args = Dict_new(admin->allocator);
  427. for (int i = 0; arguments && i < argCount; i++) {
  428. // "type" must be one of: [ "String", "Int", "Dict", "List" ]
  429. String* type = NULL;
  430. if (!CString_strcmp(arguments[i].type, STRING->bytes)) {
  431. type = STRING;
  432. } else if (!CString_strcmp(arguments[i].type, INTEGER->bytes)) {
  433. type = INTEGER;
  434. } else if (!CString_strcmp(arguments[i].type, DICT->bytes)) {
  435. type = DICT;
  436. } else if (!CString_strcmp(arguments[i].type, LIST->bytes)) {
  437. type = LIST;
  438. } else {
  439. abort();
  440. }
  441. Dict* arg = Dict_new(admin->allocator);
  442. Dict_putString(arg, TYPE, type, admin->allocator);
  443. Dict_putInt(arg, REQUIRED, arguments[i].required, admin->allocator);
  444. String* name = String_new(arguments[i].name, admin->allocator);
  445. Dict_putDict(fu->args, name, arg, admin->allocator);
  446. }
  447. }
  448. struct Admin* Admin_new(struct AddrIface* ai,
  449. struct Log* logger,
  450. struct EventBase* eventBase,
  451. String* password)
  452. {
  453. struct Allocator* alloc = ai->alloc;
  454. struct Admin_pvt* admin = Allocator_calloc(alloc, sizeof(struct Admin_pvt), 1);
  455. Identity_set(admin);
  456. admin->allocator = alloc;
  457. admin->logger = logger;
  458. admin->eventBase = eventBase;
  459. admin->addrLen = ai->addr->addrLen;
  460. admin->map.allocator = alloc;
  461. admin->iface.send = receiveMessage;
  462. Iface_plumb(&admin->iface, &ai->iface);
  463. admin->tempSendMsg = Message_new(0, Admin_MAX_RESPONSE_SIZE, alloc);
  464. admin->password = String_clone(password, alloc);
  465. Timeout_setInterval(clearExpiredAddresses, admin, TIMEOUT_MILLISECONDS * 3, eventBase, alloc);
  466. Admin_registerFunction("Admin_asyncEnabled", asyncEnabled, admin, false, NULL, &admin->pub);
  467. Admin_registerFunction("Admin_availableFunctions", availableFunctions, admin, false,
  468. ((struct Admin_FunctionArg[]) {
  469. { .name = "page", .required = 0, .type = "Int" }
  470. }), &admin->pub);
  471. return &admin->pub;
  472. }