shell.c 29 KB

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