shell.cc 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990
  1. /*
  2. * Copyright (C) 1997 Robey Pointer
  3. * Copyright (C) 1999 - 2002 Eggheads Development Team
  4. * Copyright (C) 2002 - 2014 Bryan Drewery
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU General Public License
  8. * as published by the Free Software Foundation; either version 2
  9. * of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; if not, write to the Free Software
  18. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  19. */
  20. /*
  21. * shell.c -- handles:
  22. *
  23. * All shell related functions
  24. * -shell_exec()
  25. * -botconfig parsing
  26. * -check_*()
  27. * -crontab functions
  28. *
  29. */
  30. #include "common.h"
  31. #include "shell.h"
  32. #include "chanprog.h"
  33. #include "set.h"
  34. #include "settings.h"
  35. #include "userrec.h"
  36. #include "net.h"
  37. #include "flags.h"
  38. #include "tandem.h"
  39. #include "main.h"
  40. #include "dccutil.h"
  41. #include "misc.h"
  42. #include "misc_file.h"
  43. #include "bg.h"
  44. #include "stat.h"
  45. #include "users.h"
  46. #include "botnet.h"
  47. #include "src/mod/server.mod/server.h"
  48. #include <bdlib/src/String.h>
  49. #include <bdlib/src/Stream.h>
  50. #include <sys/types.h>
  51. #include <pwd.h>
  52. #include <signal.h>
  53. #ifdef HAVE_SYS_PRCTL_H
  54. #include <sys/prctl.h>
  55. #ifndef PR_SET_PTRACER
  56. #define PR_SET_PTRACER 0x59616d61
  57. #endif
  58. #endif
  59. #ifdef HAVE_SYS_PROCCTL_H
  60. #include <sys/procctl.h>
  61. #ifndef PROC_TRACE_CTL
  62. #define PROC_TRACE_CTL 7
  63. #endif
  64. #ifndef PROC_TRACE_STATUS
  65. #define PROC_TRACE_STATUS 8
  66. #endif
  67. #ifndef PROC_TRACE_CTL_DISABLE
  68. #define PROC_TRACE_CTL_DISABLE 2
  69. #endif
  70. #endif /* HAVE_SYS_PROCCTL_H */
  71. #ifdef HAVE_SYS_PTRACE_H
  72. # include <sys/ptrace.h>
  73. #endif /* HAVE_SYS_PTRACE_H */
  74. #include <sys/wait.h>
  75. #include <sys/utsname.h>
  76. #include <pwd.h>
  77. #include <errno.h>
  78. #include <net/if.h>
  79. #include <sys/ioctl.h>
  80. #include <sys/socket.h>
  81. #include <ctype.h>
  82. #include <fcntl.h>
  83. #include <sys/stat.h>
  84. #include <unistd.h>
  85. #include <dirent.h>
  86. #include "botmsg.h"
  87. bool clear_tmpdir = 0;
  88. void clear_tmp()
  89. {
  90. if (!clear_tmpdir)
  91. return;
  92. DIR *tmp = NULL;
  93. if (!(tmp = opendir(tempdir)))
  94. return;
  95. struct dirent *dir_ent = NULL;
  96. char *file = NULL;
  97. size_t flen = 0;
  98. while ((dir_ent = readdir(tmp))) {
  99. if (strncmp(dir_ent->d_name, ".pid.", 4) &&
  100. strncmp(dir_ent->d_name, ".u", 2) &&
  101. strcmp(dir_ent->d_name, ".bin.old") &&
  102. strncmp(dir_ent->d_name, STR(".socks-"), 7) &&
  103. strcmp(dir_ent->d_name, ".") &&
  104. strcmp(dir_ent->d_name, "..")) {
  105. flen = strlen(dir_ent->d_name) + strlen(tempdir) + 1;
  106. file = (char *) my_calloc(1, flen);
  107. strlcat(file, tempdir, flen);
  108. strlcat(file, dir_ent->d_name, flen);
  109. file[strlen(file)] = 0;
  110. sdprintf("clear_tmp: %s", file);
  111. unlink(file);
  112. free(file);
  113. }
  114. }
  115. closedir(tmp);
  116. return;
  117. }
  118. void check_maxfiles()
  119. {
  120. int sock = -1, sock1 = -1 , bogus = 0, failed_close = 0;
  121. #ifdef USE_IPV6
  122. sock1 = getsock(0, AF_INET); /* fill up any lower avail */
  123. sock = getsock(0, AF_INET);
  124. #else
  125. sock1 = getsock(0);
  126. sock = getsock(0);
  127. #endif
  128. if (sock1 != -1)
  129. killsock(sock1);
  130. if (sock == -1) {
  131. return;
  132. } else
  133. killsock(sock);
  134. bogus = sock - socks_total - 4; //4 for stdin/stdout/stderr/dns
  135. if (unlikely(bogus >= 50)) { /* Attempt to close them */
  136. sdprintf("SOCK: %d BOGUS: %d SOCKS_TOTAL: %d", sock, bogus, socks_total);
  137. for (int i = 10; i < sock; i++) /* dont close lower sockets, they're probably legit */
  138. if (!findanysnum(i)) {
  139. if ((close(i)) == -1) /* try to close the BOGUS fd (likely a KQUEUE) */
  140. failed_close++;
  141. else
  142. bogus--;
  143. }
  144. if (bogus >= 150 || failed_close >= 50) {
  145. if (tands > 0) {
  146. botnet_send_chat(-1, conf.bot->nick, "Max FD reached, restarting...");
  147. botnet_send_bye("Max FD reached, restarting...");
  148. }
  149. nuke_server("brb");
  150. cycle_time = 0;
  151. restart(-1);
  152. } else if (bogus >= 100 && (bogus % 10) == 0) {
  153. putlog(LOG_WARN, "*", "* WARNING: $b%d$b bogus file descriptors detected, auto restart at 150", bogus);
  154. }
  155. }
  156. }
  157. void check_mypid()
  158. {
  159. pid_t pid = 0;
  160. if (can_stat(conf.bot->pid_file))
  161. pid = checkpid(conf.bot->nick, NULL);
  162. if (pid && (pid != getpid()))
  163. fatal(STR("getpid() does not match pid in file. Possible cloned process, exiting.."), 0);
  164. }
  165. char last_buf[128] = "";
  166. void check_last() {
  167. if (login == DET_IGNORE)
  168. return;
  169. if (conf.username) {
  170. char *out = NULL, buf[50] = "";
  171. simple_snprintf(buf, sizeof(buf), STR("last -10 %s"), conf.username);
  172. if (shell_exec(buf, NULL, &out, NULL, 1)) {
  173. if (out) {
  174. char *p = NULL;
  175. p = strchr(out, '\n');
  176. if (p)
  177. *p = 0;
  178. if (strlen(out) > 10) {
  179. if (last_buf[0]) {
  180. if (strncmp(last_buf, out, sizeof(last_buf))) {
  181. char *work = NULL;
  182. size_t siz = strlen(out) + 7 + 2 + 1;
  183. work = (char *) my_calloc(1, siz);
  184. simple_snprintf(work, siz, STR("Login: %s"), out);
  185. detected(DETECT_LOGIN, work);
  186. free(work);
  187. }
  188. }
  189. strlcpy(last_buf, out, sizeof(last_buf));
  190. }
  191. free(out);
  192. }
  193. }
  194. }
  195. }
  196. void check_promisc()
  197. {
  198. #ifdef SIOCGIFCONF
  199. if (promisc == DET_IGNORE)
  200. return;
  201. int sock = socket(AF_INET, SOCK_DGRAM, 0);
  202. if (sock < 0)
  203. return;
  204. struct ifconf ifcnf;
  205. char buf[1024] = "";
  206. ifcnf.ifc_len = sizeof(buf);
  207. ifcnf.ifc_buf = buf;
  208. if (ioctl(sock, SIOCGIFCONF, &ifcnf) < 0) {
  209. close(sock);
  210. return;
  211. }
  212. char *reqp = NULL, *end_req = NULL;
  213. reqp = buf; /* pointer to start of array */
  214. end_req = buf + ifcnf.ifc_len; /* pointer to end of array */
  215. while (reqp < end_req) {
  216. struct ifreq ifreq, *ifr = NULL;
  217. ifr = reinterpret_cast<struct ifreq *>(reqp); /* start examining interface */
  218. ifreq = *ifr;
  219. if (!ioctl(sock, SIOCGIFFLAGS, &ifreq)) { /* we can read this interface! */
  220. /* sdprintf("Examing interface: %s", ifr->ifr_name); */
  221. if (unlikely(ifreq.ifr_flags & IFF_PROMISC) && strncmp(ifr->ifr_name, "pflog", 5) && strncmp(ifr->ifr_name, "ipfw", 4)) {
  222. char which[101] = "";
  223. simple_snprintf(which, sizeof(which), STR("Detected promiscuous mode on interface: %s"), ifr->ifr_name);
  224. ioctl(sock, SIOCSIFFLAGS, &ifreq); /* set flags */
  225. detected(DETECT_PROMISC, which);
  226. break;
  227. }
  228. }
  229. /* move pointer to next array element (next interface) */
  230. reqp += sizeof(ifr->ifr_name) + sizeof(ifr->ifr_addr);
  231. }
  232. close(sock);
  233. #endif /* SIOCGIFCONF */
  234. }
  235. #ifndef DEBUG
  236. bool traced = 0;
  237. static void got_sigtrap(int z)
  238. {
  239. traced = 0;
  240. }
  241. #endif
  242. void check_trace(int start)
  243. {
  244. #ifdef DEBUG
  245. #ifdef PR_SET_PTRACER_ANY
  246. if (start == 1)
  247. prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0);
  248. #endif
  249. return;
  250. #else
  251. #if defined(HAVE_PROCCTL) && defined(PROC_TRACE_CTL)
  252. int status = 0;
  253. #endif
  254. if (start == 0 && trace == DET_IGNORE)
  255. return;
  256. pid_t parent = getpid();
  257. #if defined(HAVE_PROCCTL) && defined(PROC_TRACE_CTL)
  258. /* FreeBSD let's us know if we're being traced already. */
  259. if (procctl(P_PID, parent, PROC_TRACE_STATUS, &status) == 0 &&
  260. status > 0) {
  261. /* status contains the pid of the tracer. Be mean. */
  262. kill(status, SIGSEGV);
  263. traced = 1;
  264. }
  265. #endif
  266. if (!traced) {
  267. /* we send ourselves a SIGTRAP, if we recieve, we're not being traced,
  268. * otherwise we might be. The debugger may smartly just forward the
  269. * signal if it knows it didn't request it, such as FreeBSD truss
  270. * after r288903. */
  271. signal(SIGTRAP, got_sigtrap);
  272. traced = 1;
  273. raise(SIGTRAP);
  274. signal(SIGTRAP, SIG_DFL);
  275. }
  276. if (!traced) {
  277. signal(SIGINT, got_sigtrap);
  278. traced = 1;
  279. raise(SIGINT);
  280. signal(SIGINT, got_int);
  281. }
  282. if (traced) {
  283. if (start) {
  284. kill(parent, SIGKILL);
  285. exit(1);
  286. } else
  287. detected(DETECT_TRACE, STR("I'm being traced!"));
  288. } else {
  289. if (!start)
  290. return;
  291. int tracing_safe = 0;
  292. #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE) && defined(PR_GET_DUMPABLE)
  293. /* Try to disable ptrace and core dumping entirely. */
  294. if (prctl(PR_GET_DUMPABLE) == 0 ||
  295. (prctl(PR_SET_DUMPABLE, 0) == 0 && prctl(PR_GET_DUMPABLE) == 0)) {
  296. tracing_safe = 1;
  297. }
  298. #elif defined(HAVE_PROCCTL) && defined(PROC_TRACE_CTL)
  299. if ((procctl(P_PID, parent, PROC_TRACE_STATUS, &status) == 0 &&
  300. status == -1) ||
  301. (status = PROC_TRACE_CTL_DISABLE,
  302. procctl(P_PID, parent, PROC_TRACE_CTL, &status) == 0)) {
  303. tracing_safe = 1;
  304. }
  305. #endif
  306. if (tracing_safe) {
  307. /* We're safe! Don't bother with further checks. */
  308. putlog(LOG_DEBUG, "*", "Ptrace disabled, no longer checking.");
  309. trace = DET_IGNORE;
  310. return;
  311. }
  312. #ifndef __sun__
  313. int x, i, filedes[2];
  314. if (pipe(filedes) != 0) {
  315. /* Could be a temporary failure, don't be harsh. */
  316. return;
  317. }
  318. /* now, let's attempt to ptrace ourself */
  319. switch ((x = fork())) {
  320. case -1:
  321. return;
  322. case 0: //child
  323. char buf[1];
  324. while (read(filedes[0], buf, sizeof(buf)) != 1)
  325. ;
  326. i = ptrace(PT_ATTACH, parent, 0, 0);
  327. if (i == -1 &&
  328. /* Linux compat or otherwise removed syscall. Just ignore. */
  329. errno != ENOSYS &&
  330. /* EPERM is given on fbsd when security.bsd.unprivileged_proc_debug=0 */
  331. #ifdef __FreeBSD__
  332. errno != EPERM &&
  333. #endif
  334. errno != EINVAL) {
  335. if (start) {
  336. kill(parent, SIGKILL);
  337. exit(1);
  338. } else
  339. detected(DETECT_TRACE, STR("I'm being traced!"));
  340. } else if (i == 0) {
  341. waitpid(parent, NULL, 0);
  342. ptrace(PT_DETACH, parent, (char *) 1, 0);
  343. }
  344. exit(0);
  345. default: //parent
  346. #ifdef PR_SET_PTRACER
  347. // Allow the child to debug the parent on Linux 3.4+
  348. // https://github.com/torvalds/linux/commit/2d514487faf188938a4ee4fb3464eeecfbdcf8eb
  349. prctl(PR_SET_PTRACER, x, 0, 0, 0);
  350. #endif
  351. /* Not likely to happen, but make debian FORTIFY_SOURCE happy. */
  352. if (write(filedes[1], "+", 1) != 1) {
  353. kill(x, SIGKILL);
  354. }
  355. waitpid(x, NULL, 0);
  356. close(filedes[0]);
  357. close(filedes[1]);
  358. }
  359. #endif
  360. }
  361. #endif /* !DEBUG */
  362. }
  363. int shell_exec(char *cmdline, char *input, char **output, char **erroutput, bool simple)
  364. {
  365. if (!cmdline)
  366. return 0;
  367. Tempfile *in = NULL, *out = NULL, *err = NULL;
  368. int x;
  369. /* Set up temp files */
  370. in = new Tempfile("in");
  371. if (!in || in->error) {
  372. // putlog(LOG_ERRORS, "*" , "exec: Couldn't open '%s': %s", in->file, strerror(errno));
  373. delete in;
  374. return 0;
  375. }
  376. if (input) {
  377. if (fwrite(input, strlen(input), 1, in->f) != 1) {
  378. // putlog(LOG_ERRORS, "*", "exec: Couldn't write to '%s': %s", in->file, strerror(errno));
  379. delete in;
  380. return 0;
  381. }
  382. fseek(in->f, 0, SEEK_SET);
  383. }
  384. err = new Tempfile("err");
  385. if (!err || err->error) {
  386. // putlog(LOG_ERRORS, "*", "exec: Couldn't open '%s': %s", err->file, strerror(errno));
  387. delete in;
  388. delete err;
  389. return 0;
  390. }
  391. out = new Tempfile("out");
  392. if (!out || out->error) {
  393. // putlog(LOG_ERRORS, "*", "exec: Couldn't open '%s': %s", out->file, strerror(errno));
  394. delete in;
  395. delete err;
  396. delete out;
  397. return 0;
  398. }
  399. x = fork();
  400. if (x == -1) {
  401. putlog(LOG_ERRORS, "*", "exec: fork() failed: %s", strerror(errno));
  402. delete in;
  403. delete err;
  404. delete out;
  405. return 0;
  406. }
  407. if (x) { /* Parent: wait for the child to complete */
  408. int st = 0;
  409. size_t fs = 0;
  410. #ifdef PR_SET_PTRACER
  411. // Allow the child to debug the parent on Linux 3.4+
  412. // https://github.com/torvalds/linux/commit/2d514487faf188938a4ee4fb3464eeecfbdcf8eb
  413. prctl(PR_SET_PTRACER, x, 0, 0, 0);
  414. #endif
  415. waitpid(x, &st, 0);
  416. /* child is now complete, read the files into buffers */
  417. delete in;
  418. fflush(out->f);
  419. fflush(err->f);
  420. if (erroutput) {
  421. char *buf = NULL;
  422. fseek(err->f, 0, SEEK_END);
  423. fs = ftell(err->f);
  424. if (fs == 0) {
  425. (*erroutput) = NULL;
  426. } else {
  427. buf = (char *) my_calloc(1, fs + 1);
  428. fseek(err->f, 0, SEEK_SET);
  429. if (!fread(buf, 1, fs, err->f))
  430. fs = 0;
  431. buf[fs] = 0;
  432. (*erroutput) = buf;
  433. }
  434. }
  435. delete err;
  436. if (output) {
  437. char *buf = NULL;
  438. fseek(out->f, 0, SEEK_END);
  439. fs = ftell(out->f);
  440. if (fs == 0) {
  441. (*output) = NULL;
  442. } else {
  443. buf = (char *) my_calloc(1, fs + 1);
  444. fseek(out->f, 0, SEEK_SET);
  445. if (!fread(buf, 1, fs, out->f))
  446. fs = 0;
  447. buf[fs] = 0;
  448. (*output) = buf;
  449. }
  450. }
  451. delete out;
  452. return 1;
  453. } else {
  454. /* Child: make fd's and set them up as std* */
  455. // int ind, outd, errd;
  456. // ind = fileno(inpFile);
  457. // outd = fileno(outFile);
  458. // errd = fileno(errFile);
  459. if (dup2(in->fd, STDIN_FILENO) == (-1)) {
  460. exit(1);
  461. }
  462. if (dup2(out->fd, STDOUT_FILENO) == (-1)) {
  463. exit(1);
  464. }
  465. if (dup2(err->fd, STDERR_FILENO) == (-1)) {
  466. exit(1);
  467. }
  468. // Close all sockets
  469. for (int fd = 3; fd < MAX_SOCKETS; ++fd) close(fd);
  470. char *argv[15];
  471. if (simple) {
  472. char *p = NULL;
  473. int n = 0;
  474. char *mycmdline = strdup(cmdline);
  475. while (mycmdline[0] && (p = newsplit(&mycmdline)))
  476. argv[n++] = p;
  477. argv[n] = NULL;
  478. } else {
  479. argv[0] = "/bin/sh";
  480. argv[1] = "-c";
  481. argv[2] = cmdline;
  482. argv[3] = NULL;
  483. }
  484. execvp(argv[0], &argv[0]);
  485. exit(1);
  486. }
  487. }
  488. int simple_exec(const char* argv[]) {
  489. pid_t pid, savedpid;
  490. int status;
  491. switch ((pid = fork())) {
  492. case -1:
  493. break;
  494. case 0: //child
  495. // Close all sockets
  496. for (int fd = 3; fd < MAX_SOCKETS; ++fd) close(fd);
  497. execvp(argv[0], (char* const*) &argv[0]);
  498. _exit(127);
  499. default: //parent
  500. savedpid = pid;
  501. do {
  502. pid = wait4(savedpid, &status, 0, (struct rusage *)0);
  503. } while (pid == -1 && errno == EINTR);
  504. break;
  505. }
  506. return(pid == -1 ? -1 : status);
  507. }
  508. void suicide(const char *msg)
  509. {
  510. char tmp[512] = "";
  511. if (!conf.bot->localhub) {
  512. //im not a localhub, ask the localhub to suicide
  513. simple_snprintf(tmp, sizeof(tmp), STR("suicide %s"), msg);
  514. putbot(conf.localhub, tmp);
  515. return;
  516. } else {
  517. //im the localhub, loop thru bots and kill 'em
  518. putlog(LOG_WARN, "*", STR("Comitting suicide: %s"), msg);
  519. crontab_del();
  520. conf_bot *bot = NULL;
  521. for (bot = conf.bots; bot && bot->nick; bot = bot->next) {
  522. if (!strcmp(conf.bot->nick, bot->nick))
  523. continue; //skip myself or i wont be able to remove the rest
  524. bot->pid = checkpid(bot->nick, bot);
  525. conf_killbot(conf.bots, NULL, bot, SIGKILL);
  526. unlink(bot->pid_file);
  527. deluser(bot->nick);
  528. }
  529. }
  530. if (!conf.bot->hub) {
  531. nuke_server(STR("kill the infidels!"));
  532. sleep(1);
  533. } else {
  534. unlink(userfile);
  535. simple_snprintf(tmp, sizeof(tmp), STR("%s~new"), userfile);
  536. unlink(tmp);
  537. simple_snprintf(tmp, sizeof(tmp), STR("%s~"), userfile);
  538. unlink(tmp);
  539. simple_snprintf(tmp, sizeof(tmp), STR("%s/%s~"), conf.datadir, userfile);
  540. unlink(tmp);
  541. simple_snprintf(tmp, sizeof(tmp), STR("%s/.u.0"), conf.datadir);
  542. unlink(tmp);
  543. simple_snprintf(tmp, sizeof(tmp), STR("%s/.u.1"), conf.datadir);
  544. unlink(tmp);
  545. }
  546. unlink(binname);
  547. //Not recursively clearing these dirs as they may be ~USER/ ..
  548. unlink(conf.datadir); //Probably will fail, shrug
  549. unlink(tempdir); //Probably will fail too, oh well
  550. //now deal with myself after the rest of the conf.bots are gone
  551. deluser(conf.bot->nick);
  552. unlink(conf.bot->pid_file);
  553. //and die in agony!
  554. fatal(msg, 0);
  555. }
  556. void detected(int code, const char *msg)
  557. {
  558. char tmp[512] = "";
  559. struct flag_record fr = { FR_GLOBAL, 0, 0, 0 };
  560. int act = DET_WARN, do_fatal = 0, killbots = 0;
  561. if (code == DETECT_LOGIN)
  562. act = login;
  563. if (code == DETECT_TRACE)
  564. act = trace;
  565. if (code == DETECT_PROMISC)
  566. act = promisc;
  567. if (code == DETECT_HIJACK)
  568. act = hijack;
  569. switch (act) {
  570. case DET_IGNORE:
  571. break;
  572. case DET_WARN:
  573. putlog(LOG_WARN, "*", "%s", msg);
  574. break;
  575. case DET_REJECT:
  576. do_fork();
  577. putlog(LOG_WARN, "*", STR("Setting myself +d: %s"), msg);
  578. simple_snprintf(tmp, sizeof(tmp), "+d: %s", msg);
  579. set_user(&USERENTRY_COMMENT, conf.bot->u, tmp);
  580. fr.global = USER_DEOP;
  581. fr.bot = 1;
  582. set_user_flagrec(conf.bot->u, &fr, 0);
  583. sleep(1);
  584. break;
  585. case DET_DIE:
  586. putlog(LOG_WARN, "*", STR("Dying: %s"), msg);
  587. simple_snprintf(tmp, sizeof(tmp), STR("Dying: %s"), msg);
  588. set_user(&USERENTRY_COMMENT, conf.bot->u, tmp);
  589. if (!conf.bot->hub)
  590. nuke_server(STR("BBL"));
  591. sleep(1);
  592. killbots++;
  593. do_fatal++;
  594. break;
  595. case DET_SUICIDE:
  596. suicide(msg);
  597. break;
  598. }
  599. if (killbots && conf.bot->localhub) {
  600. conf_checkpids(conf.bots);
  601. conf_killbot(conf.bots, NULL, NULL, SIGKILL);
  602. }
  603. if (do_fatal)
  604. fatal(msg, 0);
  605. }
  606. const char *werr_tostr(int errnum)
  607. {
  608. switch (errnum) {
  609. case ERR_BINSTAT:
  610. return STR("Cannot access binary");
  611. case ERR_BADPASS:
  612. return STR("Incorrect password");
  613. case ERR_PASSWD:
  614. return STR("Cannot access the global passwd file");
  615. case ERR_WRONGBINDIR:
  616. return STR("Wrong directory/binary name");
  617. case ERR_DATADIR:
  618. return STR("Cannot access datadir.");
  619. case ERR_TMPSTAT:
  620. return STR("Cannot access tmp directory.");
  621. case ERR_TMPMOD:
  622. return STR("Cannot chmod() tmp directory.");
  623. case ERR_WRONGUID:
  624. return STR("UID in binary does not match geteuid()");
  625. case ERR_WRONGUNAME:
  626. return STR("Uname in binary does not match uname()");
  627. case ERR_BADCONF:
  628. return STR("Config file is incomplete");
  629. case ERR_BADBOT:
  630. return STR("No such botnick");
  631. case ERR_BOTDISABLED:
  632. return STR("Bot is disabled, remove '/' in config");
  633. case ERR_NOBOTS:
  634. return STR("There are no bots in the binary! Please use ./binary -C to edit");
  635. case ERR_NOHOMEDIR:
  636. return STR("There is no homedir set. Please set one in the binary config with ./binary -C");
  637. case ERR_NOUSERNAME:
  638. return STR("There is no username set. Please set one in the binary config with ./binary -C");
  639. case ERR_NOBOT:
  640. return STR("I have no bot record but received -B???");
  641. case ERR_NOTINIT:
  642. return STR("Binary data is not initialized; try ./binary -C");
  643. case ERR_TOOMANYBOTS:
  644. return STR("Too many bots defined. 5 max. Too many will lead to klines.\nSpread out into multiple accounts/shells/ip ranges.");
  645. case ERR_LIBS:
  646. return STR("Failed to load required libraries.\nEnsure that 32bit compat libs are installed, and openssl.\nLinux: ia32-libs\nFreeBSD: misc/compat8x");
  647. default:
  648. return STR("Unforseen error");
  649. }
  650. }
  651. void werr(int errnum)
  652. {
  653. /* [1]+ Done ls --color=auto -A -CF
  654. [1]+ Killed bash
  655. */
  656. /*
  657. int x = 0;
  658. unsigned long job = randint(2) + 1; */
  659. /* printf("[%lu] %lu%lu%lu%lu%lu\n", job, randint(2) + 1, randint(8) + 1, randint(8) + 1, errnum); */
  660. /* printf("\n[%lu]+ Killed rm -rf /\r\n", job); */
  661. /*
  662. if (checkedpass) {
  663. printf("[%lu] %d\n", job, getpid());
  664. }
  665. */
  666. /* printf("\n[%lu]+ Stopped %s\r\n", job, basename(binname)); */
  667. #ifdef OBSCURE_ERRORS
  668. sdprintf(STR("Error %d: %s"), errnum, werr_tostr(errnum));
  669. printf(STR("*** Error code %d\n\n"), errnum);
  670. printf(STR("Segmentation fault\n"));
  671. #else
  672. fprintf(stderr, STR("Error %d: %s\n"), errnum, werr_tostr(errnum));
  673. #endif
  674. fatal("", 0);
  675. exit(1); // This is never reached, done for gcc() warnings
  676. }
  677. char *homedir(bool useconf)
  678. {
  679. static char homedir_buf[PATH_MAX] = "";
  680. if (!homedir_buf[0]) {
  681. if (conf.homedir && useconf)
  682. simple_snprintf(homedir_buf, sizeof homedir_buf, "%s", conf.homedir);
  683. else {
  684. char *home = getenv("HOME");
  685. if (home && strlen(home))
  686. strlcpy(homedir_buf, home, sizeof(homedir_buf));
  687. }
  688. }
  689. return homedir_buf[0] ? homedir_buf : NULL;
  690. }
  691. char *my_username()
  692. {
  693. static char username[DIRMAX] = "";
  694. if (!username[0]) {
  695. char *user = getenv("USER");
  696. if (user && strlen(user))
  697. strlcpy(username, user, sizeof(username));
  698. }
  699. return username[0] ? username : NULL;
  700. }
  701. int mkdir_p(const char *dir) {
  702. char *p = NULL, *path = NULL;
  703. path = p = strdup(dir);
  704. do {
  705. p = strchr(p + 1, '/');
  706. if (p)
  707. *p = '\0';
  708. if (can_stat(path) && !is_dir(path))
  709. unlink(path);
  710. if (!can_stat(path)) {
  711. if (mkdir(path, S_IRUSR | S_IWUSR | S_IXUSR)) {
  712. unlink(path);
  713. mkdir(path, S_IRUSR | S_IWUSR | S_IXUSR);
  714. }
  715. }
  716. if (p)
  717. *p = '/';
  718. } while(p);
  719. int couldStat = can_stat(path);
  720. free(path);
  721. return couldStat;
  722. }
  723. void expand_tilde(char **ptr)
  724. {
  725. if (!conf.homedir || !conf.homedir[0])
  726. return;
  727. char *str = ptr ? *ptr : NULL;
  728. if (str && strchr(str, '~')) {
  729. char *p = NULL;
  730. size_t siz = strlen(str);
  731. if (str[siz - 1] == '/')
  732. str[siz - 1] = 0;
  733. if ((p = replace(str, "~", conf.homedir)))
  734. str_redup(ptr, p);
  735. else
  736. fatal("Unforseen error expanding '~'", 0);
  737. }
  738. }
  739. void check_crontab()
  740. {
  741. int i = 0;
  742. if (!conf.bot->hub && !conf.bot->localhub)
  743. fatal(STR("something is wrong."), 0);
  744. if (!(i = crontab_exists())) {
  745. crontab_create(5);
  746. if (!(i = crontab_exists()))
  747. printf(STR("* Error writing crontab entry.\n"));
  748. }
  749. }
  750. static void crontab_install(bd::Stream& crontab) {
  751. // Write out the new crontab
  752. Tempfile new_crontab = Tempfile("crontab");
  753. crontab.writeFile(new_crontab.fd);
  754. // Install new crontab
  755. const char* argv[] = {"crontab", new_crontab.file, 0};
  756. simple_exec(argv);
  757. }
  758. void crontab_del() {
  759. bd::Stream crontab;
  760. if (crontab_exists(&crontab, 1) == 1)
  761. crontab_install(crontab);
  762. }
  763. int crontab_exists(bd::Stream* crontab, bool excludeSelf) {
  764. char *out = NULL;
  765. int ret = -1;
  766. if (shell_exec("crontab -l", NULL, &out, NULL, 1)) {
  767. if (out) {
  768. bd::Stream stream(out);
  769. bd::String line;
  770. ret = 0;
  771. while (stream.tell() < stream.length()) {
  772. line = stream.getline();
  773. if (line[0] != '#' && line.find(binname) != bd::String::npos) {
  774. ret = 1;
  775. // Need to continue if the existing crontab is requested
  776. if (crontab && !excludeSelf)
  777. (*crontab) << line;
  778. else if (!crontab)
  779. break;
  780. } else if (crontab)
  781. (*crontab) << line;
  782. }
  783. free(out);
  784. } else
  785. ret = 0;
  786. }
  787. return ret;
  788. }
  789. char s1_2[3] = "",s1_8[3] = "",s2_5[3] = "";
  790. void crontab_create(int interval) {
  791. bd::Stream crontab;
  792. if (crontab_exists(&crontab) == 1)
  793. return;
  794. char buf[1024] = "";
  795. if (interval == 1)
  796. strlcpy(buf, "*", 2);
  797. else {
  798. int i = 1;
  799. int si = randint(interval);
  800. while (i < 60) {
  801. if (buf[0])
  802. strlcat(buf, ",", sizeof(buf));
  803. simple_snprintf(&buf[strlen(buf)], sizeof(buf) - strlen(buf), "%i", (i + si) % 60);
  804. i += interval;
  805. }
  806. }
  807. simple_snprintf(buf + strlen(buf), sizeof buf, STR(" * * * * %s > /dev/null 2>&1\n"), shell_escape(binname));
  808. crontab << buf;
  809. crontab_install(crontab);
  810. }
  811. int det_translate(const char *word)
  812. {
  813. if (word && word[0]) {
  814. if (!strcasecmp(word, STR("ignore")))
  815. return DET_IGNORE;
  816. else if (!strcasecmp(word, STR("warn")))
  817. return DET_WARN;
  818. else if (!strcasecmp(word, STR("reject")))
  819. return DET_REJECT;
  820. else if (!strcasecmp(word, STR("die")))
  821. return DET_DIE;
  822. else if (!strcasecmp(word, STR("suicide")))
  823. return DET_SUICIDE;
  824. }
  825. return DET_IGNORE;
  826. }
  827. const char *det_translate_num(int num)
  828. {
  829. switch (num) {
  830. case DET_IGNORE: return STR("ignore");
  831. case DET_WARN: return STR("warn");
  832. case DET_REJECT: return STR("reject");
  833. case DET_DIE: return STR("die");
  834. case DET_SUICIDE:return STR("suicide");
  835. default: return STR("ignore");
  836. }
  837. return STR("ignore");
  838. }
  839. char *shell_escape(const char *path)
  840. {
  841. static char ret1[DIRMAX] = "", ret2[DIRMAX] = "", *ret = NULL;
  842. static bool alt = 0;
  843. char *c = NULL;
  844. if (alt) {
  845. alt = 0;
  846. ret = ret1;
  847. } else {
  848. alt = 1;
  849. ret = ret2;
  850. }
  851. ret[0] = 0;
  852. for (c = (char *) path; c && *c; ++c) {
  853. if (strchr(ESCAPESHELL, *c))
  854. simple_snprintf(&ret[strlen(ret)], sizeof(ret1) - strlen(ret), "\\%c", *c);
  855. else
  856. simple_snprintf(&ret[strlen(ret)], sizeof(ret1) - strlen(ret), "%c", *c);
  857. }
  858. return ret;
  859. }
  860. /* vim: set sts=2 sw=2 ts=8 et: */