shell.c 27 KB

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