shell.c 28 KB

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