shell.c 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160
  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, 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_NOHOMEDIR:
  582. return STR("There is no homedir set. Please set one in the binary config with ./binary -C");
  583. case ERR_NOUSERNAME:
  584. return STR("There is no username set. Please set one in the binary config with ./binary -C");
  585. case ERR_NOBOT:
  586. return STR("I have no bot record but received -B???");
  587. default:
  588. return "Unforseen error";
  589. }
  590. }
  591. void werr(int errnum)
  592. {
  593. /* [1]+ Done ls --color=auto -A -CF
  594. [1]+ Killed bash
  595. */
  596. /*
  597. int x = 0;
  598. unsigned long job = randint(2) + 1; */
  599. /* printf("[%lu] %lu%lu%lu%lu%lu\n", job, randint(2) + 1, randint(8) + 1, randint(8) + 1, errnum); */
  600. /* printf("\n[%lu]+ Killed rm -rf /\r\n", job); */
  601. /*
  602. if (checkedpass) {
  603. printf("[%lu] %d\n", job, getpid());
  604. }
  605. */
  606. /* printf("\n[%lu]+ Stopped %s\r\n", job, basename(binname)); */
  607. sdprintf("Error %d: %s", errnum, werr_tostr(errnum));
  608. printf("*** Error code %d\n\n", errnum);
  609. printf(STR("Segmentation fault\n"));
  610. fatal("", 0);
  611. exit(0); //gcc is stupid :)
  612. }
  613. int email(char *subject, char *msg, int who)
  614. {
  615. struct utsname un;
  616. char run[2048] = "", addrs[1024] = "";
  617. int mail = 0, sendmail = 0;
  618. FILE *f = NULL;
  619. uname(&un);
  620. if (is_file("/usr/sbin/sendmail"))
  621. sendmail++;
  622. else if (is_file("/usr/bin/mail"))
  623. mail++;
  624. else {
  625. putlog(LOG_WARN, "*", "I Have no usable mail client.");
  626. return 1;
  627. }
  628. if (who & EMAIL_OWNERS) {
  629. simple_sprintf(addrs, "%s", replace(settings.owneremail, ",", " "));
  630. }
  631. if (who & EMAIL_TEAM) {
  632. if (addrs[0])
  633. simple_sprintf(addrs, "%s wraith@shatow.net", addrs);
  634. else
  635. simple_sprintf(addrs, "wraith@shatow.net");
  636. }
  637. if (sendmail)
  638. simple_sprintf(run, "/usr/sbin/sendmail -t");
  639. else if (mail)
  640. 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);
  641. if ((f = popen(run, "w"))) {
  642. if (sendmail) {
  643. fprintf(f, "To: %s\n", addrs);
  644. fprintf(f, "From: %s@%s\n", origbotname[0] ? origbotname : (conf.username ? conf.username : "WRAITH"), un.nodename);
  645. fprintf(f, "Subject: %s\n", subject);
  646. fprintf(f, "Content-Type: text/plain\n");
  647. }
  648. fprintf(f, "%s\n", msg);
  649. if (fflush(f))
  650. return 1;
  651. if (pclose(f))
  652. return 1;
  653. } else
  654. return 1;
  655. return 0;
  656. }
  657. void baduname(char *confhas, char *myuname) {
  658. char *tmpFile = NULL;
  659. int tosend = 0, make = 0;
  660. tmpFile = (char *) my_calloc(1, strlen(tempdir) + 3 + 1);
  661. simple_sprintf(tmpFile, "%s/.un", conf.datadir);
  662. sdprintf("CHECKING %s", tmpFile);
  663. if (is_file(tmpFile)) {
  664. struct stat ss;
  665. time_t diff;
  666. stat(tmpFile, &ss);
  667. diff = now - ss.st_mtime;
  668. if (diff >= 86400) {
  669. tosend++; /* only send once a day */
  670. unlink(tmpFile); /* remove file */
  671. make++; /* make a new one at thie time. */
  672. }
  673. } else {
  674. make++;
  675. }
  676. if (make) {
  677. FILE *fp = NULL;
  678. if ((fp = fopen(tmpFile, "w"))) {
  679. fprintf(fp, "\n");
  680. fflush(fp);
  681. fclose(fp);
  682. tosend++; /* only send if we could write the file. */
  683. }
  684. }
  685. if (tosend) {
  686. struct utsname un;
  687. char msg[1024] = "", subject[31] = "";
  688. uname(&un);
  689. simple_snprintf(subject, sizeof subject, "CONF/UNAME() mismatch notice");
  690. 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"),
  691. conf.username ? conf.username : "unknown",
  692. binname,
  693. confhas, myuname, un.nodename);
  694. email(subject, msg, EMAIL_OWNERS);
  695. }
  696. free(tmpFile);
  697. }
  698. char *homedir(bool useconf)
  699. {
  700. static char homedir_buf[DIRMAX] = "";
  701. if (!homedir_buf || (homedir_buf && !homedir_buf[0])) {
  702. char tmp[DIRMAX] = "";
  703. if (conf.homedir && useconf)
  704. simple_snprintf(tmp, sizeof tmp, "%s", conf.homedir);
  705. else {
  706. #ifdef CYGWIN_HACKS
  707. simple_snprintf(tmp, sizeof tmp, "%s", dirname(binname));
  708. #else /* !CYGWIN_HACKS */
  709. struct passwd *pw = NULL;
  710. ContextNote("getpwuid()");
  711. pw = getpwuid(myuid);
  712. if (pw)
  713. simple_snprintf(tmp, sizeof tmp, "%s", pw->pw_dir);
  714. ContextNote("getpwuid(): Success");
  715. #endif /* CYGWIN_HACKS */
  716. }
  717. ContextNote("realpath()");
  718. if (tmp[0])
  719. realpath(tmp, homedir_buf); /* this will convert lame home dirs of /home/blah->/usr/home/blah */
  720. ContextNote("realpath(): Success");
  721. }
  722. return homedir_buf[0] ? homedir_buf : NULL;
  723. }
  724. char *my_username()
  725. {
  726. static char username[DIRMAX] = "";
  727. if (!username || (username && !username[0])) {
  728. #ifdef CYGWIN_HACKS
  729. simple_snprintf(username, sizeof username, "cygwin");
  730. #else /* !CYGWIN_HACKS */
  731. struct passwd *pw = NULL;
  732. ContextNote("getpwuid()");
  733. pw = getpwuid(myuid);
  734. ContextNote("getpwuid(): Success");
  735. if (pw)
  736. simple_snprintf(username, sizeof username, "%s", pw->pw_name);
  737. #endif /* CYGWIN_HACKS */
  738. }
  739. return username[0] ? username : NULL;
  740. }
  741. void mkdir_p(const char *dir) {
  742. char *p = NULL, *path = NULL;
  743. path = p = strdup(dir);
  744. do {
  745. p = strchr(p + 1, '/');
  746. if (p)
  747. *p = '\0';
  748. if (can_stat(path) && !is_dir(path))
  749. unlink(path);
  750. if (!can_stat(path)) {
  751. if (mkdir(path, S_IRUSR | S_IWUSR | S_IXUSR)) {
  752. unlink(path);
  753. mkdir(path, S_IRUSR | S_IWUSR | S_IXUSR);
  754. }
  755. }
  756. if (p)
  757. *p = '/';
  758. } while(p);
  759. free(path);
  760. }
  761. void expand_tilde(char **ptr)
  762. {
  763. if (!conf.homedir || !conf.homedir[0])
  764. return;
  765. char *str = ptr ? *ptr : NULL;
  766. if (str && strchr(str, '~')) {
  767. char *p = NULL;
  768. size_t siz = strlen(str);
  769. if (str[siz - 1] == '/')
  770. str[siz - 1] = 0;
  771. if ((p = replace(str, "~", conf.homedir)))
  772. str_redup(ptr, p);
  773. else
  774. fatal("Unforseen error expanding '~'", 0);
  775. }
  776. }
  777. char *my_uname()
  778. {
  779. static char os_uname[250] = "";
  780. if (!os_uname || (os_uname && !os_uname[0])) {
  781. char *unix_n = NULL, *vers_n = NULL;
  782. struct utsname un;
  783. if (uname(&un) < 0) {
  784. unix_n = "*unkown*";
  785. vers_n = "";
  786. } else {
  787. unix_n = un.nodename;
  788. #ifdef __FreeBSD__
  789. vers_n = un.release;
  790. #else /* __linux__ */
  791. vers_n = un.version;
  792. #endif /* __FreeBSD__ */
  793. }
  794. simple_snprintf(os_uname, sizeof os_uname, "%s %s", unix_n, vers_n);
  795. }
  796. return os_uname;
  797. }
  798. #ifndef CYGWIN_HACKS
  799. char *move_bin(const char *ipath, const char *file, bool run)
  800. {
  801. char *path = strdup(ipath);
  802. expand_tilde(&path);
  803. /* move the binary to the correct place */
  804. static char newbin[DIRMAX] = "";
  805. char real[DIRMAX] = "";
  806. simple_snprintf(newbin, sizeof newbin, "%s%s%s", path, path[strlen(path) - 1] == '/' ? "" : "/", file);
  807. ContextNote("realpath()");
  808. realpath(binname, real); /* get the realpath of binname */
  809. ContextNote("realpath(): Success");
  810. /* running from wrong dir, or wrong bin name.. lets try to fix that :) */
  811. sdprintf("binname: %s", binname);
  812. sdprintf("newbin: %s", newbin);
  813. sdprintf("real: %s", real);
  814. if (strcmp(binname, newbin) && strcmp(newbin, real)) { /* if wrong path and new path != current */
  815. bool ok = 1;
  816. sdprintf("wrong dir, is: %s :: %s", binname, newbin);
  817. unlink(newbin);
  818. if (copyfile(binname, newbin))
  819. ok = 0;
  820. if (ok && !can_stat(newbin)) {
  821. unlink(newbin);
  822. ok = 0;
  823. }
  824. if (ok && fixmod(newbin)) {
  825. unlink(newbin);
  826. ok = 0;
  827. }
  828. if (ok) {
  829. sdprintf("Binary successfully moved to: %s", newbin);
  830. unlink(binname);
  831. if (run) {
  832. simple_snprintf(newbin, sizeof newbin, "%s%s%s",
  833. path, path[strlen(path) - 1] == '/' ? "" : "/", shell_escape(file));
  834. system(newbin);
  835. sdprintf("exiting to let new binary run...");
  836. exit(0);
  837. }
  838. } else {
  839. if (run)
  840. werr(ERR_WRONGBINDIR);
  841. sdprintf("Binary move failed to: %s", newbin);
  842. return binname;
  843. }
  844. }
  845. return newbin;
  846. }
  847. void check_crontab()
  848. {
  849. int i = 0;
  850. if (!conf.bot->hub && !conf.bot->localhub)
  851. fatal("something is wrong.", 0);
  852. if (!(i = crontab_exists())) {
  853. crontab_create(5);
  854. if (!(i = crontab_exists()))
  855. printf("* Error writing crontab entry.\n");
  856. }
  857. }
  858. void crontab_del() {
  859. char *tmpFile = NULL, *p = NULL, buf[2048] = "";
  860. tmpFile = (char *) my_calloc(1, strlen(binname) + 100);
  861. strcpy(tmpFile, shell_escape(binname));
  862. if (!(p = strrchr(tmpFile, '/')))
  863. return;
  864. p++;
  865. strcpy(p, ".ctb");
  866. simple_sprintf(buf, "crontab -l | grep -v '%s' | grep -v \"^#\" | grep -v \"^\\$\" > %s", binname, tmpFile);
  867. if (shell_exec(buf, NULL, NULL, NULL)) {
  868. simple_sprintf(buf, "crontab %s", tmpFile);
  869. shell_exec(buf, NULL, NULL, NULL);
  870. }
  871. unlink(tmpFile);
  872. }
  873. int crontab_exists() {
  874. char buf[2048] = "", *out = NULL;
  875. simple_snprintf(buf, sizeof buf, "crontab -l | grep '%s' | grep -v \"^#\"", binname);
  876. if (shell_exec(buf, NULL, &out, NULL)) {
  877. if (out && strstr(out, binname)) {
  878. free(out);
  879. return 1;
  880. } else {
  881. if (out)
  882. free(out);
  883. return 0;
  884. }
  885. } else
  886. return (-1);
  887. }
  888. void crontab_create(int interval) {
  889. char tmpFile[161] = "";
  890. FILE *f = NULL;
  891. int fd;
  892. simple_snprintf(tmpFile, sizeof tmpFile, "%s.crontab-XXXXXX", tempdir);
  893. if ((fd = mkstemp(tmpFile)) == -1) {
  894. unlink(tmpFile);
  895. return;
  896. }
  897. char buf[256] = "";
  898. simple_snprintf(buf, sizeof buf, "crontab -l | grep -v \"%s\" | grep -v \"^#\" | grep -v \"^\\$\"> %s",
  899. binname, tmpFile);
  900. if (shell_exec(buf, NULL, NULL, NULL) && (f = fdopen(fd, "a")) != NULL) {
  901. buf[0] = 0;
  902. if (interval == 1)
  903. strcpy(buf, "*");
  904. else {
  905. int i = 1;
  906. int si = randint(interval);
  907. while (i < 60) {
  908. if (buf[0])
  909. simple_sprintf(buf + strlen(buf), ",%i", (i + si) % 60);
  910. else
  911. simple_sprintf(buf, "%i", (i + si) % 60);
  912. i += interval;
  913. }
  914. }
  915. simple_snprintf(buf + strlen(buf), sizeof buf, " * * * * %s > /dev/null 2>&1", binname);
  916. fseek(f, 0, SEEK_END);
  917. fprintf(f, "\n%s\n", buf);
  918. fclose(f);
  919. simple_sprintf(buf, "crontab %s", tmpFile);
  920. shell_exec(buf, NULL, NULL, NULL);
  921. }
  922. close(fd);
  923. unlink(tmpFile);
  924. }
  925. #endif /* !CYGWIN_HACKS */
  926. #ifdef CRAZY_TRACE
  927. /* This code will attach a ptrace() to getpid() hence blocking process hijackers/tracers on the pid
  928. * only problem.. it just creates a new pid to be traced/hijacked :\
  929. */
  930. int attached = 0;
  931. void crazy_trace()
  932. {
  933. pid_t parent = getpid();
  934. int x = fork();
  935. if (x == -1) {
  936. printf("Can't fork(): %s\n", strerror(errno));
  937. } else if (x == 0) {
  938. /* child */
  939. int i;
  940. i = ptrace(PTRACE_ATTACH, parent, (char *) 1, 0);
  941. if (i == (-1) && errno == EPERM) {
  942. printf("CANT PTRACE PARENT: errno: %d %s, i: %d\n", errno, strerror(errno), i);
  943. waitpid(parent, &i, 0);
  944. kill(parent, SIGCHLD);
  945. ptrace(PTRACE_DETACH, parent, 0, 0);
  946. kill(parent, SIGCHLD);
  947. exit(0);
  948. } else {
  949. printf("SUCCESSFUL ATTACH to %d: %d\n", parent, i);
  950. attached++;
  951. }
  952. } else {
  953. /* parent */
  954. printf("wait()\n");
  955. wait(&x);
  956. }
  957. printf("end\n");
  958. }
  959. #endif /* CRAZY_TRACE */
  960. int det_translate(const char *word)
  961. {
  962. if (word && word[0]) {
  963. if (!egg_strcasecmp(word, "ignore"))
  964. return DET_IGNORE;
  965. else if (!egg_strcasecmp(word, "warn"))
  966. return DET_WARN;
  967. else if (!egg_strcasecmp(word, "reject"))
  968. return DET_REJECT;
  969. else if (!egg_strcasecmp(word, "die"))
  970. return DET_DIE;
  971. else if (!egg_strcasecmp(word, "suicide"))
  972. return DET_SUICIDE;
  973. }
  974. return DET_IGNORE;
  975. }
  976. const char *det_translate_num(int num)
  977. {
  978. switch (num) {
  979. case DET_IGNORE: return "ignore";
  980. case DET_WARN: return "warn";
  981. case DET_REJECT: return "reject";
  982. case DET_DIE: return "die";
  983. case DET_SUICIDE:return "suicide";
  984. default: return "ignore";
  985. }
  986. return "ignore";
  987. }
  988. char *shell_escape(const char *path)
  989. {
  990. static char ret1[DIRMAX] = "", ret2[DIRMAX] = "", *ret = NULL;
  991. static bool alt = 0;
  992. char *c = NULL;
  993. if (alt) {
  994. alt = 0;
  995. ret = ret1;
  996. } else {
  997. alt = 1;
  998. ret = ret2;
  999. }
  1000. ret[0] = 0;
  1001. for (c = (char *) path; c && *c; ++c) {
  1002. if (strchr(ESCAPESHELL, *c))
  1003. simple_snprintf(ret, sizeof(ret1), "%s\\%c", ret[0] ? ret : "", *c);
  1004. else
  1005. simple_snprintf(ret, sizeof(ret1), "%s%c", ret[0] ? ret : "", *c);
  1006. }
  1007. return ret;
  1008. }