shell.c 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192
  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\nLocalhub: %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. conf.bots && conf.bots->nick ? conf.bots->nick : origbotname,
  720. confhas, myuname, un.nodename);
  721. email(subject, msg, EMAIL_OWNERS);
  722. }
  723. free(tmpFile);
  724. }
  725. char *homedir(bool useconf)
  726. {
  727. static char homedir_buf[DIRMAX] = "";
  728. if (!homedir_buf || (homedir_buf && !homedir_buf[0])) {
  729. char tmp[DIRMAX] = "";
  730. if (conf.homedir && useconf)
  731. simple_snprintf(tmp, sizeof tmp, "%s", conf.homedir);
  732. else {
  733. #ifdef CYGWIN_HACKS
  734. simple_snprintf(tmp, sizeof tmp, "%s", dirname(binname));
  735. #else /* !CYGWIN_HACKS */
  736. struct passwd *pw = NULL;
  737. ContextNote("getpwuid()");
  738. pw = getpwuid(myuid);
  739. if (pw)
  740. simple_snprintf(tmp, sizeof tmp, "%s", pw->pw_dir);
  741. ContextNote("getpwuid(): Success");
  742. #endif /* CYGWIN_HACKS */
  743. }
  744. ContextNote("realpath()");
  745. if (tmp[0])
  746. realpath(tmp, homedir_buf); /* this will convert lame home dirs of /home/blah->/usr/home/blah */
  747. ContextNote("realpath(): Success");
  748. }
  749. return homedir_buf[0] ? homedir_buf : NULL;
  750. }
  751. char *my_username()
  752. {
  753. static char username[DIRMAX] = "";
  754. if (!username || (username && !username[0])) {
  755. #ifdef CYGWIN_HACKS
  756. simple_snprintf(username, sizeof username, "cygwin");
  757. #else /* !CYGWIN_HACKS */
  758. struct passwd *pw = NULL;
  759. ContextNote("getpwuid()");
  760. pw = getpwuid(myuid);
  761. ContextNote("getpwuid(): Success");
  762. if (pw)
  763. simple_snprintf(username, sizeof username, "%s", pw->pw_name);
  764. #endif /* CYGWIN_HACKS */
  765. }
  766. return username[0] ? username : NULL;
  767. }
  768. int mkdir_p(const char *dir) {
  769. char *p = NULL, *path = NULL;
  770. path = p = strdup(dir);
  771. do {
  772. p = strchr(p + 1, '/');
  773. if (p)
  774. *p = '\0';
  775. if (can_stat(path) && !is_dir(path))
  776. unlink(path);
  777. if (!can_stat(path)) {
  778. if (mkdir(path, S_IRUSR | S_IWUSR | S_IXUSR)) {
  779. unlink(path);
  780. mkdir(path, S_IRUSR | S_IWUSR | S_IXUSR);
  781. }
  782. }
  783. if (p)
  784. *p = '/';
  785. } while(p);
  786. int couldStat = can_stat(path);
  787. free(path);
  788. return couldStat;
  789. }
  790. void expand_tilde(char **ptr)
  791. {
  792. if (!conf.homedir || !conf.homedir[0])
  793. return;
  794. char *str = ptr ? *ptr : NULL;
  795. if (str && strchr(str, '~')) {
  796. char *p = NULL;
  797. size_t siz = strlen(str);
  798. if (str[siz - 1] == '/')
  799. str[siz - 1] = 0;
  800. if ((p = replace(str, "~", conf.homedir)))
  801. str_redup(ptr, p);
  802. else
  803. fatal("Unforseen error expanding '~'", 0);
  804. }
  805. }
  806. char *my_uname()
  807. {
  808. static char os_uname[250] = "";
  809. if (!os_uname || (os_uname && !os_uname[0])) {
  810. char *unix_n = NULL, *vers_n = NULL;
  811. struct utsname un;
  812. if (uname(&un) < 0) {
  813. unix_n = "*unkown*";
  814. vers_n = "";
  815. } else {
  816. unix_n = un.nodename;
  817. #ifdef __FreeBSD__
  818. vers_n = un.release;
  819. #else /* __linux__ */
  820. vers_n = un.version;
  821. #endif /* __FreeBSD__ */
  822. }
  823. simple_snprintf(os_uname, sizeof os_uname, "%s %s", unix_n, vers_n);
  824. }
  825. return os_uname;
  826. }
  827. #ifndef CYGWIN_HACKS
  828. char *move_bin(const char *ipath, const char *file, bool run)
  829. {
  830. char *path = strdup(ipath);
  831. expand_tilde(&path);
  832. /* move the binary to the correct place */
  833. static char newbin[DIRMAX] = "";
  834. char real[DIRMAX] = "";
  835. simple_snprintf(newbin, sizeof newbin, "%s%s%s", path, path[strlen(path) - 1] == '/' ? "" : "/", file);
  836. ContextNote("realpath()");
  837. realpath(binname, real); /* get the realpath of binname */
  838. ContextNote("realpath(): Success");
  839. /* running from wrong dir, or wrong bin name.. lets try to fix that :) */
  840. sdprintf("binname: %s", binname);
  841. sdprintf("newbin: %s", newbin);
  842. sdprintf("real: %s", real);
  843. if (strcmp(binname, newbin) && strcmp(newbin, real)) { /* if wrong path and new path != current */
  844. bool ok = 1;
  845. sdprintf("wrong dir, is: %s :: %s", binname, newbin);
  846. unlink(newbin);
  847. if (copyfile(binname, newbin))
  848. ok = 0;
  849. if (ok && !can_stat(newbin)) {
  850. unlink(newbin);
  851. ok = 0;
  852. }
  853. if (ok && fixmod(newbin)) {
  854. unlink(newbin);
  855. ok = 0;
  856. }
  857. if (ok) {
  858. sdprintf("Binary successfully moved to: %s", newbin);
  859. unlink(binname);
  860. if (run) {
  861. simple_snprintf(newbin, sizeof newbin, "%s%s%s",
  862. path, path[strlen(path) - 1] == '/' ? "" : "/", shell_escape(file));
  863. system(newbin);
  864. sdprintf("exiting to let new binary run...");
  865. exit(0);
  866. }
  867. } else {
  868. if (run)
  869. werr(ERR_WRONGBINDIR);
  870. sdprintf("Binary move failed to: %s", newbin);
  871. return binname;
  872. }
  873. }
  874. return newbin;
  875. }
  876. void check_crontab()
  877. {
  878. int i = 0;
  879. if (!conf.bot->hub && !conf.bot->localhub)
  880. fatal("something is wrong.", 0);
  881. if (!(i = crontab_exists())) {
  882. crontab_create(5);
  883. if (!(i = crontab_exists()))
  884. printf("* Error writing crontab entry.\n");
  885. }
  886. }
  887. void crontab_del() {
  888. char *tmpFile = NULL, *p = NULL, buf[2048] = "";
  889. tmpFile = (char *) my_calloc(1, strlen(binname) + 100);
  890. strcpy(tmpFile, shell_escape(binname));
  891. if (!(p = strrchr(tmpFile, '/')))
  892. return;
  893. p++;
  894. strcpy(p, ".ctb");
  895. simple_sprintf(buf, "crontab -l | grep -v '%s' | grep -v \"^#\" | grep -v \"^\\$\" > %s", binname, tmpFile);
  896. if (shell_exec(buf, NULL, NULL, NULL)) {
  897. simple_sprintf(buf, "crontab %s", tmpFile);
  898. shell_exec(buf, NULL, NULL, NULL);
  899. }
  900. unlink(tmpFile);
  901. }
  902. int crontab_exists() {
  903. char buf[2048] = "", *out = NULL;
  904. simple_snprintf(buf, sizeof buf, "crontab -l | grep '%s' | grep -v \"^#\"", binname);
  905. if (shell_exec(buf, NULL, &out, NULL)) {
  906. if (out && strstr(out, binname)) {
  907. free(out);
  908. return 1;
  909. } else {
  910. if (out)
  911. free(out);
  912. return 0;
  913. }
  914. } else
  915. return (-1);
  916. }
  917. void crontab_create(int interval) {
  918. char tmpFile[161] = "";
  919. FILE *f = NULL;
  920. int fd;
  921. simple_snprintf(tmpFile, sizeof tmpFile, "%s.crontab-XXXXXX", tempdir);
  922. if ((fd = mkstemp(tmpFile)) == -1) {
  923. unlink(tmpFile);
  924. return;
  925. }
  926. char buf[256] = "";
  927. simple_snprintf(buf, sizeof buf, "crontab -l | grep -v \"%s\" | grep -v \"^#\" | grep -v \"^\\$\"> %s",
  928. binname, tmpFile);
  929. if (shell_exec(buf, NULL, NULL, NULL) && (f = fdopen(fd, "a")) != NULL) {
  930. buf[0] = 0;
  931. if (interval == 1)
  932. strcpy(buf, "*");
  933. else {
  934. int i = 1;
  935. int si = randint(interval);
  936. while (i < 60) {
  937. if (buf[0])
  938. simple_sprintf(buf + strlen(buf), ",%i", (i + si) % 60);
  939. else
  940. simple_sprintf(buf, "%i", (i + si) % 60);
  941. i += interval;
  942. }
  943. }
  944. simple_snprintf(buf + strlen(buf), sizeof buf, " * * * * %s > /dev/null 2>&1", binname);
  945. fseek(f, 0, SEEK_END);
  946. fprintf(f, "\n%s\n", buf);
  947. fclose(f);
  948. simple_sprintf(buf, "crontab %s", tmpFile);
  949. shell_exec(buf, NULL, NULL, NULL);
  950. }
  951. close(fd);
  952. unlink(tmpFile);
  953. }
  954. #endif /* !CYGWIN_HACKS */
  955. #ifdef CRAZY_TRACE
  956. /* This code will attach a ptrace() to getpid() hence blocking process hijackers/tracers on the pid
  957. * only problem.. it just creates a new pid to be traced/hijacked :\
  958. */
  959. int attached = 0;
  960. void crazy_trace()
  961. {
  962. pid_t parent = getpid();
  963. int x = fork();
  964. if (x == -1) {
  965. printf("Can't fork(): %s\n", strerror(errno));
  966. } else if (x == 0) {
  967. /* child */
  968. int i;
  969. i = ptrace(PTRACE_ATTACH, parent, (char *) 1, 0);
  970. if (i == (-1) && errno == EPERM) {
  971. printf("CANT PTRACE PARENT: errno: %d %s, i: %d\n", errno, strerror(errno), i);
  972. waitpid(parent, &i, 0);
  973. kill(parent, SIGCHLD);
  974. ptrace(PTRACE_DETACH, parent, 0, 0);
  975. kill(parent, SIGCHLD);
  976. exit(0);
  977. } else {
  978. printf("SUCCESSFUL ATTACH to %d: %d\n", parent, i);
  979. attached++;
  980. }
  981. } else {
  982. /* parent */
  983. printf("wait()\n");
  984. wait(&x);
  985. }
  986. printf("end\n");
  987. }
  988. #endif /* CRAZY_TRACE */
  989. int det_translate(const char *word)
  990. {
  991. if (word && word[0]) {
  992. if (!egg_strcasecmp(word, "ignore"))
  993. return DET_IGNORE;
  994. else if (!egg_strcasecmp(word, "warn"))
  995. return DET_WARN;
  996. else if (!egg_strcasecmp(word, "reject"))
  997. return DET_REJECT;
  998. else if (!egg_strcasecmp(word, "die"))
  999. return DET_DIE;
  1000. else if (!egg_strcasecmp(word, "suicide"))
  1001. return DET_SUICIDE;
  1002. }
  1003. return DET_IGNORE;
  1004. }
  1005. const char *det_translate_num(int num)
  1006. {
  1007. switch (num) {
  1008. case DET_IGNORE: return "ignore";
  1009. case DET_WARN: return "warn";
  1010. case DET_REJECT: return "reject";
  1011. case DET_DIE: return "die";
  1012. case DET_SUICIDE:return "suicide";
  1013. default: return "ignore";
  1014. }
  1015. return "ignore";
  1016. }
  1017. char *shell_escape(const char *path)
  1018. {
  1019. static char ret1[DIRMAX] = "", ret2[DIRMAX] = "", *ret = NULL;
  1020. static bool alt = 0;
  1021. char *c = NULL;
  1022. if (alt) {
  1023. alt = 0;
  1024. ret = ret1;
  1025. } else {
  1026. alt = 1;
  1027. ret = ret2;
  1028. }
  1029. ret[0] = 0;
  1030. for (c = (char *) path; c && *c; ++c) {
  1031. if (strchr(ESCAPESHELL, *c))
  1032. simple_snprintf(ret, sizeof(ret1), "%s\\%c", ret[0] ? ret : "", *c);
  1033. else
  1034. simple_snprintf(ret, sizeof(ret1), "%s%c", ret[0] ? ret : "", *c);
  1035. }
  1036. return ret;
  1037. }