shell.c 27 KB

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