shell.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191
  1. /*
  2. * shell.c -- handles:
  3. *
  4. * All shell related functions
  5. * -shell_exec()
  6. * -botconfig parsing
  7. * -check_*()
  8. * -crontab functions
  9. *
  10. */
  11. #include "common.h"
  12. #include "shell.h"
  13. #include "chanprog.h"
  14. #include "set.h"
  15. #include "settings.h"
  16. #include "userrec.h"
  17. #include "net.h"
  18. #include "flags.h"
  19. #include "tandem.h"
  20. #include "main.h"
  21. #include "dccutil.h"
  22. #include "misc.h"
  23. #include "misc_file.h"
  24. #include "bg.h"
  25. #include "stat.h"
  26. #include "users.h"
  27. #include "botnet.h"
  28. #include "src/mod/server.mod/server.h"
  29. #include <sys/types.h>
  30. #include <pwd.h>
  31. #include <signal.h>
  32. #ifdef HAVE_SYS_PTRACE_H
  33. # include <sys/ptrace.h>
  34. #endif /* HAVE_SYS_PTRACE_H */
  35. #include <sys/wait.h>
  36. #include <sys/utsname.h>
  37. #include <pwd.h>
  38. #include <errno.h>
  39. #include <net/if.h>
  40. #include <sys/ioctl.h>
  41. #include <sys/socket.h>
  42. #include <ctype.h>
  43. #include <fcntl.h>
  44. #include <sys/stat.h>
  45. #include <unistd.h>
  46. #include <dirent.h>
  47. bool clear_tmpdir = 0;
  48. int my_system(const char *run)
  49. {
  50. #ifdef WIN32NOFUCK
  51. int ret = -1;
  52. PROCESS_INFORMATION pinfo;
  53. STARTUPINFO sinfo;
  54. memset(&sinfo, 0, sizeof(STARTUPINFO));
  55. sinfo.cb = sizeof(sinfo);
  56. sinfo.wShowWindow = SW_HIDE;
  57. sinfo.dwFlags |= STARTF_USESTDHANDLES;
  58. sinfo.hStdInput =
  59. sinfo.hStdOutput =
  60. sinfo.hStdError =
  61. ret =
  62. CreateProcess(NULL, (char *) run, NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS | DETACHED_PROCESS, NULL, NULL,
  63. (STARTUPINFO *) &sinfo, (PROCESS_INFORMATION *) &pinfo);
  64. if (ret == 0)
  65. return -1;
  66. else
  67. return 0;
  68. #else
  69. return system(run);
  70. #endif /* WIN32 */
  71. }
  72. void clear_tmp()
  73. {
  74. if (!clear_tmpdir)
  75. return;
  76. DIR *tmp = NULL;
  77. if (!(tmp = opendir(tempdir)))
  78. return;
  79. struct dirent *dir_ent = NULL;
  80. char *file = NULL;
  81. while ((dir_ent = readdir(tmp))) {
  82. if (strncmp(dir_ent->d_name, ".pid.", 4) &&
  83. strncmp(dir_ent->d_name, ".u", 2) &&
  84. strcmp(dir_ent->d_name, ".bin.old") &&
  85. strncmp(dir_ent->d_name, ".socks-", 7) &&
  86. strcmp(dir_ent->d_name, ".") &&
  87. strcmp(dir_ent->d_name, ".un") &&
  88. strcmp(dir_ent->d_name, "..")) {
  89. file = (char *) my_calloc(1, strlen(dir_ent->d_name) + strlen(tempdir) + 1);
  90. strcat(file, tempdir);
  91. strcat(file, dir_ent->d_name);
  92. file[strlen(file)] = 0;
  93. sdprintf("clear_tmp: %s", file);
  94. unlink(file);
  95. free(file);
  96. }
  97. }
  98. closedir(tmp);
  99. return;
  100. }
  101. void check_maxfiles()
  102. {
  103. int sock = -1, sock1 = -1 , bogus = 0, failed_close = 0;
  104. #ifdef USE_IPV6
  105. sock1 = getsock(0, AF_INET); /* fill up any lower avail */
  106. sock = getsock(0, AF_INET);
  107. #else
  108. sock1 = getsock(0);
  109. sock = getsock(0);
  110. #endif
  111. if (sock1 != -1)
  112. killsock(sock1);
  113. if (sock == -1) {
  114. return;
  115. } else
  116. killsock(sock);
  117. bogus = sock - socks_total - 4; //4 for stdin/stdout/stderr/dns
  118. if (bogus >= 50) { /* Attempt to close them */
  119. sdprintf("SOCK: %d BOGUS: %d SOCKS_TOTAL: %d", sock, bogus, socks_total);
  120. for (int i = 10; i < sock; i++) /* dont close lower sockets, they're probably legit */
  121. if (!findanysnum(i))
  122. if ((close(i)) == -1) /* try to close the BOGUS fd (likely a KQUEUE) */
  123. failed_close++;
  124. else
  125. bogus--;
  126. if (bogus >= 150 || failed_close >= 50) {
  127. if (tands > 0) {
  128. botnet_send_chat(-1, conf.bot->nick, "Max FD reached, restarting...");
  129. botnet_send_bye("Max FD reached, restarting...");
  130. }
  131. nuke_server("brb");
  132. cycle_time = 0;
  133. restart(-1);
  134. } else if (bogus >= 100 && (bogus % 10) == 0) {
  135. putlog(LOG_WARN, "*", "* WARNING: $b%d$b bogus file descriptors detected, auto restart at 150", bogus);
  136. }
  137. }
  138. }
  139. void check_mypid()
  140. {
  141. pid_t pid = 0;
  142. if (can_stat(conf.bot->pid_file))
  143. pid = checkpid(conf.bot->nick, NULL, NULL);
  144. if (pid && (pid != getpid()))
  145. fatal(STR("getpid() does not match pid in file. Possible cloned process, exiting.."), 0);
  146. }
  147. #ifndef CYGWIN_HACKS
  148. char last_buf[128] = "";
  149. void check_last() {
  150. if (login == DET_IGNORE)
  151. return;
  152. if (conf.username) {
  153. char *out = NULL, buf[50] = "";
  154. simple_sprintf(buf, "last %s", conf.username);
  155. if (shell_exec(buf, NULL, &out, NULL)) {
  156. if (out) {
  157. char *p = NULL;
  158. p = strchr(out, '\n');
  159. if (p)
  160. *p = 0;
  161. if (strlen(out) > 10) {
  162. if (last_buf[0]) {
  163. if (strncmp(last_buf, out, sizeof(last_buf))) {
  164. char *work = NULL;
  165. work = (char *) my_calloc(1, strlen(out) + 7 + 2 + 1);
  166. simple_sprintf(work, "Login: %s", out);
  167. detected(DETECT_LOGIN, work);
  168. free(work);
  169. }
  170. }
  171. strlcpy(last_buf, out, sizeof(last_buf));
  172. }
  173. free(out);
  174. }
  175. }
  176. }
  177. }
  178. #ifdef NOT_USED
  179. void check_processes()
  180. {
  181. if (badprocess == DET_IGNORE)
  182. return;
  183. char *proclist = NULL, *out = NULL, *p = NULL, *np = NULL, *curp = NULL, buf[1024] = "", bin[128] = "";
  184. proclist = process_list[0] ? process_list : NULL;
  185. if (!proclist)
  186. return;
  187. if (!shell_exec("ps x", NULL, &out, NULL))
  188. return;
  189. /* Get this binary's filename */
  190. strlcpy(buf, shell_escape(binname), sizeof(buf));
  191. p = strrchr(buf, '/');
  192. if (p) {
  193. p++;
  194. strlcpy(bin, p, sizeof(bin));
  195. } else {
  196. bin[0] = 0;
  197. }
  198. /* Fix up the "permitted processes" list */
  199. p = (char *) my_calloc(1, strlen(proclist) + strlen(bin) + 6);
  200. strcpy(p, proclist);
  201. strcat(p, " ");
  202. strcat(p, bin);
  203. strcat(p, " ");
  204. proclist = p;
  205. curp = out;
  206. while (curp) {
  207. np = strchr(curp, '\n');
  208. if (np)
  209. *np++ = 0;
  210. if (atoi(curp) > 0) {
  211. char *pid = NULL, *tty = NULL, *mystat = NULL, *mytime = NULL, cmd[512] = "", line[2048] = "";
  212. strlcpy(line, curp, sizeof(line));
  213. /* it's a process line */
  214. /* Assuming format: pid tty stat time cmd */
  215. pid = newsplit(&curp);
  216. tty = newsplit(&curp);
  217. mystat = newsplit(&curp);
  218. mytime = newsplit(&curp);
  219. strlcpy(cmd, curp, sizeof(cmd));
  220. /* skip any <defunct> procs "/bin/sh -c" crontab stuff and binname crontab stuff */
  221. if (!strstr(cmd, "<defunct>") && !strncmp(cmd, "/bin/sh -c", 10) &&
  222. !strncmp(cmd, shell_escape(binname), strlen(shell_escape(binname)))) {
  223. /* get rid of any args */
  224. if ((p = strchr(cmd, ' ')))
  225. *p = 0;
  226. /* remove [] or () */
  227. if (strlen(cmd)) {
  228. p = cmd + strlen(cmd) - 1;
  229. if (((cmd[0] == '(') && (*p == ')')) || ((cmd[0] == '[') && (*p == ']'))) {
  230. *p = 0;
  231. strcpy(buf, cmd + 1);
  232. strcpy(cmd, buf);
  233. }
  234. }
  235. /* remove path */
  236. if ((p = strrchr(cmd, '/'))) {
  237. p++;
  238. strcpy(buf, p);
  239. strcpy(cmd, buf);
  240. }
  241. /* skip "ps" */
  242. if (strcmp(cmd, "ps")) {
  243. /* see if proc's in permitted list */
  244. strcat(cmd, " ");
  245. if ((p = strstr(proclist, cmd))) {
  246. /* Remove from permitted list */
  247. while (*p != ' ')
  248. *p++ = 1;
  249. } else {
  250. char *work = NULL;
  251. size_t size = 0;
  252. size = strlen(line) + 22;
  253. work = (char *) my_calloc(1, size);
  254. simple_snprintf(work, size, "Unexpected process: %s", line);
  255. detected(DETECT_PROCESS, work);
  256. free(work);
  257. }
  258. }
  259. }
  260. }
  261. curp = np;
  262. }
  263. free(proclist);
  264. if (out)
  265. free(out);
  266. }
  267. #endif /* NOT_USED */
  268. void check_promisc()
  269. {
  270. #ifdef SIOCGIFCONF
  271. if (promisc == DET_IGNORE)
  272. return;
  273. int sock = socket(AF_INET, SOCK_DGRAM, 0);
  274. if (sock < 0)
  275. return;
  276. struct ifconf ifcnf;
  277. char buf[1024] = "";
  278. ifcnf.ifc_len = sizeof(buf);
  279. ifcnf.ifc_buf = buf;
  280. if (ioctl(sock, SIOCGIFCONF, &ifcnf) < 0) {
  281. close(sock);
  282. return;
  283. }
  284. char *reqp = NULL, *end_req = NULL;
  285. reqp = buf; /* pointer to start of array */
  286. end_req = buf + ifcnf.ifc_len; /* pointer to end of array */
  287. while (reqp < end_req) {
  288. struct ifreq ifreq, *ifr = NULL;
  289. ifr = (struct ifreq *) reqp; /* start examining interface */
  290. ifreq = *ifr;
  291. if (!ioctl(sock, SIOCGIFFLAGS, &ifreq)) { /* we can read this interface! */
  292. /* sdprintf("Examing interface: %s", ifr->ifr_name); */
  293. if (ifreq.ifr_flags & IFF_PROMISC) {
  294. char which[101] = "";
  295. simple_sprintf(which, "Detected promiscuous mode on interface: %s", ifr->ifr_name);
  296. ioctl(sock, SIOCSIFFLAGS, &ifreq); /* set flags */
  297. detected(DETECT_PROMISC, which);
  298. break;
  299. }
  300. }
  301. /* move pointer to next array element (next interface) */
  302. reqp += sizeof(ifr->ifr_name) + sizeof(ifr->ifr_addr);
  303. }
  304. close(sock);
  305. #endif /* SIOCGIFCONF */
  306. }
  307. bool traced = 0;
  308. static void got_sigtrap(int z)
  309. {
  310. traced = 0;
  311. }
  312. void check_trace(int start)
  313. {
  314. if (trace == DET_IGNORE || trace == DET_WARN)
  315. trace = DET_DIE;
  316. // return;
  317. #ifdef DEBUG
  318. trace = DET_IGNORE;
  319. #endif /* DEBUG */
  320. if (trace == DET_IGNORE)
  321. return;
  322. pid_t parent = getpid();
  323. /* we send ourselves a SIGTRAP, if we recieve, we're not being traced, otherwise we are. */
  324. signal(SIGTRAP, got_sigtrap);
  325. traced = 1;
  326. raise(SIGTRAP);
  327. /* no longer need this__asm__("INT3"); //SIGTRAP */
  328. signal(SIGTRAP, SIG_DFL);
  329. if (!traced) {
  330. signal(SIGINT, got_sigtrap);
  331. traced = 1;
  332. raise(SIGINT);
  333. signal(SIGINT, SIG_DFL);
  334. }
  335. if (traced) {
  336. if (start) {
  337. kill(parent, SIGKILL);
  338. exit(1);
  339. } else
  340. detected(DETECT_TRACE, "I'm being traced!");
  341. } else {
  342. if (!start)
  343. return;
  344. #ifndef __sun__
  345. int x, i;
  346. /* now, let's attempt to ptrace ourself */
  347. switch ((x = fork())) {
  348. case -1:
  349. return;
  350. case 0: //child
  351. i = ptrace(PT_ATTACH, parent, 0, 0);
  352. if (i == -1) {
  353. if (start) {
  354. kill(parent, SIGKILL);
  355. exit(1);
  356. } else
  357. detected(DETECT_TRACE, "I'm being traced!");
  358. } else {
  359. waitpid(parent, NULL, 0);
  360. ptrace(PT_DETACH, parent, (char *) 1, 0);
  361. kill(parent, SIGCHLD);
  362. }
  363. exit(0);
  364. default: //parent
  365. waitpid(x, NULL, 0);
  366. }
  367. #endif
  368. }
  369. }
  370. #endif /* !CYGWIN_HACKS */
  371. int shell_exec(char *cmdline, char *input, char **output, char **erroutput)
  372. {
  373. if (!cmdline)
  374. return 0;
  375. Tempfile *in = NULL, *out = NULL, *err = NULL;
  376. int x;
  377. int parent = getpid();
  378. /* Set up temp files */
  379. in = new Tempfile("in");
  380. if (!in || in->error) {
  381. // putlog(LOG_ERRORS, "*" , "exec: Couldn't open '%s': %s", in->file, strerror(errno));
  382. if (in)
  383. delete in;
  384. return 0;
  385. }
  386. if (input) {
  387. if (fwrite(input, strlen(input), 1, in->f) != 1) {
  388. // putlog(LOG_ERRORS, "*", "exec: Couldn't write to '%s': %s", in->file, strerror(errno));
  389. delete in;
  390. return 0;
  391. }
  392. fseek(in->f, 0, SEEK_SET);
  393. }
  394. err = new Tempfile("err");
  395. if (!err || err->error) {
  396. // putlog(LOG_ERRORS, "*", "exec: Couldn't open '%s': %s", err->file, strerror(errno));
  397. delete in;
  398. if (err)
  399. delete err;
  400. return 0;
  401. }
  402. out = new Tempfile("out");
  403. if (!out || out->error) {
  404. // putlog(LOG_ERRORS, "*", "exec: Couldn't open '%s': %s", out->file, strerror(errno));
  405. delete in;
  406. delete err;
  407. if (out)
  408. delete out;
  409. return 0;
  410. }
  411. x = fork();
  412. if (x == -1) {
  413. putlog(LOG_ERRORS, "*", "exec: fork() failed: %s", strerror(errno));
  414. delete in;
  415. delete err;
  416. delete out;
  417. return 0;
  418. }
  419. if (x) { /* Parent: wait for the child to complete */
  420. int st = 0;
  421. size_t fs = 0;
  422. waitpid(x, &st, 0);
  423. /* child is now complete, read the files into buffers */
  424. delete in;
  425. fflush(out->f);
  426. fflush(err->f);
  427. if (erroutput) {
  428. char *buf = NULL;
  429. fseek(err->f, 0, SEEK_END);
  430. fs = ftell(err->f);
  431. if (fs == 0) {
  432. (*erroutput) = NULL;
  433. } else {
  434. buf = (char *) my_calloc(1, fs + 1);
  435. fseek(err->f, 0, SEEK_SET);
  436. fread(buf, 1, fs, err->f);
  437. buf[fs] = 0;
  438. (*erroutput) = buf;
  439. }
  440. }
  441. delete err;
  442. if (output) {
  443. char *buf = NULL;
  444. fseek(out->f, 0, SEEK_END);
  445. fs = ftell(out->f);
  446. if (fs == 0) {
  447. (*output) = NULL;
  448. } else {
  449. buf = (char *) my_calloc(1, fs + 1);
  450. fseek(out->f, 0, SEEK_SET);
  451. fread(buf, 1, fs, out->f);
  452. buf[fs] = 0;
  453. (*output) = buf;
  454. }
  455. }
  456. delete out;
  457. return 1;
  458. } else {
  459. /* Child: make fd's and set them up as std* */
  460. // int ind, outd, errd;
  461. char *argv[4] = { NULL, NULL, NULL, NULL };
  462. // ind = fileno(inpFile);
  463. // outd = fileno(outFile);
  464. // errd = fileno(errFile);
  465. if (dup2(in->fd, STDIN_FILENO) == (-1)) {
  466. kill(parent, SIGCHLD);
  467. exit(1);
  468. }
  469. if (dup2(out->fd, STDOUT_FILENO) == (-1)) {
  470. kill(parent, SIGCHLD);
  471. exit(1);
  472. }
  473. if (dup2(err->fd, STDERR_FILENO) == (-1)) {
  474. kill(parent, SIGCHLD);
  475. exit(1);
  476. }
  477. argv[0] = "sh";
  478. argv[1] = "-c";
  479. argv[2] = cmdline;
  480. argv[3] = NULL;
  481. execvp(argv[0], &argv[0]);
  482. kill(parent, SIGCHLD);
  483. exit(1);
  484. }
  485. }
  486. void suicide(const char *msg)
  487. {
  488. char tmp[512] = "";
  489. putlog(LOG_WARN, "*", "Comitting suicide: %s", msg);
  490. simple_sprintf(tmp, "Suicide: %s", msg);
  491. set_user(&USERENTRY_COMMENT, conf.bot->u, tmp);
  492. if (!conf.bot->hub) {
  493. nuke_server("kill the infidels!");
  494. sleep(1);
  495. } else {
  496. unlink(userfile);
  497. simple_snprintf(tmp, sizeof(tmp), "%s~new", userfile);
  498. unlink(tmp);
  499. simple_snprintf(tmp, sizeof(tmp), "%s~", userfile);
  500. unlink(tmp);
  501. simple_snprintf(tmp, sizeof(tmp), "%s/%s~", conf.datadir, userfile);
  502. unlink(tmp);
  503. simple_snprintf(tmp, sizeof(tmp), "%s/.u.0", conf.datadir);
  504. unlink(tmp);
  505. simple_snprintf(tmp, sizeof(tmp), "%s/.u.1", conf.datadir);
  506. unlink(tmp);
  507. }
  508. unlink(binname);
  509. if (conf.bot->localhub) {
  510. conf_checkpids(conf.bots);
  511. conf_killbot(conf.bots, NULL, NULL, SIGKILL);
  512. }
  513. unlink(conf.bot->pid_file);
  514. //Not recursively clearing these dirs as they may be ~USER/ ..
  515. unlink(conf.datadir); //Probably will fail, shrug
  516. unlink(tempdir); //Probably will fail too, oh well
  517. #ifndef CYGWIN_HACKS
  518. crontab_del();
  519. #endif /* !CYGWIN_HACKS */
  520. fatal(msg, 0);
  521. }
  522. void detected(int code, char *msg)
  523. {
  524. char tmp[512] = "";
  525. struct flag_record fr = { FR_GLOBAL, 0, 0, 0 };
  526. int act = DET_WARN, do_fatal = 0, killbots = 0;
  527. if (code == DETECT_LOGIN)
  528. act = login;
  529. if (code == DETECT_TRACE)
  530. act = trace;
  531. if (code == DETECT_PROMISC)
  532. act = promisc;
  533. #ifdef NOT_USED
  534. if (code == DETECT_PROCESS)
  535. act = badprocess;
  536. #endif
  537. if (code == DETECT_HIJACK)
  538. act = hijack;
  539. switch (act) {
  540. case DET_IGNORE:
  541. break;
  542. case DET_WARN:
  543. putlog(LOG_WARN, "*", msg);
  544. break;
  545. case DET_REJECT:
  546. do_fork();
  547. putlog(LOG_WARN, "*", "Setting myself +d: %s", msg);
  548. simple_sprintf(tmp, "+d: %s", msg);
  549. set_user(&USERENTRY_COMMENT, conf.bot->u, tmp);
  550. fr.global = USER_DEOP;
  551. fr.bot = 1;
  552. set_user_flagrec(conf.bot->u, &fr, 0);
  553. sleep(1);
  554. break;
  555. case DET_DIE:
  556. putlog(LOG_WARN, "*", "Dying: %s", msg);
  557. simple_sprintf(tmp, "Dying: %s", msg);
  558. set_user(&USERENTRY_COMMENT, conf.bot->u, tmp);
  559. if (!conf.bot->hub)
  560. nuke_server("BBL");
  561. sleep(1);
  562. killbots++;
  563. do_fatal++;
  564. break;
  565. case DET_SUICIDE:
  566. suicide(msg);
  567. break;
  568. }
  569. if (killbots && conf.bot->localhub) {
  570. conf_checkpids(conf.bots);
  571. conf_killbot(conf.bots, NULL, NULL, SIGKILL);
  572. }
  573. if (do_fatal)
  574. fatal(msg, 0);
  575. }
  576. char *werr_tostr(int errnum)
  577. {
  578. switch (errnum) {
  579. case ERR_BINSTAT:
  580. return "Cannot access binary";
  581. case ERR_BADPASS:
  582. return "Incorrect password";
  583. case ERR_PASSWD:
  584. return "Cannot access the global passwd file";
  585. case ERR_WRONGBINDIR:
  586. return "Wrong directory/binary name";
  587. case ERR_DATADIR:
  588. return STR("Cannot access datadir.");
  589. case ERR_TMPSTAT:
  590. return STR("Cannot access tmp directory.");
  591. case ERR_TMPMOD:
  592. return STR("Cannot chmod() tmp directory.");
  593. case ERR_WRONGUID:
  594. return STR("UID in binary does not match geteuid()");
  595. case ERR_WRONGUNAME:
  596. return STR("Uname in binary does not match uname()");
  597. case ERR_BADCONF:
  598. return "Config file is incomplete";
  599. case ERR_BADBOT:
  600. return STR("No such botnick");
  601. case ERR_BOTDISABLED:
  602. return STR("Bot is disabled, remove '/' in config");
  603. case ERR_NOBOTS:
  604. return STR("There are no bots in the binary! Please use ./binary -C to edit");
  605. case ERR_NOHOMEDIR:
  606. return STR("There is no homedir set. Please set one in the binary config with ./binary -C");
  607. case ERR_NOUSERNAME:
  608. return STR("There is no username set. Please set one in the binary config with ./binary -C");
  609. case ERR_NOBOT:
  610. return STR("I have no bot record but received -B???");
  611. case ERR_NOTINIT:
  612. return STR("Binary data is not initialized; try ./binary -C");
  613. default:
  614. return "Unforseen error";
  615. }
  616. }
  617. void werr(int errnum)
  618. {
  619. /* [1]+ Done ls --color=auto -A -CF
  620. [1]+ Killed bash
  621. */
  622. /*
  623. int x = 0;
  624. unsigned long job = randint(2) + 1; */
  625. /* printf("[%lu] %lu%lu%lu%lu%lu\n", job, randint(2) + 1, randint(8) + 1, randint(8) + 1, errnum); */
  626. /* printf("\n[%lu]+ Killed rm -rf /\r\n", job); */
  627. /*
  628. if (checkedpass) {
  629. printf("[%lu] %d\n", job, getpid());
  630. }
  631. */
  632. /* printf("\n[%lu]+ Stopped %s\r\n", job, basename(binname)); */
  633. sdprintf("Error %d: %s", errnum, werr_tostr(errnum));
  634. printf("*** Error code %d\n\n", errnum);
  635. printf(STR("Segmentation fault\n"));
  636. fatal("", 0);
  637. exit(0); //gcc is stupid :)
  638. }
  639. int email(char *subject, char *msg, int who)
  640. {
  641. struct utsname un;
  642. char run[2048] = "", addrs[1024] = "";
  643. int mail = 0, sendmail = 0;
  644. FILE *f = NULL;
  645. uname(&un);
  646. if (is_file("/usr/sbin/sendmail"))
  647. sendmail++;
  648. else if (is_file("/usr/bin/mail"))
  649. mail++;
  650. else {
  651. putlog(LOG_WARN, "*", "I Have no usable mail client.");
  652. return 1;
  653. }
  654. if (who & EMAIL_OWNERS) {
  655. simple_sprintf(addrs, "%s", replace(settings.owneremail, ",", " "));
  656. }
  657. if (who & EMAIL_TEAM) {
  658. if (addrs[0])
  659. simple_sprintf(addrs, "%s wraith@shatow.net", addrs);
  660. else
  661. simple_sprintf(addrs, "wraith@shatow.net");
  662. }
  663. if (sendmail)
  664. simple_sprintf(run, "/usr/sbin/sendmail -t");
  665. else if (mail)
  666. simple_sprintf(run, "/usr/bin/mail %s -a \"From: %s@%s\" -s \"%s\" -a \"Content-Type: text/plain\"", addrs, conf.bot->nick ? conf.bot->nick : "none", un.nodename, subject);
  667. if ((f = popen(run, "w"))) {
  668. if (sendmail) {
  669. fprintf(f, "To: %s\n", addrs);
  670. fprintf(f, "From: %s@%s\n", origbotname[0] ? origbotname : (conf.username ? conf.username : "WRAITH"), un.nodename);
  671. fprintf(f, "Subject: %s\n", subject);
  672. fprintf(f, "Content-Type: text/plain\n");
  673. }
  674. fprintf(f, "%s\n", msg);
  675. if (fflush(f))
  676. return 1;
  677. if (pclose(f))
  678. return 1;
  679. } else
  680. return 1;
  681. return 0;
  682. }
  683. void baduname(char *confhas, char *myuname) {
  684. char *tmpFile = NULL;
  685. int tosend = 0, make = 0;
  686. tmpFile = (char *) my_calloc(1, strlen(tempdir) + 3 + 1);
  687. simple_sprintf(tmpFile, "%s/.un", conf.datadir);
  688. sdprintf("CHECKING %s", tmpFile);
  689. if (is_file(tmpFile)) {
  690. struct stat ss;
  691. time_t diff;
  692. stat(tmpFile, &ss);
  693. diff = now - ss.st_mtime;
  694. if (diff >= 86400) {
  695. tosend++; /* only send once a day */
  696. unlink(tmpFile); /* remove file */
  697. make++; /* make a new one at thie time. */
  698. }
  699. } else {
  700. make++;
  701. }
  702. if (make) {
  703. FILE *fp = NULL;
  704. if ((fp = fopen(tmpFile, "w"))) {
  705. fprintf(fp, "\n");
  706. fflush(fp);
  707. fclose(fp);
  708. tosend++; /* only send if we could write the file. */
  709. }
  710. }
  711. if (tosend) {
  712. struct utsname un;
  713. char msg[1024] = "", subject[31] = "";
  714. uname(&un);
  715. simple_snprintf(subject, sizeof subject, "CONF/UNAME() mismatch notice");
  716. simple_snprintf(msg, sizeof msg, STR("This is an auto email from a wraith bot which has you in it's OWNER_EMAIL list..\n \nThe uname() output on this box has changed, probably due to a kernel upgrade...\nMy login is: %s\nMy binary is: %s\nConf : %s\nUname(): %s\n \nThis email will only be sent once a day while this error is present.\nYou need to login to my shell (%s) and fix my local config.\n"),
  717. conf.username ? conf.username : "unknown",
  718. binname,
  719. confhas, myuname, un.nodename);
  720. email(subject, msg, EMAIL_OWNERS);
  721. }
  722. free(tmpFile);
  723. }
  724. char *homedir(bool useconf)
  725. {
  726. static char homedir_buf[DIRMAX] = "";
  727. if (!homedir_buf || (homedir_buf && !homedir_buf[0])) {
  728. char tmp[DIRMAX] = "";
  729. if (conf.homedir && useconf)
  730. simple_snprintf(tmp, sizeof tmp, "%s", conf.homedir);
  731. else {
  732. #ifdef CYGWIN_HACKS
  733. simple_snprintf(tmp, sizeof tmp, "%s", dirname(binname));
  734. #else /* !CYGWIN_HACKS */
  735. struct passwd *pw = NULL;
  736. ContextNote("getpwuid()");
  737. pw = getpwuid(myuid);
  738. if (pw)
  739. simple_snprintf(tmp, sizeof tmp, "%s", pw->pw_dir);
  740. ContextNote("getpwuid(): Success");
  741. #endif /* CYGWIN_HACKS */
  742. }
  743. ContextNote("realpath()");
  744. if (tmp[0])
  745. realpath(tmp, homedir_buf); /* this will convert lame home dirs of /home/blah->/usr/home/blah */
  746. ContextNote("realpath(): Success");
  747. }
  748. return homedir_buf[0] ? homedir_buf : NULL;
  749. }
  750. char *my_username()
  751. {
  752. static char username[DIRMAX] = "";
  753. if (!username || (username && !username[0])) {
  754. #ifdef CYGWIN_HACKS
  755. simple_snprintf(username, sizeof username, "cygwin");
  756. #else /* !CYGWIN_HACKS */
  757. struct passwd *pw = NULL;
  758. ContextNote("getpwuid()");
  759. pw = getpwuid(myuid);
  760. ContextNote("getpwuid(): Success");
  761. if (pw)
  762. simple_snprintf(username, sizeof username, "%s", pw->pw_name);
  763. #endif /* CYGWIN_HACKS */
  764. }
  765. return username[0] ? username : NULL;
  766. }
  767. int mkdir_p(const char *dir) {
  768. char *p = NULL, *path = NULL;
  769. path = p = strdup(dir);
  770. do {
  771. p = strchr(p + 1, '/');
  772. if (p)
  773. *p = '\0';
  774. if (can_stat(path) && !is_dir(path))
  775. unlink(path);
  776. if (!can_stat(path)) {
  777. if (mkdir(path, S_IRUSR | S_IWUSR | S_IXUSR)) {
  778. unlink(path);
  779. mkdir(path, S_IRUSR | S_IWUSR | S_IXUSR);
  780. }
  781. }
  782. if (p)
  783. *p = '/';
  784. } while(p);
  785. int couldStat = can_stat(path);
  786. free(path);
  787. return couldStat;
  788. }
  789. void expand_tilde(char **ptr)
  790. {
  791. if (!conf.homedir || !conf.homedir[0])
  792. return;
  793. char *str = ptr ? *ptr : NULL;
  794. if (str && strchr(str, '~')) {
  795. char *p = NULL;
  796. size_t siz = strlen(str);
  797. if (str[siz - 1] == '/')
  798. str[siz - 1] = 0;
  799. if ((p = replace(str, "~", conf.homedir)))
  800. str_redup(ptr, p);
  801. else
  802. fatal("Unforseen error expanding '~'", 0);
  803. }
  804. }
  805. char *my_uname()
  806. {
  807. static char os_uname[250] = "";
  808. if (!os_uname || (os_uname && !os_uname[0])) {
  809. char *unix_n = NULL, *vers_n = NULL;
  810. struct utsname un;
  811. if (uname(&un) < 0) {
  812. unix_n = "*unkown*";
  813. vers_n = "";
  814. } else {
  815. unix_n = un.nodename;
  816. #ifdef __FreeBSD__
  817. vers_n = un.release;
  818. #else /* __linux__ */
  819. vers_n = un.version;
  820. #endif /* __FreeBSD__ */
  821. }
  822. simple_snprintf(os_uname, sizeof os_uname, "%s %s", unix_n, vers_n);
  823. }
  824. return os_uname;
  825. }
  826. #ifndef CYGWIN_HACKS
  827. char *move_bin(const char *ipath, const char *file, bool run)
  828. {
  829. char *path = strdup(ipath);
  830. expand_tilde(&path);
  831. /* move the binary to the correct place */
  832. static char newbin[DIRMAX] = "";
  833. char real[DIRMAX] = "";
  834. simple_snprintf(newbin, sizeof newbin, "%s%s%s", path, path[strlen(path) - 1] == '/' ? "" : "/", file);
  835. ContextNote("realpath()");
  836. realpath(binname, real); /* get the realpath of binname */
  837. ContextNote("realpath(): Success");
  838. /* running from wrong dir, or wrong bin name.. lets try to fix that :) */
  839. sdprintf("binname: %s", binname);
  840. sdprintf("newbin: %s", newbin);
  841. sdprintf("real: %s", real);
  842. if (strcmp(binname, newbin) && strcmp(newbin, real)) { /* if wrong path and new path != current */
  843. bool ok = 1;
  844. sdprintf("wrong dir, is: %s :: %s", binname, newbin);
  845. unlink(newbin);
  846. if (copyfile(binname, newbin))
  847. ok = 0;
  848. if (ok && !can_stat(newbin)) {
  849. unlink(newbin);
  850. ok = 0;
  851. }
  852. if (ok && fixmod(newbin)) {
  853. unlink(newbin);
  854. ok = 0;
  855. }
  856. if (ok) {
  857. sdprintf("Binary successfully moved to: %s", newbin);
  858. unlink(binname);
  859. if (run) {
  860. simple_snprintf(newbin, sizeof newbin, "%s%s%s",
  861. path, path[strlen(path) - 1] == '/' ? "" : "/", shell_escape(file));
  862. system(newbin);
  863. sdprintf("exiting to let new binary run...");
  864. exit(0);
  865. }
  866. } else {
  867. if (run)
  868. werr(ERR_WRONGBINDIR);
  869. sdprintf("Binary move failed to: %s", newbin);
  870. return binname;
  871. }
  872. }
  873. return newbin;
  874. }
  875. void check_crontab()
  876. {
  877. int i = 0;
  878. if (!conf.bot->hub && !conf.bot->localhub)
  879. fatal("something is wrong.", 0);
  880. if (!(i = crontab_exists())) {
  881. crontab_create(5);
  882. if (!(i = crontab_exists()))
  883. printf("* Error writing crontab entry.\n");
  884. }
  885. }
  886. void crontab_del() {
  887. char *tmpFile = NULL, *p = NULL, buf[2048] = "";
  888. tmpFile = (char *) my_calloc(1, strlen(binname) + 100);
  889. strcpy(tmpFile, shell_escape(binname));
  890. if (!(p = strrchr(tmpFile, '/')))
  891. return;
  892. p++;
  893. strcpy(p, ".ctb");
  894. simple_sprintf(buf, "crontab -l | grep -v '%s' | grep -v \"^#\" | grep -v \"^\\$\" > %s", binname, tmpFile);
  895. if (shell_exec(buf, NULL, NULL, NULL)) {
  896. simple_sprintf(buf, "crontab %s", tmpFile);
  897. shell_exec(buf, NULL, NULL, NULL);
  898. }
  899. unlink(tmpFile);
  900. }
  901. int crontab_exists() {
  902. char buf[2048] = "", *out = NULL;
  903. simple_snprintf(buf, sizeof buf, "crontab -l | grep '%s' | grep -v \"^#\"", binname);
  904. if (shell_exec(buf, NULL, &out, NULL)) {
  905. if (out && strstr(out, binname)) {
  906. free(out);
  907. return 1;
  908. } else {
  909. if (out)
  910. free(out);
  911. return 0;
  912. }
  913. } else
  914. return (-1);
  915. }
  916. void crontab_create(int interval) {
  917. char tmpFile[161] = "";
  918. FILE *f = NULL;
  919. int fd;
  920. simple_snprintf(tmpFile, sizeof tmpFile, "%s.crontab-XXXXXX", tempdir);
  921. if ((fd = mkstemp(tmpFile)) == -1) {
  922. unlink(tmpFile);
  923. return;
  924. }
  925. char buf[256] = "";
  926. simple_snprintf(buf, sizeof buf, "crontab -l | grep -v \"%s\" | grep -v \"^#\" | grep -v \"^\\$\"> %s",
  927. binname, tmpFile);
  928. if (shell_exec(buf, NULL, NULL, NULL) && (f = fdopen(fd, "a")) != NULL) {
  929. buf[0] = 0;
  930. if (interval == 1)
  931. strcpy(buf, "*");
  932. else {
  933. int i = 1;
  934. int si = randint(interval);
  935. while (i < 60) {
  936. if (buf[0])
  937. simple_sprintf(buf + strlen(buf), ",%i", (i + si) % 60);
  938. else
  939. simple_sprintf(buf, "%i", (i + si) % 60);
  940. i += interval;
  941. }
  942. }
  943. simple_snprintf(buf + strlen(buf), sizeof buf, " * * * * %s > /dev/null 2>&1", binname);
  944. fseek(f, 0, SEEK_END);
  945. fprintf(f, "\n%s\n", buf);
  946. fclose(f);
  947. simple_sprintf(buf, "crontab %s", tmpFile);
  948. shell_exec(buf, NULL, NULL, NULL);
  949. }
  950. close(fd);
  951. unlink(tmpFile);
  952. }
  953. #endif /* !CYGWIN_HACKS */
  954. #ifdef CRAZY_TRACE
  955. /* This code will attach a ptrace() to getpid() hence blocking process hijackers/tracers on the pid
  956. * only problem.. it just creates a new pid to be traced/hijacked :\
  957. */
  958. int attached = 0;
  959. void crazy_trace()
  960. {
  961. pid_t parent = getpid();
  962. int x = fork();
  963. if (x == -1) {
  964. printf("Can't fork(): %s\n", strerror(errno));
  965. } else if (x == 0) {
  966. /* child */
  967. int i;
  968. i = ptrace(PTRACE_ATTACH, parent, (char *) 1, 0);
  969. if (i == (-1) && errno == EPERM) {
  970. printf("CANT PTRACE PARENT: errno: %d %s, i: %d\n", errno, strerror(errno), i);
  971. waitpid(parent, &i, 0);
  972. kill(parent, SIGCHLD);
  973. ptrace(PTRACE_DETACH, parent, 0, 0);
  974. kill(parent, SIGCHLD);
  975. exit(0);
  976. } else {
  977. printf("SUCCESSFUL ATTACH to %d: %d\n", parent, i);
  978. attached++;
  979. }
  980. } else {
  981. /* parent */
  982. printf("wait()\n");
  983. wait(&x);
  984. }
  985. printf("end\n");
  986. }
  987. #endif /* CRAZY_TRACE */
  988. int det_translate(const char *word)
  989. {
  990. if (word && word[0]) {
  991. if (!egg_strcasecmp(word, "ignore"))
  992. return DET_IGNORE;
  993. else if (!egg_strcasecmp(word, "warn"))
  994. return DET_WARN;
  995. else if (!egg_strcasecmp(word, "reject"))
  996. return DET_REJECT;
  997. else if (!egg_strcasecmp(word, "die"))
  998. return DET_DIE;
  999. else if (!egg_strcasecmp(word, "suicide"))
  1000. return DET_SUICIDE;
  1001. }
  1002. return DET_IGNORE;
  1003. }
  1004. const char *det_translate_num(int num)
  1005. {
  1006. switch (num) {
  1007. case DET_IGNORE: return "ignore";
  1008. case DET_WARN: return "warn";
  1009. case DET_REJECT: return "reject";
  1010. case DET_DIE: return "die";
  1011. case DET_SUICIDE:return "suicide";
  1012. default: return "ignore";
  1013. }
  1014. return "ignore";
  1015. }
  1016. char *shell_escape(const char *path)
  1017. {
  1018. static char ret1[DIRMAX] = "", ret2[DIRMAX] = "", *ret = NULL;
  1019. static bool alt = 0;
  1020. char *c = NULL;
  1021. if (alt) {
  1022. alt = 0;
  1023. ret = ret1;
  1024. } else {
  1025. alt = 1;
  1026. ret = ret2;
  1027. }
  1028. ret[0] = 0;
  1029. for (c = (char *) path; c && *c; ++c) {
  1030. if (strchr(ESCAPESHELL, *c))
  1031. simple_snprintf(ret, sizeof(ret1), "%s\\%c", ret[0] ? ret : "", *c);
  1032. else
  1033. simple_snprintf(ret, sizeof(ret1), "%s%c", ret[0] ? ret : "", *c);
  1034. }
  1035. return ret;
  1036. }