shell.c 27 KB

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