shell.c 27 KB

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