shell.c 27 KB

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