shell.c 27 KB

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