shell.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  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. #ifdef WIN32
  48. int
  49. my_system(const char *run)
  50. {
  51. int ret = -1;
  52. PROCESS_INFORMATION pinfo;
  53. STARTUPINFO sinfo;
  54. memset(&sinfo, 0, sizeof(STARTUPINFO));
  55. sinfo.cb = sizeof(sinfo);
  56. sinfo.wShowWindow = SW_HIDE;
  57. sinfo.dwFlags |= STARTF_USESTDHANDLES;
  58. sinfo.hStdInput =
  59. sinfo.hStdOutput =
  60. sinfo.hStdError =
  61. ret =
  62. CreateProcess(NULL, (char *) run, NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS | DETACHED_PROCESS, NULL, NULL,
  63. &sinfo, &pinfo);
  64. if (ret == 0)
  65. return -1;
  66. else
  67. return 0;
  68. }
  69. #endif /* WIN32 */
  70. void clear_tmp()
  71. {
  72. if (!clear_tmpdir)
  73. return;
  74. DIR *tmp = NULL;
  75. if (!(tmp = opendir(tempdir)))
  76. return;
  77. struct dirent *dir_ent = NULL;
  78. char *file = NULL;
  79. while ((dir_ent = readdir(tmp))) {
  80. if (strncmp(dir_ent->d_name, ".pid.", 4) && strncmp(dir_ent->d_name, ".u", 2) && strcmp(dir_ent->d_name, ".bin.old")
  81. && strcmp(dir_ent->d_name, ".") && strcmp(dir_ent->d_name, ".un") && strcmp(dir_ent->d_name, "..")) {
  82. file = (char *) my_calloc(1, strlen(dir_ent->d_name) + strlen(tempdir) + 1);
  83. strcat(file, tempdir);
  84. strcat(file, dir_ent->d_name);
  85. file[strlen(file)] = 0;
  86. sdprintf("clear_tmp: %s", file);
  87. unlink(file);
  88. free(file);
  89. }
  90. }
  91. closedir(tmp);
  92. return;
  93. }
  94. void check_maxfiles()
  95. {
  96. int sock = -1, sock1 = -1 , bogus = 0, failed_close = 0;
  97. #ifdef USE_IPV6
  98. sock1 = getsock(0, AF_INET); /* fill up any lower avail */
  99. sock = getsock(0, AF_INET);
  100. #else
  101. sock1 = getsock(0);
  102. sock = getsock(0);
  103. #endif
  104. if (sock1 != -1)
  105. killsock(sock1);
  106. if (sock == -1) {
  107. return;
  108. } else
  109. killsock(sock);
  110. bogus = sock - socks_total - 4; //4 for stdin/stdout/stderr/dns
  111. if (bogus >= 50) { /* Attempt to close them */
  112. sdprintf("SOCK: %d BOGUS: %d SOCKS_TOTAL: %d", sock, bogus, socks_total);
  113. for (int i = 10; i < sock; i++) /* dont close lower sockets, they're probably legit */
  114. if (!findanysnum(i))
  115. if ((close(i)) == -1) /* try to close the BOGUS fd (likely a KQUEUE) */
  116. failed_close++;
  117. else
  118. bogus--;
  119. if (bogus >= 150 || failed_close >= 50) {
  120. nuke_server("Max FD reached, restarting...");
  121. cycle_time = 0;
  122. restart(-1);
  123. } else if (bogus >= 100 && (bogus % 10) == 0) {
  124. putlog(LOG_WARN, "*", "* WARNING: $b%d$b bogus file descriptors detected, auto restart at 150", bogus);
  125. }
  126. }
  127. }
  128. void check_mypid()
  129. {
  130. pid_t pid = 0;
  131. if (can_stat(conf.bot->pid_file))
  132. pid = checkpid(conf.bot->nick, NULL);
  133. if (pid && (pid != getpid()))
  134. fatal(STR("getpid() does not match pid in file. Possible cloned process, exiting.."), 0);
  135. }
  136. #ifndef CYGWIN_HACKS
  137. char last_buf[128] = "";
  138. void check_last() {
  139. if (login == DET_IGNORE)
  140. return;
  141. if (conf.username) {
  142. char *out = NULL, buf[50] = "";
  143. simple_sprintf(buf, "last %s", conf.username);
  144. if (shell_exec(buf, NULL, &out, NULL)) {
  145. if (out) {
  146. char *p = NULL;
  147. p = strchr(out, '\n');
  148. if (p)
  149. *p = 0;
  150. if (strlen(out) > 10) {
  151. if (last_buf[0]) {
  152. if (strncmp(last_buf, out, sizeof(last_buf))) {
  153. char *work = NULL;
  154. work = (char *) my_calloc(1, strlen(out) + 7 + 2 + 1);
  155. simple_sprintf(work, "Login: %s", out);
  156. detected(DETECT_LOGIN, work);
  157. free(work);
  158. }
  159. }
  160. strlcpy(last_buf, out, sizeof(last_buf));
  161. }
  162. free(out);
  163. }
  164. }
  165. }
  166. }
  167. void check_processes()
  168. {
  169. if (badprocess == DET_IGNORE)
  170. return;
  171. char *proclist = NULL, *out = NULL, *p = NULL, *np = NULL, *curp = NULL, buf[1024] = "", bin[128] = "";
  172. proclist = process_list[0] ? process_list : NULL;
  173. if (!proclist)
  174. return;
  175. if (!shell_exec("ps x", NULL, &out, NULL))
  176. return;
  177. /* Get this binary's filename */
  178. strlcpy(buf, binname, sizeof(buf));
  179. p = strrchr(buf, '/');
  180. if (p) {
  181. p++;
  182. strlcpy(bin, p, sizeof(bin));
  183. } else {
  184. bin[0] = 0;
  185. }
  186. /* Fix up the "permitted processes" list */
  187. p = (char *) my_calloc(1, strlen(proclist) + strlen(bin) + 6);
  188. strcpy(p, proclist);
  189. strcat(p, " ");
  190. strcat(p, bin);
  191. strcat(p, " ");
  192. proclist = p;
  193. curp = out;
  194. while (curp) {
  195. np = strchr(curp, '\n');
  196. if (np)
  197. *np++ = 0;
  198. if (atoi(curp) > 0) {
  199. char *pid = NULL, *tty = NULL, *mystat = NULL, *mytime = NULL, cmd[512] = "", line[2048] = "";
  200. strlcpy(line, curp, sizeof(line));
  201. /* it's a process line */
  202. /* Assuming format: pid tty stat time cmd */
  203. pid = newsplit(&curp);
  204. tty = newsplit(&curp);
  205. mystat = newsplit(&curp);
  206. mytime = newsplit(&curp);
  207. strlcpy(cmd, curp, sizeof(cmd));
  208. /* skip any <defunct> procs "/bin/sh -c" crontab stuff and binname crontab stuff */
  209. if (!strstr(cmd, "<defunct>") && !strncmp(cmd, "/bin/sh -c", 10) && !strncmp(cmd, binname, strlen(binname))) {
  210. /* get rid of any args */
  211. if ((p = strchr(cmd, ' ')))
  212. *p = 0;
  213. /* remove [] or () */
  214. if (strlen(cmd)) {
  215. p = cmd + strlen(cmd) - 1;
  216. if (((cmd[0] == '(') && (*p == ')')) || ((cmd[0] == '[') && (*p == ']'))) {
  217. *p = 0;
  218. strcpy(buf, cmd + 1);
  219. strcpy(cmd, buf);
  220. }
  221. }
  222. /* remove path */
  223. if ((p = strrchr(cmd, '/'))) {
  224. p++;
  225. strcpy(buf, p);
  226. strcpy(cmd, buf);
  227. }
  228. /* skip "ps" */
  229. if (strcmp(cmd, "ps")) {
  230. /* see if proc's in permitted list */
  231. strcat(cmd, " ");
  232. if ((p = strstr(proclist, cmd))) {
  233. /* Remove from permitted list */
  234. while (*p != ' ')
  235. *p++ = 1;
  236. } else {
  237. char *work = NULL;
  238. size_t size = 0;
  239. size = strlen(line) + 22;
  240. work = (char *) my_calloc(1, size);
  241. simple_snprintf(work, size, "Unexpected process: %s", line);
  242. detected(DETECT_PROCESS, work);
  243. free(work);
  244. }
  245. }
  246. }
  247. }
  248. curp = np;
  249. }
  250. free(proclist);
  251. if (out)
  252. free(out);
  253. }
  254. void check_promisc()
  255. {
  256. #ifdef SIOCGIFCONF
  257. if (promisc == DET_IGNORE)
  258. return;
  259. int sock = socket(AF_INET, SOCK_DGRAM, 0);
  260. if (sock < 0)
  261. return;
  262. struct ifconf ifcnf;
  263. char buf[1024] = "";
  264. ifcnf.ifc_len = sizeof(buf);
  265. ifcnf.ifc_buf = buf;
  266. if (ioctl(sock, SIOCGIFCONF, &ifcnf) < 0) {
  267. close(sock);
  268. return;
  269. }
  270. char *reqp = NULL, *end_req = NULL;
  271. reqp = buf; /* pointer to start of array */
  272. end_req = buf + ifcnf.ifc_len; /* pointer to end of array */
  273. while (reqp < end_req) {
  274. struct ifreq ifreq, *ifr = NULL;
  275. ifr = (struct ifreq *) reqp; /* start examining interface */
  276. ifreq = *ifr;
  277. if (!ioctl(sock, SIOCGIFFLAGS, &ifreq)) { /* we can read this interface! */
  278. /* sdprintf("Examing interface: %s", ifr->ifr_name); */
  279. if (ifreq.ifr_flags & IFF_PROMISC) {
  280. char which[101] = "";
  281. simple_sprintf(which, "Detected promiscuous mode on interface: %s", ifr->ifr_name);
  282. ioctl(sock, SIOCSIFFLAGS, &ifreq); /* set flags */
  283. detected(DETECT_PROMISC, which);
  284. break;
  285. }
  286. }
  287. /* move pointer to next array element (next interface) */
  288. reqp += sizeof(ifr->ifr_name) + sizeof(ifr->ifr_addr);
  289. }
  290. close(sock);
  291. #endif /* SIOCGIFCONF */
  292. }
  293. #ifdef __linux__
  294. bool traced = 0;
  295. static void got_sigtrap(int z)
  296. {
  297. traced = 0;
  298. }
  299. #endif
  300. void check_trace(int start)
  301. {
  302. if (trace == DET_IGNORE)
  303. return;
  304. int x, i;
  305. pid_t parent = getpid();
  306. #ifdef __linux__
  307. /* we send ourselves a SIGTRAP, if we recieve, we're not being traced, otherwise we are. */
  308. signal(SIGTRAP, got_sigtrap);
  309. traced = 1;
  310. raise(SIGTRAP);
  311. /* no longer need this__asm__("INT3"); //SIGTRAP */
  312. signal(SIGTRAP, SIG_DFL);
  313. if (traced) {
  314. if (start) {
  315. kill(parent, SIGKILL);
  316. exit(1);
  317. } else
  318. detected(DETECT_TRACE, "I'm being traced!");
  319. } else {
  320. x = fork();
  321. if (x == -1)
  322. return;
  323. else if (x == 0) {
  324. i = ptrace(PTRACE_ATTACH, parent, 0, 0);
  325. if (i == (-1) && errno == EPERM) {
  326. if (start) {
  327. kill(parent, SIGKILL);
  328. exit(1);
  329. } else
  330. detected(DETECT_TRACE, "I'm being traced!");
  331. } else {
  332. waitpid(parent, &i, 0);
  333. kill(parent, SIGCHLD);
  334. ptrace(PTRACE_DETACH, parent, 0, 0);
  335. kill(parent, SIGCHLD);
  336. }
  337. exit(0);
  338. } else
  339. wait(&i);
  340. }
  341. #endif /* __linux__ */
  342. #ifdef BSD
  343. x = fork();
  344. if (x == -1)
  345. return;
  346. else if (x == 0) {
  347. i = ptrace(PT_ATTACH, parent, 0, 0);
  348. if (i == (-1) && errno == EBUSY) {
  349. if (start) {
  350. kill(parent, SIGKILL);
  351. exit(1);
  352. } else
  353. detected(DETECT_TRACE, "I'm being traced");
  354. } else {
  355. wait(&i);
  356. i = ptrace(PT_CONTINUE, parent, (caddr_t) 1, 0);
  357. kill(parent, SIGCHLD);
  358. wait(&i);
  359. i = ptrace(PT_DETACH, parent, (caddr_t) 1, 0);
  360. wait(&i);
  361. }
  362. exit(0);
  363. } else
  364. waitpid(x, NULL, 0);
  365. #endif /* BSD */
  366. }
  367. #endif /* !CYGWIN_HACKS */
  368. int shell_exec(char *cmdline, char *input, char **output, char **erroutput)
  369. {
  370. if (!cmdline)
  371. return 0;
  372. Tempfile *in = NULL, *out = NULL, *err = NULL;
  373. int x;
  374. int parent = getpid();
  375. /* Set up temp files */
  376. in = new Tempfile("in");
  377. if (!in || in->error) {
  378. // putlog(LOG_ERRORS, "*" , "exec: Couldn't open '%s': %s", in->file, strerror(errno));
  379. if (in)
  380. delete in;
  381. return 0;
  382. }
  383. if (input) {
  384. if (fwrite(input, strlen(input), 1, in->f) != 1) {
  385. // putlog(LOG_ERRORS, "*", "exec: Couldn't write to '%s': %s", in->file, strerror(errno));
  386. delete in;
  387. return 0;
  388. }
  389. fseek(in->f, 0, SEEK_SET);
  390. }
  391. err = new Tempfile("err");
  392. if (!err || err->error) {
  393. // putlog(LOG_ERRORS, "*", "exec: Couldn't open '%s': %s", err->file, strerror(errno));
  394. delete in;
  395. if (err)
  396. delete err;
  397. return 0;
  398. }
  399. out = new Tempfile("out");
  400. if (!out || out->error) {
  401. // putlog(LOG_ERRORS, "*", "exec: Couldn't open '%s': %s", out->file, strerror(errno));
  402. delete in;
  403. delete err;
  404. if (out)
  405. delete out;
  406. return 0;
  407. }
  408. x = fork();
  409. if (x == -1) {
  410. putlog(LOG_ERRORS, "*", "exec: fork() failed: %s", strerror(errno));
  411. delete in;
  412. delete err;
  413. delete out;
  414. return 0;
  415. }
  416. if (x) { /* Parent: wait for the child to complete */
  417. int st = 0;
  418. size_t fs = 0;
  419. waitpid(x, &st, 0);
  420. /* child is now complete, read the files into buffers */
  421. delete in;
  422. fflush(out->f);
  423. fflush(err->f);
  424. if (erroutput) {
  425. char *buf = NULL;
  426. fseek(err->f, 0, SEEK_END);
  427. fs = ftell(err->f);
  428. if (fs == 0) {
  429. (*erroutput) = NULL;
  430. } else {
  431. buf = (char *) my_calloc(1, fs + 1);
  432. fseek(err->f, 0, SEEK_SET);
  433. fread(buf, 1, fs, err->f);
  434. buf[fs] = 0;
  435. (*erroutput) = buf;
  436. }
  437. }
  438. delete err;
  439. if (output) {
  440. char *buf = NULL;
  441. fseek(out->f, 0, SEEK_END);
  442. fs = ftell(out->f);
  443. if (fs == 0) {
  444. (*output) = NULL;
  445. } else {
  446. buf = (char *) my_calloc(1, fs + 1);
  447. fseek(out->f, 0, SEEK_SET);
  448. fread(buf, 1, fs, out->f);
  449. buf[fs] = 0;
  450. (*output) = buf;
  451. }
  452. }
  453. delete out;
  454. return 1;
  455. } else {
  456. /* Child: make fd's and set them up as std* */
  457. // int ind, outd, errd;
  458. char *argv[4] = { NULL, NULL, NULL, NULL };
  459. // ind = fileno(inpFile);
  460. // outd = fileno(outFile);
  461. // errd = fileno(errFile);
  462. if (dup2(in->fd, STDIN_FILENO) == (-1)) {
  463. kill(parent, SIGCHLD);
  464. exit(1);
  465. }
  466. if (dup2(out->fd, STDOUT_FILENO) == (-1)) {
  467. kill(parent, SIGCHLD);
  468. exit(1);
  469. }
  470. if (dup2(err->fd, STDERR_FILENO) == (-1)) {
  471. kill(parent, SIGCHLD);
  472. exit(1);
  473. }
  474. argv[0] = "sh";
  475. argv[1] = "-c";
  476. argv[2] = cmdline;
  477. argv[3] = NULL;
  478. execvp(argv[0], &argv[0]);
  479. kill(parent, SIGCHLD);
  480. exit(1);
  481. }
  482. }
  483. void suicide(const char *msg)
  484. {
  485. char tmp[512] = "";
  486. putlog(LOG_WARN, "*", "Comitting suicide: %s", msg);
  487. simple_sprintf(tmp, "Suicide: %s", msg);
  488. set_user(&USERENTRY_COMMENT, conf.bot->u, tmp);
  489. if (!conf.bot->hub) {
  490. nuke_server("HARAKIRI!!");
  491. sleep(1);
  492. } else {
  493. unlink(userfile);
  494. simple_sprintf(tmp, "%s~", userfile);
  495. unlink(tmp);
  496. }
  497. unlink(binname);
  498. if (conf.bot->localhub) {
  499. conf_checkpids();
  500. conf_killbot(NULL, NULL, SIGKILL);
  501. }
  502. fatal(msg, 0);
  503. }
  504. void detected(int code, char *msg)
  505. {
  506. char tmp[512] = "";
  507. struct flag_record fr = { FR_GLOBAL, 0, 0, 0 };
  508. int act = DET_WARN, do_fatal = 0, killbots = 0;
  509. if (code == DETECT_LOGIN)
  510. act = login;
  511. if (code == DETECT_TRACE)
  512. act = trace;
  513. if (code == DETECT_PROMISC)
  514. act = promisc;
  515. if (code == DETECT_PROCESS)
  516. act = badprocess;
  517. if (code == DETECT_SIGCONT)
  518. act = hijack;
  519. switch (act) {
  520. case DET_IGNORE:
  521. break;
  522. case DET_WARN:
  523. putlog(LOG_WARN, "*", msg);
  524. break;
  525. case DET_REJECT:
  526. do_fork();
  527. putlog(LOG_WARN, "*", "Setting myself +d: %s", msg);
  528. simple_sprintf(tmp, "+d: %s", msg);
  529. set_user(&USERENTRY_COMMENT, conf.bot->u, tmp);
  530. fr.global = USER_DEOP;
  531. fr.bot = 1;
  532. set_user_flagrec(conf.bot->u, &fr, 0);
  533. sleep(1);
  534. break;
  535. case DET_DIE:
  536. putlog(LOG_WARN, "*", "Dying: %s", msg);
  537. simple_sprintf(tmp, "Dying: %s", msg);
  538. set_user(&USERENTRY_COMMENT, conf.bot->u, tmp);
  539. if (!conf.bot->hub)
  540. nuke_server("BBL");
  541. sleep(1);
  542. killbots++;
  543. do_fatal++;
  544. break;
  545. case DET_SUICIDE:
  546. suicide(msg);
  547. break;
  548. }
  549. if (killbots && conf.bot->localhub) {
  550. conf_checkpids();
  551. conf_killbot(NULL, NULL, SIGKILL);
  552. }
  553. if (do_fatal)
  554. fatal(msg, 0);
  555. }
  556. char *werr_tostr(int errnum)
  557. {
  558. switch (errnum) {
  559. case ERR_BINSTAT:
  560. return "Cannot access binary";
  561. case ERR_BADPASS:
  562. return "Incorrect password";
  563. case ERR_BINMOD:
  564. return "Cannot chmod() binary";
  565. case ERR_PASSWD:
  566. return "Cannot access the global passwd file";
  567. case ERR_WRONGBINDIR:
  568. return "Wrong directory/binary name";
  569. case ERR_TMPSTAT:
  570. return STR("Cannot access tmp directory.");
  571. case ERR_TMPMOD:
  572. return STR("Cannot chmod() tmp directory.");
  573. case ERR_WRONGUID:
  574. return STR("UID in binary does not match geteuid()");
  575. case ERR_WRONGUNAME:
  576. return STR("Uname in binary does not match uname()");
  577. case ERR_BADCONF:
  578. return "Config file is incomplete";
  579. case ERR_BADBOT:
  580. return STR("No such botnick");
  581. case ERR_BOTDISABLED:
  582. return STR("Bot is disabled, remove '/' in config");
  583. case ERR_NOBOTS:
  584. return STR("There are no bots in the binary! Please use ./binary -C to edit");
  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", tempdir);
  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. simple_snprintf(tmp, sizeof tmp, "%s", pw->pw_dir);
  713. ContextNote("getpwuid(): Success");
  714. #endif /* CYGWIN_HACKS */
  715. }
  716. ContextNote("realpath()");
  717. realpath(tmp, homedir_buf); /* this will convert lame home dirs of /home/blah->/usr/home/blah */
  718. ContextNote("realpath(): Success");
  719. }
  720. return homedir_buf;
  721. }
  722. char *my_username()
  723. {
  724. static char username[DIRMAX] = "";
  725. if (!username || (username && !username[0])) {
  726. #ifdef CYGWIN_HACKS
  727. simple_snprintf(username, sizeof username, "cygwin");
  728. #else /* !CYGWIN_HACKS */
  729. struct passwd *pw = NULL;
  730. ContextNote("getpwuid()");
  731. pw = getpwuid(myuid);
  732. ContextNote("getpwuid(): Success");
  733. simple_snprintf(username, sizeof username, "%s", pw->pw_name);
  734. #endif /* CYGWIN_HACKS */
  735. }
  736. return username;
  737. }
  738. void fix_tilde(char **binptr)
  739. {
  740. char *binpath = binptr ? *binptr : NULL;
  741. if (binpath && strchr(binpath, '~')) {
  742. char *p = NULL;
  743. if (binpath[strlen(binpath) - 1] == '/')
  744. binpath[strlen(binpath) - 1] = 0;
  745. if ((p = replace(binpath, "~", homedir())))
  746. str_redup(binptr, p);
  747. else
  748. fatal("Unforseen error expanding '~'", 0);
  749. }
  750. }
  751. char *my_uname()
  752. {
  753. static char os_uname[250] = "";
  754. if (!os_uname || (os_uname && !os_uname[0])) {
  755. char *unix_n = NULL, *vers_n = NULL;
  756. struct utsname un;
  757. if (uname(&un) < 0) {
  758. unix_n = "*unkown*";
  759. vers_n = "";
  760. } else {
  761. unix_n = un.nodename;
  762. #ifdef __FreeBSD__
  763. vers_n = un.release;
  764. #else /* __linux__ */
  765. vers_n = un.version;
  766. #endif /* __FreeBSD__ */
  767. }
  768. simple_snprintf(os_uname, sizeof os_uname, "%s %s", unix_n, vers_n);
  769. }
  770. return os_uname;
  771. }
  772. #ifndef CYGWIN_HACKS
  773. char *move_bin(const char *ipath, const char *file, bool run)
  774. {
  775. char *path = strdup(ipath);
  776. fix_tilde(&path);
  777. /* move the binary to the correct place */
  778. static char newbin[DIRMAX] = "";
  779. char real[DIRMAX] = "";
  780. simple_snprintf(newbin, sizeof newbin, "%s%s%s", path, path[strlen(path) - 1] == '/' ? "" : "/", file);
  781. ContextNote("realpath()");
  782. realpath(binname, real); /* get the realpath of binname */
  783. ContextNote("realpath(): Success");
  784. /* running from wrong dir, or wrong bin name.. lets try to fix that :) */
  785. sdprintf("binname: %s", binname);
  786. sdprintf("newbin: %s", newbin);
  787. sdprintf("real: %s", real);
  788. if (strcmp(binname, newbin) && strcmp(newbin, real)) { /* if wrong path and new path != current */
  789. bool ok = 1;
  790. sdprintf("wrong dir, is: %s :: %s", binname, newbin);
  791. unlink(newbin);
  792. if (copyfile(binname, newbin))
  793. ok = 0;
  794. if (ok && !can_stat(newbin)) {
  795. unlink(newbin);
  796. ok = 0;
  797. }
  798. if (ok && fixmod(newbin)) {
  799. unlink(newbin);
  800. ok = 0;
  801. }
  802. if (ok) {
  803. sdprintf("Binary successfully moved to: %s", newbin);
  804. unlink(binname);
  805. if (run) {
  806. system(newbin);
  807. sdprintf("exiting to let new binary run...");
  808. exit(0);
  809. }
  810. } else {
  811. if (run)
  812. werr(ERR_WRONGBINDIR);
  813. sdprintf("Binary move failed to: %s", newbin);
  814. return binname;
  815. }
  816. }
  817. return newbin;
  818. }
  819. void check_crontab()
  820. {
  821. int i = 0;
  822. if (!conf.bot->hub && !conf.bot->localhub)
  823. fatal("something is wrong.", 0);
  824. if (!(i = crontab_exists())) {
  825. crontab_create(5);
  826. if (!(i = crontab_exists()))
  827. printf("* Error writing crontab entry.\n");
  828. }
  829. }
  830. void crontab_del() {
  831. char *tmpFile = NULL, *p = NULL, buf[2048] = "";
  832. tmpFile = (char *) my_calloc(1, strlen(binname) + 100);
  833. strcpy(tmpFile, binname);
  834. if (!(p = strrchr(tmpFile, '/')))
  835. return;
  836. p++;
  837. strcpy(p, ".ctb");
  838. simple_sprintf(buf, "crontab -l | grep -v \"%s\" | grep -v \"^#\" | grep -v \"^\\$\" > %s", binname, tmpFile);
  839. if (shell_exec(buf, NULL, NULL, NULL)) {
  840. simple_sprintf(buf, "crontab %s", tmpFile);
  841. shell_exec(buf, NULL, NULL, NULL);
  842. }
  843. unlink(tmpFile);
  844. }
  845. int crontab_exists() {
  846. char buf[2048] = "", *out = NULL;
  847. simple_snprintf(buf, sizeof buf, "crontab -l | grep \"%s\" | grep -v \"^#\"", binname);
  848. if (shell_exec(buf, NULL, &out, NULL)) {
  849. if (out && strstr(out, binname)) {
  850. free(out);
  851. return 1;
  852. } else {
  853. if (out)
  854. free(out);
  855. return 0;
  856. }
  857. } else
  858. return (-1);
  859. }
  860. void crontab_create(int interval) {
  861. char tmpFile[161] = "";
  862. FILE *f = NULL;
  863. int fd;
  864. simple_snprintf(tmpFile, sizeof tmpFile, "%s.crontab-XXXXXX", tempdir);
  865. if ((fd = mkstemp(tmpFile)) == -1) {
  866. unlink(tmpFile);
  867. return;
  868. }
  869. char buf[256] = "";
  870. simple_snprintf(buf, sizeof buf, "crontab -l | grep -v \"%s\" | grep -v \"^#\" | grep -v \"^\\$\"> %s", 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 (!egg_strcasecmp(word, "ignore"))
  934. return DET_IGNORE;
  935. else if (!egg_strcasecmp(word, "warn"))
  936. return DET_WARN;
  937. else if (!egg_strcasecmp(word, "reject"))
  938. return DET_REJECT;
  939. else if (!egg_strcasecmp(word, "die"))
  940. return DET_DIE;
  941. else if (!egg_strcasecmp(word, "suicide"))
  942. return DET_SUICIDE;
  943. return DET_IGNORE;
  944. }
  945. const char *det_translate_num(int num)
  946. {
  947. switch (num) {
  948. case DET_IGNORE: return "ignore";
  949. case DET_WARN: return "warn";
  950. case DET_REJECT: return "reject";
  951. case DET_DIE: return "die";
  952. case DET_SUICIDE:return "suicide";
  953. default: return "ignore";
  954. }
  955. return "ignore";
  956. }