2
0

functions.inc.php 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767
  1. <?php
  2. function is_valid_regex($exp) {
  3. return @preg_match($exp, '') !== false;
  4. }
  5. function isset_has_content($var) {
  6. if (isset($var) && $var != "") {
  7. return true;
  8. }
  9. else {
  10. return false;
  11. }
  12. }
  13. // Validates ips and cidrs
  14. function valid_network($network) {
  15. if (filter_var($network, FILTER_VALIDATE_IP)) {
  16. return true;
  17. }
  18. $parts = explode('/', $network);
  19. if (count($parts) != 2) {
  20. return false;
  21. }
  22. $ip = $parts[0];
  23. $netmask = $parts[1];
  24. if (!preg_match("/^\d+$/", $netmask)){
  25. return false;
  26. }
  27. $netmask = intval($parts[1]);
  28. if ($netmask < 0) {
  29. return false;
  30. }
  31. if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
  32. return $netmask <= 32;
  33. }
  34. if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
  35. return $netmask <= 128;
  36. }
  37. return false;
  38. }
  39. function valid_hostname($hostname) {
  40. return filter_var($hostname, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME);
  41. }
  42. // Thanks to https://stackoverflow.com/a/49373789
  43. // Validates exact ip matches and ip-in-cidr, ipv4 and ipv6
  44. function ip_acl($ip, $networks) {
  45. foreach($networks as $network) {
  46. if (filter_var($network, FILTER_VALIDATE_IP)) {
  47. if ($ip == $network) {
  48. return true;
  49. }
  50. else {
  51. continue;
  52. }
  53. }
  54. $ipb = inet_pton($ip);
  55. $iplen = strlen($ipb);
  56. if (strlen($ipb) < 4) {
  57. continue;
  58. }
  59. $ar = explode('/', $network);
  60. $ip1 = $ar[0];
  61. $ip1b = inet_pton($ip1);
  62. $ip1len = strlen($ip1b);
  63. if ($ip1len != $iplen) {
  64. continue;
  65. }
  66. if (count($ar)>1) {
  67. $bits=(int)($ar[1]);
  68. }
  69. else {
  70. $bits = $iplen * 8;
  71. }
  72. for ($c=0; $bits>0; $c++) {
  73. $bytemask = ($bits < 8) ? 0xff ^ ((1 << (8-$bits))-1) : 0xff;
  74. if (((ord($ipb[$c]) ^ ord($ip1b[$c])) & $bytemask) != 0) {
  75. continue 2;
  76. }
  77. $bits-=8;
  78. }
  79. return true;
  80. }
  81. return false;
  82. }
  83. function hash_password($password) {
  84. $salt_str = bin2hex(openssl_random_pseudo_bytes(8));
  85. return "{SSHA256}".base64_encode(hash('sha256', $password . $salt_str, true) . $salt_str);
  86. }
  87. function last_login($user) {
  88. global $pdo;
  89. $stmt = $pdo->prepare('SELECT `remote`, `time` FROM `logs`
  90. WHERE JSON_EXTRACT(`call`, "$[0]") = "check_login"
  91. AND JSON_EXTRACT(`call`, "$[1]") = :user
  92. AND `type` = "success" ORDER BY `time` DESC LIMIT 1');
  93. $stmt->execute(array(':user' => $user));
  94. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  95. if (!empty($row)) {
  96. return $row;
  97. }
  98. else {
  99. return false;
  100. }
  101. }
  102. function flush_memcached() {
  103. try {
  104. $m = new Memcached();
  105. $m->addServer('memcached', 11211);
  106. $m->flush();
  107. }
  108. catch ( Exception $e ) {
  109. // Dunno
  110. }
  111. }
  112. function sys_mail($_data) {
  113. if ($_SESSION['mailcow_cc_role'] != "admin") {
  114. $_SESSION['return'][] = array(
  115. 'type' => 'danger',
  116. 'log' => array(__FUNCTION__),
  117. 'msg' => 'access_denied'
  118. );
  119. return false;
  120. }
  121. $excludes = $_data['mass_exclude'];
  122. $includes = $_data['mass_include'];
  123. $mailboxes = array();
  124. $mass_from = $_data['mass_from'];
  125. $mass_text = $_data['mass_text'];
  126. $mass_subject = $_data['mass_subject'];
  127. if (!filter_var($mass_from, FILTER_VALIDATE_EMAIL)) {
  128. $_SESSION['return'][] = array(
  129. 'type' => 'danger',
  130. 'log' => array(__FUNCTION__),
  131. 'msg' => 'from_invalid'
  132. );
  133. return false;
  134. }
  135. if (empty($mass_subject)) {
  136. $_SESSION['return'][] = array(
  137. 'type' => 'danger',
  138. 'log' => array(__FUNCTION__),
  139. 'msg' => 'subject_empty'
  140. );
  141. return false;
  142. }
  143. if (empty($mass_text)) {
  144. $_SESSION['return'][] = array(
  145. 'type' => 'danger',
  146. 'log' => array(__FUNCTION__),
  147. 'msg' => 'text_empty'
  148. );
  149. return false;
  150. }
  151. $domains = array_merge(mailbox('get', 'domains'), mailbox('get', 'alias_domains'));
  152. foreach ($domains as $domain) {
  153. foreach (mailbox('get', 'mailboxes', $domain) as $mailbox) {
  154. $mailboxes[] = $mailbox;
  155. }
  156. }
  157. if (!empty($includes)) {
  158. $rcpts = array_intersect($mailboxes, $includes);
  159. }
  160. elseif (!empty($excludes)) {
  161. $rcpts = array_diff($mailboxes, $excludes);
  162. }
  163. else {
  164. $rcpts = $mailboxes;
  165. }
  166. if (!empty($rcpts)) {
  167. ini_set('max_execution_time', 0);
  168. ini_set('max_input_time', 0);
  169. $mail = new PHPMailer;
  170. $mail->Timeout = 10;
  171. $mail->SMTPOptions = array(
  172. 'ssl' => array(
  173. 'verify_peer' => false,
  174. 'verify_peer_name' => false,
  175. 'allow_self_signed' => true
  176. )
  177. );
  178. $mail->isSMTP();
  179. $mail->Host = 'dovecot-mailcow';
  180. $mail->SMTPAuth = false;
  181. $mail->Port = 24;
  182. $mail->setFrom($mass_from);
  183. $mail->Subject = $mass_subject;
  184. $mail->CharSet ="UTF-8";
  185. $mail->Body = $mass_text;
  186. $mail->XMailer = 'MooMassMail';
  187. foreach ($rcpts as $rcpt) {
  188. $mail->AddAddress($rcpt);
  189. if (!$mail->send()) {
  190. $_SESSION['return'][] = array(
  191. 'type' => 'warning',
  192. 'log' => array(__FUNCTION__),
  193. 'msg' => 'Mailer error (RCPT "' . htmlspecialchars($rcpt) . '"): ' . str_replace('https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting', '', $mail->ErrorInfo)
  194. );
  195. }
  196. $mail->ClearAllRecipients();
  197. }
  198. }
  199. $_SESSION['return'][] = array(
  200. 'type' => 'success',
  201. 'log' => array(__FUNCTION__),
  202. 'msg' => 'Mass mail job completed, sent ' . count($rcpts) . ' mails'
  203. );
  204. }
  205. function logger($_data = false) {
  206. /*
  207. logger() will be called as last function
  208. To manually log a message, logger needs to be called like below.
  209. logger(array(
  210. 'return' => array(
  211. array(
  212. 'type' => 'danger',
  213. 'log' => array(__FUNCTION__),
  214. 'msg' => $err
  215. )
  216. )
  217. ));
  218. These messages will not be printed as alert box.
  219. To do so, push them to $_SESSION['return'] and do not call logger as they will be included automatically:
  220. $_SESSION['return'][] = array(
  221. 'type' => 'danger',
  222. 'log' => array(__FUNCTION__, $user, '*'),
  223. 'msg' => $err
  224. );
  225. */
  226. global $pdo;
  227. if (!$_data) {
  228. $_data = $_SESSION;
  229. }
  230. if (!empty($_data['return'])) {
  231. $task = substr(strtoupper(md5(uniqid(rand(), true))), 0, 6);
  232. foreach ($_data['return'] as $return) {
  233. $type = $return['type'];
  234. $msg = json_encode($return['msg'], JSON_UNESCAPED_UNICODE);
  235. $call = json_encode($return['log'], JSON_UNESCAPED_UNICODE);
  236. if (!empty($_SESSION["dual-login"]["username"])) {
  237. $user = $_SESSION["dual-login"]["username"] . ' => ' . $_SESSION['mailcow_cc_username'];
  238. $role = $_SESSION["dual-login"]["role"] . ' => ' . $_SESSION['mailcow_cc_role'];
  239. }
  240. elseif (!empty($_SESSION['mailcow_cc_username'])) {
  241. $user = $_SESSION['mailcow_cc_username'];
  242. $role = $_SESSION['mailcow_cc_role'];
  243. }
  244. else {
  245. $user = 'unauthenticated';
  246. $role = 'unauthenticated';
  247. }
  248. // We cannot log when logs is missing...
  249. try {
  250. $stmt = $pdo->prepare("INSERT INTO `logs` (`type`, `task`, `msg`, `call`, `user`, `role`, `remote`, `time`) VALUES
  251. (:type, :task, :msg, :call, :user, :role, :remote, UNIX_TIMESTAMP())");
  252. $stmt->execute(array(
  253. ':type' => $type,
  254. ':task' => $task,
  255. ':call' => $call,
  256. ':msg' => $msg,
  257. ':user' => $user,
  258. ':role' => $role,
  259. ':remote' => get_remote_ip()
  260. ));
  261. }
  262. catch (Exception $e) {
  263. // Do nothing
  264. }
  265. }
  266. }
  267. else {
  268. return true;
  269. }
  270. }
  271. function hasDomainAccess($username, $role, $domain) {
  272. global $pdo;
  273. if (!filter_var($username, FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $username))) {
  274. return false;
  275. }
  276. if (empty($domain) || !is_valid_domain_name($domain)) {
  277. return false;
  278. }
  279. if ($role != 'admin' && $role != 'domainadmin') {
  280. return false;
  281. }
  282. if ($role == 'admin') {
  283. $stmt = $pdo->prepare("SELECT `domain` FROM `domain`
  284. WHERE `domain` = :domain");
  285. $stmt->execute(array(':domain' => $domain));
  286. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  287. $stmt = $pdo->prepare("SELECT `alias_domain` FROM `alias_domain`
  288. WHERE `alias_domain` = :domain");
  289. $stmt->execute(array(':domain' => $domain));
  290. $num_results = $num_results + count($stmt->fetchAll(PDO::FETCH_ASSOC));
  291. if ($num_results != 0) {
  292. return true;
  293. }
  294. }
  295. elseif ($role == 'domainadmin') {
  296. $stmt = $pdo->prepare("SELECT `domain` FROM `domain_admins`
  297. WHERE (
  298. `active`='1'
  299. AND `username` = :username
  300. AND (`domain` = :domain1 OR `domain` = (SELECT `target_domain` FROM `alias_domain` WHERE `alias_domain` = :domain2))
  301. )");
  302. $stmt->execute(array(':username' => $username, ':domain1' => $domain, ':domain2' => $domain));
  303. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  304. if (!empty($num_results)) {
  305. return true;
  306. }
  307. }
  308. return false;
  309. }
  310. function hasMailboxObjectAccess($username, $role, $object) {
  311. global $pdo;
  312. if (!filter_var(html_entity_decode(rawurldecode($username)), FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $username))) {
  313. return false;
  314. }
  315. if ($role != 'admin' && $role != 'domainadmin' && $role != 'user') {
  316. return false;
  317. }
  318. if ($username == $object) {
  319. return true;
  320. }
  321. $stmt = $pdo->prepare("SELECT `domain` FROM `mailbox` WHERE `username` = :object");
  322. $stmt->execute(array(':object' => $object));
  323. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  324. if (isset($row['domain']) && hasDomainAccess($username, $role, $row['domain'])) {
  325. return true;
  326. }
  327. return false;
  328. }
  329. function hasAliasObjectAccess($username, $role, $object) {
  330. global $pdo;
  331. if (!filter_var(html_entity_decode(rawurldecode($username)), FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $username))) {
  332. return false;
  333. }
  334. if ($role != 'admin' && $role != 'domainadmin' && $role != 'user') {
  335. return false;
  336. }
  337. if ($username == $object) {
  338. return true;
  339. }
  340. $stmt = $pdo->prepare("SELECT `domain` FROM `alias` WHERE `address` = :object");
  341. $stmt->execute(array(':object' => $object));
  342. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  343. if (isset($row['domain']) && hasDomainAccess($username, $role, $row['domain'])) {
  344. return true;
  345. }
  346. return false;
  347. }
  348. function pem_to_der($pem_key) {
  349. // Need to remove BEGIN/END PUBLIC KEY
  350. $lines = explode("\n", trim($pem_key));
  351. unset($lines[count($lines)-1]);
  352. unset($lines[0]);
  353. return base64_decode(implode('', $lines));
  354. }
  355. function expand_ipv6($ip) {
  356. $hex = unpack("H*hex", inet_pton($ip));
  357. $ip = substr(preg_replace("/([A-f0-9]{4})/", "$1:", $hex['hex']), 0, -1);
  358. return $ip;
  359. }
  360. function generate_tlsa_digest($hostname, $port, $starttls = null) {
  361. if (!is_valid_domain_name($hostname)) {
  362. return "Not a valid hostname";
  363. }
  364. if (empty($starttls)) {
  365. $context = stream_context_create(array("ssl" => array("capture_peer_cert" => true, 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true)));
  366. $stream = stream_socket_client('ssl://' . $hostname . ':' . $port, $error_nr, $error_msg, 5, STREAM_CLIENT_CONNECT, $context);
  367. if (!$stream) {
  368. $error_msg = isset($error_msg) ? $error_msg : '-';
  369. return $error_nr . ': ' . $error_msg;
  370. }
  371. }
  372. else {
  373. $stream = stream_socket_client('tcp://' . $hostname . ':' . $port, $error_nr, $error_msg, 5);
  374. if (!$stream) {
  375. return $error_nr . ': ' . $error_msg;
  376. }
  377. $banner = fread($stream, 512 );
  378. if (preg_match("/^220/i", $banner)) { // SMTP
  379. fwrite($stream,"HELO tlsa.generator.local\r\n");
  380. fread($stream, 512);
  381. fwrite($stream,"STARTTLS\r\n");
  382. fread($stream, 512);
  383. }
  384. elseif (preg_match("/imap.+starttls/i", $banner)) { // IMAP
  385. fwrite($stream,"A1 STARTTLS\r\n");
  386. fread($stream, 512);
  387. }
  388. elseif (preg_match("/^\+OK/", $banner)) { // POP3
  389. fwrite($stream,"STLS\r\n");
  390. fread($stream, 512);
  391. }
  392. elseif (preg_match("/^OK/m", $banner)) { // Sieve
  393. fwrite($stream,"STARTTLS\r\n");
  394. fread($stream, 512);
  395. }
  396. else {
  397. return 'Unknown banner: "' . htmlspecialchars(trim($banner)) . '"';
  398. }
  399. // Upgrade connection
  400. stream_set_blocking($stream, true);
  401. stream_context_set_option($stream, 'ssl', 'capture_peer_cert', true);
  402. stream_context_set_option($stream, 'ssl', 'verify_peer', false);
  403. stream_context_set_option($stream, 'ssl', 'verify_peer_name', false);
  404. stream_context_set_option($stream, 'ssl', 'allow_self_signed', true);
  405. stream_socket_enable_crypto($stream, true, STREAM_CRYPTO_METHOD_ANY_CLIENT);
  406. stream_set_blocking($stream, false);
  407. }
  408. $params = stream_context_get_params($stream);
  409. if (!empty($params['options']['ssl']['peer_certificate'])) {
  410. $key_resource = openssl_pkey_get_public($params['options']['ssl']['peer_certificate']);
  411. // We cannot get ['rsa']['n'], the binary data would contain BEGIN/END PUBLIC KEY
  412. $key_data = openssl_pkey_get_details($key_resource)['key'];
  413. return '3 1 1 ' . openssl_digest(pem_to_der($key_data), 'sha256');
  414. }
  415. else {
  416. return 'Error: Cannot read peer certificate';
  417. }
  418. }
  419. function alertbox_log_parser($_data){
  420. global $lang;
  421. if (isset($_data['return'])) {
  422. foreach ($_data['return'] as $return) {
  423. // Get type
  424. $type = $return['type'];
  425. // If a lang[type][msg] string exists, use it as message
  426. if (is_string($lang[$return['type']][$return['msg']])) {
  427. $msg = $lang[$return['type']][$return['msg']];
  428. }
  429. // If msg is an array, use first element as language string and run printf on it with remaining array elements
  430. elseif (is_array($return['msg'])) {
  431. $msg = array_shift($return['msg']);
  432. $msg = vsprintf(
  433. $lang[$return['type']][$msg],
  434. $return['msg']
  435. );
  436. }
  437. // If none applies, use msg as returned message
  438. else {
  439. $msg = $return['msg'];
  440. }
  441. $log_array[] = array('msg' => $msg, 'type' => json_encode($type));
  442. }
  443. if (!empty($log_array)) {
  444. return $log_array;
  445. }
  446. }
  447. return false;
  448. }
  449. function verify_hash($hash, $password) {
  450. if (preg_match('/^{SSHA256}/i', $hash)) {
  451. // Remove tag if any
  452. $hash = preg_replace('/^{SSHA256}/i', '', $hash);
  453. // Decode hash
  454. $dhash = base64_decode($hash);
  455. // Get first 32 bytes of binary which equals a SHA256 hash
  456. $ohash = substr($dhash, 0, 32);
  457. // Remove SHA256 hash from decoded hash to get original salt string
  458. $osalt = str_replace($ohash, '', $dhash);
  459. // Check single salted SHA256 hash against extracted hash
  460. if (hash_equals(hash('sha256', $password . $osalt, true), $ohash)) {
  461. return true;
  462. }
  463. }
  464. elseif (preg_match('/^{PLAIN-MD5}/i', $hash)) {
  465. $hash = preg_replace('/^{PLAIN-MD5}/i', '', $hash);
  466. if (md5($password) == $hash) {
  467. return true;
  468. }
  469. }
  470. elseif (preg_match('/^{SHA512-CRYPT}/i', $hash)) {
  471. // Remove tag if any
  472. $hash = preg_replace('/^{SHA512-CRYPT}/i', '', $hash);
  473. // Decode hash
  474. preg_match('/\\$6\\$(.*)\\$(.*)/i', $hash, $hash_array);
  475. $osalt = $hash_array[1];
  476. $ohash = $hash_array[2];
  477. if (hash_equals(crypt($password, '$6$' . $osalt . '$'), $hash)) {
  478. return true;
  479. }
  480. }
  481. elseif (preg_match('/^{SSHA512}/i', $hash)) {
  482. $hash = preg_replace('/^{SSHA512}/i', '', $hash);
  483. // Decode hash
  484. $dhash = base64_decode($hash);
  485. // Get first 64 bytes of binary which equals a SHA512 hash
  486. $ohash = substr($dhash, 0, 64);
  487. // Remove SHA512 hash from decoded hash to get original salt string
  488. $osalt = str_replace($ohash, '', $dhash);
  489. // Check single salted SHA512 hash against extracted hash
  490. if (hash_equals(hash('sha512', $password . $osalt, true), $ohash)) {
  491. return true;
  492. }
  493. }
  494. elseif (preg_match('/^{MD5-CRYPT}/i', $hash)) {
  495. $hash = preg_replace('/^{MD5-CRYPT}/i', '', $hash);
  496. if (password_verify($password, $hash)) {
  497. return true;
  498. }
  499. }
  500. return false;
  501. }
  502. function check_login($user, $pass) {
  503. global $pdo;
  504. global $redis;
  505. global $imap_server;
  506. if (!filter_var($user, FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $user))) {
  507. $_SESSION['return'][] = array(
  508. 'type' => 'danger',
  509. 'log' => array(__FUNCTION__, $user, '*'),
  510. 'msg' => 'malformed_username'
  511. );
  512. return false;
  513. }
  514. $user = strtolower(trim($user));
  515. $stmt = $pdo->prepare("SELECT `password` FROM `admin`
  516. WHERE `superadmin` = '1'
  517. AND `active` = '1'
  518. AND `username` = :user");
  519. $stmt->execute(array(':user' => $user));
  520. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  521. foreach ($rows as $row) {
  522. if (verify_hash($row['password'], $pass)) {
  523. if (get_tfa($user)['name'] != "none") {
  524. $_SESSION['pending_mailcow_cc_username'] = $user;
  525. $_SESSION['pending_mailcow_cc_role'] = "admin";
  526. $_SESSION['pending_tfa_method'] = get_tfa($user)['name'];
  527. unset($_SESSION['ldelay']);
  528. $_SESSION['return'][] = array(
  529. 'type' => 'info',
  530. 'log' => array(__FUNCTION__, $user, '*'),
  531. 'msg' => 'awaiting_tfa_confirmation'
  532. );
  533. return "pending";
  534. }
  535. else {
  536. unset($_SESSION['ldelay']);
  537. // Reactivate TFA if it was set to "deactivate TFA for next login"
  538. $stmt = $pdo->prepare("UPDATE `tfa` SET `active`='1' WHERE `username` = :user");
  539. $stmt->execute(array(':user' => $user));
  540. $_SESSION['return'][] = array(
  541. 'type' => 'success',
  542. 'log' => array(__FUNCTION__, $user, '*'),
  543. 'msg' => array('logged_in_as', $user)
  544. );
  545. return "admin";
  546. }
  547. }
  548. }
  549. $stmt = $pdo->prepare("SELECT `password` FROM `admin`
  550. WHERE `superadmin` = '0'
  551. AND `active`='1'
  552. AND `username` = :user");
  553. $stmt->execute(array(':user' => $user));
  554. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  555. foreach ($rows as $row) {
  556. if (verify_hash($row['password'], $pass) !== false) {
  557. if (get_tfa($user)['name'] != "none") {
  558. $_SESSION['pending_mailcow_cc_username'] = $user;
  559. $_SESSION['pending_mailcow_cc_role'] = "domainadmin";
  560. $_SESSION['pending_tfa_method'] = get_tfa($user)['name'];
  561. unset($_SESSION['ldelay']);
  562. $_SESSION['return'][] = array(
  563. 'type' => 'info',
  564. 'log' => array(__FUNCTION__, $user, '*'),
  565. 'msg' => 'awaiting_tfa_confirmation'
  566. );
  567. return "pending";
  568. }
  569. else {
  570. unset($_SESSION['ldelay']);
  571. // Reactivate TFA if it was set to "deactivate TFA for next login"
  572. $stmt = $pdo->prepare("UPDATE `tfa` SET `active`='1' WHERE `username` = :user");
  573. $stmt->execute(array(':user' => $user));
  574. $_SESSION['return'][] = array(
  575. 'type' => 'success',
  576. 'log' => array(__FUNCTION__, $user, '*'),
  577. 'msg' => array('logged_in_as', $user)
  578. );
  579. return "domainadmin";
  580. }
  581. }
  582. }
  583. $stmt = $pdo->prepare("SELECT `password` FROM `mailbox`
  584. INNER JOIN domain on mailbox.domain = domain.domain
  585. WHERE `kind` NOT REGEXP 'location|thing|group'
  586. AND `mailbox`.`active`='1'
  587. AND `domain`.`active`='1'
  588. AND `username` = :user");
  589. $stmt->execute(array(':user' => $user));
  590. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  591. foreach ($rows as $row) {
  592. if (verify_hash($row['password'], $pass) !== false) {
  593. unset($_SESSION['ldelay']);
  594. $_SESSION['return'][] = array(
  595. 'type' => 'success',
  596. 'log' => array(__FUNCTION__, $user, '*'),
  597. 'msg' => array('logged_in_as', $user)
  598. );
  599. return "user";
  600. }
  601. }
  602. if (!isset($_SESSION['ldelay'])) {
  603. $_SESSION['ldelay'] = "0";
  604. $redis->publish("F2B_CHANNEL", "mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  605. error_log("mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  606. }
  607. elseif (!isset($_SESSION['mailcow_cc_username'])) {
  608. $_SESSION['ldelay'] = $_SESSION['ldelay']+0.5;
  609. $redis->publish("F2B_CHANNEL", "mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  610. error_log("mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  611. }
  612. $_SESSION['return'][] = array(
  613. 'type' => 'danger',
  614. 'log' => array(__FUNCTION__, $user, '*'),
  615. 'msg' => 'login_failed'
  616. );
  617. sleep($_SESSION['ldelay']);
  618. return false;
  619. }
  620. function formatBytes($size, $precision = 2) {
  621. if(!is_numeric($size)) {
  622. return "0";
  623. }
  624. $base = log($size, 1024);
  625. $suffixes = array(' Byte', ' KiB', ' MiB', ' GiB', ' TiB');
  626. if ($size == "0") {
  627. return "0";
  628. }
  629. return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
  630. }
  631. function update_sogo_static_view() {
  632. if (getenv('SKIP_SOGO') == "y") {
  633. return true;
  634. }
  635. global $pdo;
  636. global $lang;
  637. $stmt = $pdo->query("SELECT 'OK' FROM INFORMATION_SCHEMA.TABLES
  638. WHERE TABLE_NAME = 'sogo_view'");
  639. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  640. if ($num_results != 0) {
  641. $stmt = $pdo->query("REPLACE INTO _sogo_static_view (`c_uid`, `domain`, `c_name`, `c_password`, `c_cn`, `mail`, `aliases`, `ad_aliases`, `ext_acl`, `kind`, `multiple_bookings`)
  642. SELECT `c_uid`, `domain`, `c_name`, `c_password`, `c_cn`, `mail`, `aliases`, `ad_aliases`, `ext_acl`, `kind`, `multiple_bookings` from sogo_view");
  643. $stmt = $pdo->query("DELETE FROM _sogo_static_view WHERE `c_uid` NOT IN (SELECT `username` FROM `mailbox` WHERE `active` = '1');");
  644. }
  645. flush_memcached();
  646. }
  647. function edit_user_account($_data) {
  648. global $lang;
  649. global $pdo;
  650. $_data_log = $_data;
  651. !isset($_data_log['user_new_pass']) ?: $_data_log['user_new_pass'] = '*';
  652. !isset($_data_log['user_new_pass2']) ?: $_data_log['user_new_pass2'] = '*';
  653. !isset($_data_log['user_old_pass']) ?: $_data_log['user_old_pass'] = '*';
  654. $username = $_SESSION['mailcow_cc_username'];
  655. $role = $_SESSION['mailcow_cc_role'];
  656. $password_old = $_data['user_old_pass'];
  657. if (filter_var($username, FILTER_VALIDATE_EMAIL === false) || $role != 'user') {
  658. $_SESSION['return'][] = array(
  659. 'type' => 'danger',
  660. 'log' => array(__FUNCTION__, $_data_log),
  661. 'msg' => 'access_denied'
  662. );
  663. return false;
  664. }
  665. if (isset($_data['user_new_pass']) && isset($_data['user_new_pass2'])) {
  666. $password_new = $_data['user_new_pass'];
  667. $password_new2 = $_data['user_new_pass2'];
  668. }
  669. $stmt = $pdo->prepare("SELECT `password` FROM `mailbox`
  670. WHERE `kind` NOT REGEXP 'location|thing|group'
  671. AND `username` = :user");
  672. $stmt->execute(array(':user' => $username));
  673. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  674. if (!verify_hash($row['password'], $password_old)) {
  675. $_SESSION['return'][] = array(
  676. 'type' => 'danger',
  677. 'log' => array(__FUNCTION__, $_data_log),
  678. 'msg' => 'access_denied'
  679. );
  680. return false;
  681. }
  682. if (isset($password_new) && isset($password_new2)) {
  683. if (!empty($password_new2) && !empty($password_new)) {
  684. if ($password_new2 != $password_new) {
  685. $_SESSION['return'][] = array(
  686. 'type' => 'danger',
  687. 'log' => array(__FUNCTION__, $_data_log),
  688. 'msg' => 'password_mismatch'
  689. );
  690. return false;
  691. }
  692. if (!preg_match('/' . $GLOBALS['PASSWD_REGEP'] . '/', $password_new)) {
  693. $_SESSION['return'][] = array(
  694. 'type' => 'danger',
  695. 'log' => array(__FUNCTION__, $_data_log),
  696. 'msg' => 'password_complexity'
  697. );
  698. return false;
  699. }
  700. $password_hashed = hash_password($password_new);
  701. try {
  702. $stmt = $pdo->prepare("UPDATE `mailbox` SET `password` = :password_hashed, `attributes` = JSON_SET(`attributes`, '$.force_pw_update', '0') WHERE `username` = :username");
  703. $stmt->execute(array(
  704. ':password_hashed' => $password_hashed,
  705. ':username' => $username
  706. ));
  707. }
  708. catch (PDOException $e) {
  709. $_SESSION['return'][] = array(
  710. 'type' => 'danger',
  711. 'log' => array(__FUNCTION__, $_data_log),
  712. 'msg' => array('mysql_error', $e)
  713. );
  714. return false;
  715. }
  716. }
  717. }
  718. update_sogo_static_view();
  719. $_SESSION['return'][] = array(
  720. 'type' => 'success',
  721. 'log' => array(__FUNCTION__, $_data_log),
  722. 'msg' => array('mailbox_modified', htmlspecialchars($username))
  723. );
  724. }
  725. function user_get_alias_details($username) {
  726. global $lang;
  727. global $pdo;
  728. $data['direct_aliases'] = false;
  729. $data['shared_aliases'] = false;
  730. if ($_SESSION['mailcow_cc_role'] == "user") {
  731. $username = $_SESSION['mailcow_cc_username'];
  732. }
  733. if (!filter_var($username, FILTER_VALIDATE_EMAIL)) {
  734. return false;
  735. }
  736. $data['address'] = $username;
  737. $stmt = $pdo->prepare("SELECT `address` AS `shared_aliases`, `public_comment` FROM `alias`
  738. WHERE `goto` REGEXP :username_goto
  739. AND `address` NOT LIKE '@%'
  740. AND `goto` != :username_goto2
  741. AND `address` != :username_address");
  742. $stmt->execute(array(
  743. ':username_goto' => '(^|,)'.$username.'($|,)',
  744. ':username_goto2' => $username,
  745. ':username_address' => $username
  746. ));
  747. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  748. while ($row = array_shift($run)) {
  749. $data['shared_aliases'][$row['shared_aliases']]['public_comment'] = htmlspecialchars($row['public_comment']);
  750. //$data['shared_aliases'][] = $row['shared_aliases'];
  751. }
  752. $stmt = $pdo->prepare("SELECT `address` AS `direct_aliases`, `public_comment` FROM `alias`
  753. WHERE `goto` = :username_goto
  754. AND `address` NOT LIKE '@%'
  755. AND `address` != :username_address");
  756. $stmt->execute(
  757. array(
  758. ':username_goto' => $username,
  759. ':username_address' => $username
  760. ));
  761. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  762. while ($row = array_shift($run)) {
  763. $data['direct_aliases'][$row['direct_aliases']]['public_comment'] = htmlspecialchars($row['public_comment']);
  764. }
  765. $stmt = $pdo->prepare("SELECT CONCAT(local_part, '@', alias_domain) AS `ad_alias`, `alias_domain` FROM `mailbox`
  766. LEFT OUTER JOIN `alias_domain` on `target_domain` = `domain`
  767. WHERE `username` = :username ;");
  768. $stmt->execute(array(':username' => $username));
  769. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  770. while ($row = array_shift($run)) {
  771. if (empty($row['ad_alias'])) {
  772. continue;
  773. }
  774. $data['direct_aliases'][$row['ad_alias']]['public_comment'] = '↪ ' . $row['alias_domain'];
  775. }
  776. $stmt = $pdo->prepare("SELECT IFNULL(GROUP_CONCAT(`send_as` SEPARATOR ', '), '&#10008;') AS `send_as` FROM `sender_acl` WHERE `logged_in_as` = :username AND `send_as` NOT LIKE '@%';");
  777. $stmt->execute(array(':username' => $username));
  778. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  779. while ($row = array_shift($run)) {
  780. $data['aliases_also_send_as'] = $row['send_as'];
  781. }
  782. $stmt = $pdo->prepare("SELECT CONCAT_WS(', ', IFNULL(GROUP_CONCAT(DISTINCT `send_as` SEPARATOR ', '), '&#10008;'), GROUP_CONCAT(DISTINCT CONCAT('@',`alias_domain`) SEPARATOR ', ')) AS `send_as` FROM `sender_acl` LEFT JOIN `alias_domain` ON `alias_domain`.`target_domain` = TRIM(LEADING '@' FROM `send_as`) WHERE `logged_in_as` = :username AND `send_as` LIKE '@%';");
  783. $stmt->execute(array(':username' => $username));
  784. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  785. while ($row = array_shift($run)) {
  786. $data['aliases_send_as_all'] = $row['send_as'];
  787. }
  788. $stmt = $pdo->prepare("SELECT IFNULL(GROUP_CONCAT(`address` SEPARATOR ', '), '&#10008;') as `address` FROM `alias` WHERE `goto` REGEXP :username AND `address` LIKE '@%';");
  789. $stmt->execute(array(':username' => '(^|,)'.$username.'($|,)'));
  790. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  791. while ($row = array_shift($run)) {
  792. $data['is_catch_all'] = $row['address'];
  793. }
  794. return $data;
  795. }
  796. function is_valid_domain_name($domain_name) {
  797. if (empty($domain_name)) {
  798. return false;
  799. }
  800. $domain_name = idn_to_ascii($domain_name, 0, INTL_IDNA_VARIANT_UTS46);
  801. return (preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $domain_name)
  802. && preg_match("/^.{1,253}$/", $domain_name)
  803. && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $domain_name));
  804. }
  805. function set_tfa($_data) {
  806. global $lang;
  807. global $pdo;
  808. global $yubi;
  809. global $u2f;
  810. global $tfa;
  811. $_data_log = $_data;
  812. !isset($_data_log['confirm_password']) ?: $_data_log['confirm_password'] = '*';
  813. $username = $_SESSION['mailcow_cc_username'];
  814. if ($_SESSION['mailcow_cc_role'] != "domainadmin" &&
  815. $_SESSION['mailcow_cc_role'] != "admin") {
  816. $_SESSION['return'][] = array(
  817. 'type' => 'danger',
  818. 'log' => array(__FUNCTION__, $_data_log),
  819. 'msg' => 'access_denied'
  820. );
  821. return false;
  822. }
  823. $stmt = $pdo->prepare("SELECT `password` FROM `admin`
  824. WHERE `username` = :user");
  825. $stmt->execute(array(':user' => $username));
  826. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  827. if (!verify_hash($row['password'], $_data["confirm_password"])) {
  828. $_SESSION['return'][] = array(
  829. 'type' => 'danger',
  830. 'log' => array(__FUNCTION__, $_data_log),
  831. 'msg' => 'access_denied'
  832. );
  833. return false;
  834. }
  835. switch ($_data["tfa_method"]) {
  836. case "yubi_otp":
  837. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  838. $yubico_id = $_data['yubico_id'];
  839. $yubico_key = $_data['yubico_key'];
  840. $yubi = new Auth_Yubico($yubico_id, $yubico_key);
  841. if (!$yubi) {
  842. $_SESSION['return'][] = array(
  843. 'type' => 'danger',
  844. 'log' => array(__FUNCTION__, $_data_log),
  845. 'msg' => 'access_denied'
  846. );
  847. return false;
  848. }
  849. if (!ctype_alnum($_data["otp_token"]) || strlen($_data["otp_token"]) != 44) {
  850. $_SESSION['return'][] = array(
  851. 'type' => 'danger',
  852. 'log' => array(__FUNCTION__, $_data_log),
  853. 'msg' => 'tfa_token_invalid'
  854. );
  855. return false;
  856. }
  857. $yauth = $yubi->verify($_data["otp_token"]);
  858. if (PEAR::isError($yauth)) {
  859. $_SESSION['return'][] = array(
  860. 'type' => 'danger',
  861. 'log' => array(__FUNCTION__, $_data_log),
  862. 'msg' => array('yotp_verification_failed', $yauth->getMessage())
  863. );
  864. return false;
  865. }
  866. try {
  867. // We could also do a modhex translation here
  868. $yubico_modhex_id = substr($_data["otp_token"], 0, 12);
  869. $stmt = $pdo->prepare("DELETE FROM `tfa`
  870. WHERE `username` = :username
  871. AND (`authmech` != 'yubi_otp')
  872. OR (`authmech` = 'yubi_otp' AND `secret` LIKE :modhex)");
  873. $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id));
  874. $stmt = $pdo->prepare("INSERT INTO `tfa` (`key_id`, `username`, `authmech`, `active`, `secret`) VALUES
  875. (:key_id, :username, 'yubi_otp', '1', :secret)");
  876. $stmt->execute(array(':key_id' => $key_id, ':username' => $username, ':secret' => $yubico_id . ':' . $yubico_key . ':' . $yubico_modhex_id));
  877. }
  878. catch (PDOException $e) {
  879. $_SESSION['return'][] = array(
  880. 'type' => 'danger',
  881. 'log' => array(__FUNCTION__, $_data_log),
  882. 'msg' => array('mysql_error', $e)
  883. );
  884. return false;
  885. }
  886. $_SESSION['return'][] = array(
  887. 'type' => 'success',
  888. 'log' => array(__FUNCTION__, $_data_log),
  889. 'msg' => array('object_modified', htmlspecialchars($username))
  890. );
  891. break;
  892. case "u2f":
  893. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  894. try {
  895. $reg = $u2f->doRegister(json_decode($_SESSION['regReq']), json_decode($_data['token']));
  896. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username AND `authmech` != 'u2f'");
  897. $stmt->execute(array(':username' => $username));
  898. $stmt = $pdo->prepare("INSERT INTO `tfa` (`username`, `key_id`, `authmech`, `keyHandle`, `publicKey`, `certificate`, `counter`, `active`) VALUES (?, ?, 'u2f', ?, ?, ?, ?, '1')");
  899. $stmt->execute(array($username, $key_id, $reg->keyHandle, $reg->publicKey, $reg->certificate, $reg->counter));
  900. $_SESSION['return'][] = array(
  901. 'type' => 'success',
  902. 'log' => array(__FUNCTION__, $_data_log),
  903. 'msg' => array('object_modified', $username)
  904. );
  905. $_SESSION['regReq'] = null;
  906. }
  907. catch (Exception $e) {
  908. $_SESSION['return'][] = array(
  909. 'type' => 'danger',
  910. 'log' => array(__FUNCTION__, $_data_log),
  911. 'msg' => array('u2f_verification_failed', $e->getMessage())
  912. );
  913. $_SESSION['regReq'] = null;
  914. return false;
  915. }
  916. break;
  917. case "totp":
  918. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  919. if ($tfa->verifyCode($_POST['totp_secret'], $_POST['totp_confirm_token']) === true) {
  920. try {
  921. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
  922. $stmt->execute(array(':username' => $username));
  923. $stmt = $pdo->prepare("INSERT INTO `tfa` (`username`, `key_id`, `authmech`, `secret`, `active`) VALUES (?, ?, 'totp', ?, '1')");
  924. $stmt->execute(array($username, $key_id, $_POST['totp_secret']));
  925. }
  926. catch (PDOException $e) {
  927. $_SESSION['return'][] = array(
  928. 'type' => 'danger',
  929. 'log' => array(__FUNCTION__, $_data_log),
  930. 'msg' => array('mysql_error', $e)
  931. );
  932. return false;
  933. }
  934. $_SESSION['return'][] = array(
  935. 'type' => 'success',
  936. 'log' => array(__FUNCTION__, $_data_log),
  937. 'msg' => array('object_modified', $username)
  938. );
  939. }
  940. else {
  941. $_SESSION['return'][] = array(
  942. 'type' => 'danger',
  943. 'log' => array(__FUNCTION__, $_data_log),
  944. 'msg' => 'totp_verification_failed'
  945. );
  946. }
  947. break;
  948. case "none":
  949. try {
  950. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
  951. $stmt->execute(array(':username' => $username));
  952. }
  953. catch (PDOException $e) {
  954. $_SESSION['return'][] = array(
  955. 'type' => 'danger',
  956. 'log' => array(__FUNCTION__, $_data_log),
  957. 'msg' => array('mysql_error', $e)
  958. );
  959. return false;
  960. }
  961. $_SESSION['return'][] = array(
  962. 'type' => 'success',
  963. 'log' => array(__FUNCTION__, $_data_log),
  964. 'msg' => array('object_modified', htmlspecialchars($username))
  965. );
  966. break;
  967. }
  968. }
  969. function unset_tfa_key($_data) {
  970. // Can only unset own keys
  971. // Needs at least one key left
  972. global $pdo;
  973. global $lang;
  974. $_data_log = $_data;
  975. $id = intval($_data['unset_tfa_key']);
  976. $username = $_SESSION['mailcow_cc_username'];
  977. if ($_SESSION['mailcow_cc_role'] != "domainadmin" &&
  978. $_SESSION['mailcow_cc_role'] != "admin") {
  979. $_SESSION['return'][] = array(
  980. 'type' => 'danger',
  981. 'log' => array(__FUNCTION__, $_data_log),
  982. 'msg' => 'access_denied'
  983. );
  984. return false;
  985. }
  986. try {
  987. if (!is_numeric($id)) {
  988. $_SESSION['return'][] = array(
  989. 'type' => 'danger',
  990. 'log' => array(__FUNCTION__, $_data_log),
  991. 'msg' => 'access_denied'
  992. );
  993. return false;
  994. }
  995. $stmt = $pdo->prepare("SELECT COUNT(*) AS `keys` FROM `tfa`
  996. WHERE `username` = :username AND `active` = '1'");
  997. $stmt->execute(array(':username' => $username));
  998. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  999. if ($row['keys'] == "1") {
  1000. $_SESSION['return'][] = array(
  1001. 'type' => 'danger',
  1002. 'log' => array(__FUNCTION__, $_data_log),
  1003. 'msg' => 'last_key'
  1004. );
  1005. return false;
  1006. }
  1007. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username AND `id` = :id");
  1008. $stmt->execute(array(':username' => $username, ':id' => $id));
  1009. $_SESSION['return'][] = array(
  1010. 'type' => 'success',
  1011. 'log' => array(__FUNCTION__, $_data_log),
  1012. 'msg' => array('object_modified', $username)
  1013. );
  1014. }
  1015. catch (PDOException $e) {
  1016. $_SESSION['return'][] = array(
  1017. 'type' => 'danger',
  1018. 'log' => array(__FUNCTION__, $_data_log),
  1019. 'msg' => array('mysql_error', $e)
  1020. );
  1021. return false;
  1022. }
  1023. }
  1024. function get_tfa($username = null) {
  1025. global $pdo;
  1026. if (isset($_SESSION['mailcow_cc_username'])) {
  1027. $username = $_SESSION['mailcow_cc_username'];
  1028. }
  1029. elseif (empty($username)) {
  1030. return false;
  1031. }
  1032. $stmt = $pdo->prepare("SELECT * FROM `tfa`
  1033. WHERE `username` = :username AND `active` = '1'");
  1034. $stmt->execute(array(':username' => $username));
  1035. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1036. switch ($row["authmech"]) {
  1037. case "yubi_otp":
  1038. $data['name'] = "yubi_otp";
  1039. $data['pretty'] = "Yubico OTP";
  1040. $stmt = $pdo->prepare("SELECT `id`, `key_id`, RIGHT(`secret`, 12) AS 'modhex' FROM `tfa` WHERE `authmech` = 'yubi_otp' AND `username` = :username");
  1041. $stmt->execute(array(
  1042. ':username' => $username,
  1043. ));
  1044. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1045. while($row = array_shift($rows)) {
  1046. $data['additional'][] = $row;
  1047. }
  1048. return $data;
  1049. break;
  1050. case "u2f":
  1051. $data['name'] = "u2f";
  1052. $data['pretty'] = "Fido U2F";
  1053. $stmt = $pdo->prepare("SELECT `id`, `key_id` FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username");
  1054. $stmt->execute(array(
  1055. ':username' => $username,
  1056. ));
  1057. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1058. while($row = array_shift($rows)) {
  1059. $data['additional'][] = $row;
  1060. }
  1061. return $data;
  1062. break;
  1063. case "hotp":
  1064. $data['name'] = "hotp";
  1065. $data['pretty'] = "HMAC-based OTP";
  1066. return $data;
  1067. break;
  1068. case "totp":
  1069. $data['name'] = "totp";
  1070. $data['pretty'] = "Time-based OTP";
  1071. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `secret` FROM `tfa` WHERE `authmech` = 'totp' AND `username` = :username");
  1072. $stmt->execute(array(
  1073. ':username' => $username,
  1074. ));
  1075. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1076. while($row = array_shift($rows)) {
  1077. $data['additional'][] = $row;
  1078. }
  1079. return $data;
  1080. break;
  1081. default:
  1082. $data['name'] = 'none';
  1083. $data['pretty'] = "-";
  1084. return $data;
  1085. break;
  1086. }
  1087. }
  1088. function verify_tfa_login($username, $token) {
  1089. global $pdo;
  1090. global $lang;
  1091. global $yubi;
  1092. global $u2f;
  1093. global $tfa;
  1094. $stmt = $pdo->prepare("SELECT `authmech` FROM `tfa`
  1095. WHERE `username` = :username AND `active` = '1'");
  1096. $stmt->execute(array(':username' => $username));
  1097. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1098. switch ($row["authmech"]) {
  1099. case "yubi_otp":
  1100. if (!ctype_alnum($token) || strlen($token) != 44) {
  1101. $_SESSION['return'][] = array(
  1102. 'type' => 'danger',
  1103. 'log' => array(__FUNCTION__, $username, '*'),
  1104. 'msg' => array('yotp_verification_failed', 'token length error')
  1105. );
  1106. return false;
  1107. }
  1108. $yubico_modhex_id = substr($token, 0, 12);
  1109. $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
  1110. WHERE `username` = :username
  1111. AND `authmech` = 'yubi_otp'
  1112. AND `active`='1'
  1113. AND `secret` LIKE :modhex");
  1114. $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id));
  1115. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1116. $yubico_auth = explode(':', $row['secret']);
  1117. $yubi = new Auth_Yubico($yubico_auth[0], $yubico_auth[1]);
  1118. $yauth = $yubi->verify($token);
  1119. if (PEAR::isError($yauth)) {
  1120. $_SESSION['return'][] = array(
  1121. 'type' => 'danger',
  1122. 'log' => array(__FUNCTION__, $username, '*'),
  1123. 'msg' => array('yotp_verification_failed', $yauth->getMessage())
  1124. );
  1125. return false;
  1126. }
  1127. else {
  1128. $_SESSION['tfa_id'] = $row['id'];
  1129. $_SESSION['return'][] = array(
  1130. 'type' => 'success',
  1131. 'log' => array(__FUNCTION__, $username, '*'),
  1132. 'msg' => 'verified_yotp_login'
  1133. );
  1134. return true;
  1135. }
  1136. $_SESSION['return'][] = array(
  1137. 'type' => 'danger',
  1138. 'log' => array(__FUNCTION__, $username, '*'),
  1139. 'msg' => array('yotp_verification_failed', 'unknown')
  1140. );
  1141. return false;
  1142. break;
  1143. case "u2f":
  1144. try {
  1145. $reg = $u2f->doAuthenticate(json_decode($_SESSION['authReq']), get_u2f_registrations($username), json_decode($token));
  1146. $stmt = $pdo->prepare("SELECT `id` FROM `tfa` WHERE `keyHandle` = ?");
  1147. $stmt->execute(array($reg->keyHandle));
  1148. $row_key_id = $stmt->fetch(PDO::FETCH_ASSOC);
  1149. $_SESSION['tfa_id'] = $row_key_id['id'];
  1150. $_SESSION['authReq'] = null;
  1151. $_SESSION['return'][] = array(
  1152. 'type' => 'success',
  1153. 'log' => array(__FUNCTION__, $username, '*'),
  1154. 'msg' => 'verified_u2f_login'
  1155. );
  1156. return true;
  1157. }
  1158. catch (Exception $e) {
  1159. $_SESSION['return'][] = array(
  1160. 'type' => 'danger',
  1161. 'log' => array(__FUNCTION__, $username, '*'),
  1162. 'msg' => array('u2f_verification_failed', $e->getMessage())
  1163. );
  1164. $_SESSION['regReq'] = null;
  1165. return false;
  1166. }
  1167. $_SESSION['return'][] = array(
  1168. 'type' => 'danger',
  1169. 'log' => array(__FUNCTION__, $username, '*'),
  1170. 'msg' => array('u2f_verification_failed', 'unknown')
  1171. );
  1172. return false;
  1173. break;
  1174. case "hotp":
  1175. return false;
  1176. break;
  1177. case "totp":
  1178. try {
  1179. $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
  1180. WHERE `username` = :username
  1181. AND `authmech` = 'totp'
  1182. AND `active`='1'");
  1183. $stmt->execute(array(':username' => $username));
  1184. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1185. if ($tfa->verifyCode($row['secret'], $_POST['token']) === true) {
  1186. $_SESSION['tfa_id'] = $row['id'];
  1187. $_SESSION['return'][] = array(
  1188. 'type' => 'success',
  1189. 'log' => array(__FUNCTION__, $username, '*'),
  1190. 'msg' => 'verified_totp_login'
  1191. );
  1192. return true;
  1193. }
  1194. $_SESSION['return'][] = array(
  1195. 'type' => 'danger',
  1196. 'log' => array(__FUNCTION__, $username, '*'),
  1197. 'msg' => 'totp_verification_failed'
  1198. );
  1199. return false;
  1200. }
  1201. catch (PDOException $e) {
  1202. $_SESSION['return'][] = array(
  1203. 'type' => 'danger',
  1204. 'log' => array(__FUNCTION__, $username, '*'),
  1205. 'msg' => array('mysql_error', $e)
  1206. );
  1207. return false;
  1208. }
  1209. break;
  1210. default:
  1211. $_SESSION['return'][] = array(
  1212. 'type' => 'danger',
  1213. 'log' => array(__FUNCTION__, $username, '*'),
  1214. 'msg' => 'unknown_tfa_method'
  1215. );
  1216. return false;
  1217. break;
  1218. }
  1219. return false;
  1220. }
  1221. function admin_api($access, $action, $data = null) {
  1222. global $pdo;
  1223. global $lang;
  1224. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1225. $_SESSION['return'][] = array(
  1226. 'type' => 'danger',
  1227. 'log' => array(__FUNCTION__),
  1228. 'msg' => 'access_denied'
  1229. );
  1230. return false;
  1231. }
  1232. if ($access !== "ro" && $access !== "rw") {
  1233. $_SESSION['return'][] = array(
  1234. 'type' => 'danger',
  1235. 'log' => array(__FUNCTION__),
  1236. 'msg' => 'invalid access type'
  1237. );
  1238. return false;
  1239. }
  1240. if ($action == "edit") {
  1241. $active = (!empty($data['active'])) ? 1 : 0;
  1242. $skip_ip_check = (isset($data['skip_ip_check'])) ? 1 : 0;
  1243. $allow_from = array_map('trim', preg_split( "/( |,|;|\n)/", $data['allow_from']));
  1244. foreach ($allow_from as $key => $val) {
  1245. if (empty($val)) {
  1246. unset($allow_from[$key]);
  1247. continue;
  1248. }
  1249. if (valid_network($val) !== true) {
  1250. $_SESSION['return'][] = array(
  1251. 'type' => 'warning',
  1252. 'log' => array(__FUNCTION__, $data),
  1253. 'msg' => array('ip_invalid', htmlspecialchars($allow_from[$key]))
  1254. );
  1255. unset($allow_from[$key]);
  1256. continue;
  1257. }
  1258. }
  1259. $allow_from = implode(',', array_unique(array_filter($allow_from)));
  1260. if (empty($allow_from) && $skip_ip_check == 0) {
  1261. $_SESSION['return'][] = array(
  1262. 'type' => 'danger',
  1263. 'log' => array(__FUNCTION__, $data),
  1264. 'msg' => 'ip_list_empty'
  1265. );
  1266. return false;
  1267. }
  1268. $api_key = implode('-', array(
  1269. strtoupper(bin2hex(random_bytes(3))),
  1270. strtoupper(bin2hex(random_bytes(3))),
  1271. strtoupper(bin2hex(random_bytes(3))),
  1272. strtoupper(bin2hex(random_bytes(3))),
  1273. strtoupper(bin2hex(random_bytes(3)))
  1274. ));
  1275. $stmt = $pdo->query("SELECT `api_key` FROM `api` WHERE `access` = '" . $access . "'");
  1276. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  1277. if (empty($num_results)) {
  1278. $stmt = $pdo->prepare("INSERT INTO `api` (`api_key`, `skip_ip_check`, `active`, `allow_from`, `access`)
  1279. VALUES (:api_key, :skip_ip_check, :active, :allow_from, :access);");
  1280. $stmt->execute(array(
  1281. ':api_key' => $api_key,
  1282. ':skip_ip_check' => $skip_ip_check,
  1283. ':active' => $active,
  1284. ':allow_from' => $allow_from,
  1285. ':access' => $access
  1286. ));
  1287. }
  1288. else {
  1289. if ($skip_ip_check == 0) {
  1290. $stmt = $pdo->prepare("UPDATE `api` SET `skip_ip_check` = :skip_ip_check,
  1291. `active` = :active,
  1292. `allow_from` = :allow_from
  1293. WHERE `access` = :access;");
  1294. $stmt->execute(array(
  1295. ':active' => $active,
  1296. ':skip_ip_check' => $skip_ip_check,
  1297. ':allow_from' => $allow_from,
  1298. ':access' => $access
  1299. ));
  1300. }
  1301. else {
  1302. $stmt = $pdo->prepare("UPDATE `api` SET `skip_ip_check` = :skip_ip_check,
  1303. `active` = :active
  1304. WHERE `access` = :access;");
  1305. $stmt->execute(array(
  1306. ':active' => $active,
  1307. ':skip_ip_check' => $skip_ip_check,
  1308. ':access' => $access
  1309. ));
  1310. }
  1311. }
  1312. }
  1313. elseif ($action == "regen_key") {
  1314. $api_key = implode('-', array(
  1315. strtoupper(bin2hex(random_bytes(3))),
  1316. strtoupper(bin2hex(random_bytes(3))),
  1317. strtoupper(bin2hex(random_bytes(3))),
  1318. strtoupper(bin2hex(random_bytes(3))),
  1319. strtoupper(bin2hex(random_bytes(3)))
  1320. ));
  1321. $stmt = $pdo->prepare("UPDATE `api` SET `api_key` = :api_key WHERE `access` = :access");
  1322. $stmt->execute(array(
  1323. ':api_key' => $api_key,
  1324. ':access' => $access
  1325. ));
  1326. }
  1327. elseif ($action == "get") {
  1328. $stmt = $pdo->query("SELECT * FROM `api` WHERE `access` = '" . $access . "'");
  1329. $apidata = $stmt->fetch(PDO::FETCH_ASSOC);
  1330. $apidata['allow_from'] = str_replace(',', PHP_EOL, $apidata['allow_from']);
  1331. return $apidata;
  1332. }
  1333. $_SESSION['return'][] = array(
  1334. 'type' => 'success',
  1335. 'log' => array(__FUNCTION__, $data),
  1336. 'msg' => 'admin_api_modified'
  1337. );
  1338. }
  1339. function license($action, $data = null) {
  1340. global $pdo;
  1341. global $redis;
  1342. global $lang;
  1343. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1344. $_SESSION['return'][] = array(
  1345. 'type' => 'danger',
  1346. 'log' => array(__FUNCTION__),
  1347. 'msg' => 'access_denied'
  1348. );
  1349. return false;
  1350. }
  1351. switch ($action) {
  1352. case "verify":
  1353. // Keep result until revalidate button is pressed or session expired
  1354. $stmt = $pdo->query("SELECT `version` FROM `versions` WHERE `application` = 'GUID'");
  1355. $versions = $stmt->fetch(PDO::FETCH_ASSOC);
  1356. $post = array('guid' => $versions['version']);
  1357. $curl = curl_init('https://verify.mailcow.email');
  1358. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  1359. curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
  1360. curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
  1361. $response = curl_exec($curl);
  1362. curl_close($curl);
  1363. $json_return = json_decode($response, true);
  1364. if ($response && $json_return) {
  1365. if ($json_return['response'] === "ok") {
  1366. $_SESSION['gal']['valid'] = "true";
  1367. $_SESSION['gal']['c'] = $json_return['c'];
  1368. $_SESSION['gal']['s'] = $json_return['s'];
  1369. if ($json_return['m'] == 'NoMoore') {
  1370. $_SESSION['gal']['m'] = '🐄';
  1371. }
  1372. else {
  1373. $_SESSION['gal']['m'] = str_repeat('🐄', substr_count($json_return['m'], 'o'));
  1374. }
  1375. }
  1376. elseif ($json_return['response'] === "invalid") {
  1377. $_SESSION['gal']['valid'] = "false";
  1378. $_SESSION['gal']['c'] = $lang['mailbox']['no'];
  1379. $_SESSION['gal']['s'] = $lang['mailbox']['no'];
  1380. $_SESSION['gal']['m'] = $lang['mailbox']['no'];
  1381. }
  1382. }
  1383. else {
  1384. $_SESSION['gal']['valid'] = "false";
  1385. $_SESSION['gal']['c'] = $lang['danger']['temp_error'];
  1386. $_SESSION['gal']['s'] = $lang['danger']['temp_error'];
  1387. $_SESSION['gal']['m'] = $lang['danger']['temp_error'];
  1388. }
  1389. try {
  1390. // json_encode needs "true"/"false" instead of true/false, to not encode it to 0 or 1
  1391. $redis->Set('LICENSE_STATUS_CACHE', json_encode($_SESSION['gal']));
  1392. }
  1393. catch (RedisException $e) {
  1394. $_SESSION['return'][] = array(
  1395. 'type' => 'danger',
  1396. 'log' => array(__FUNCTION__, $_action, $_data_log),
  1397. 'msg' => array('redis_error', $e)
  1398. );
  1399. return false;
  1400. }
  1401. return $_SESSION['gal']['valid'];
  1402. break;
  1403. case "guid":
  1404. $stmt = $pdo->query("SELECT `version` FROM `versions` WHERE `application` = 'GUID'");
  1405. $versions = $stmt->fetch(PDO::FETCH_ASSOC);
  1406. return $versions['version'];
  1407. break;
  1408. }
  1409. }
  1410. function rspamd_ui($action, $data = null) {
  1411. global $lang;
  1412. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1413. $_SESSION['return'][] = array(
  1414. 'type' => 'danger',
  1415. 'log' => array(__FUNCTION__),
  1416. 'msg' => 'access_denied'
  1417. );
  1418. return false;
  1419. }
  1420. switch ($action) {
  1421. case "edit":
  1422. $rspamd_ui_pass = $data['rspamd_ui_pass'];
  1423. $rspamd_ui_pass2 = $data['rspamd_ui_pass2'];
  1424. if (empty($rspamd_ui_pass) || empty($rspamd_ui_pass2)) {
  1425. $_SESSION['return'][] = array(
  1426. 'type' => 'danger',
  1427. 'log' => array(__FUNCTION__, '*', '*'),
  1428. 'msg' => 'password_empty'
  1429. );
  1430. return false;
  1431. }
  1432. if ($rspamd_ui_pass != $rspamd_ui_pass2) {
  1433. $_SESSION['return'][] = array(
  1434. 'type' => 'danger',
  1435. 'log' => array(__FUNCTION__, '*', '*'),
  1436. 'msg' => 'password_mismatch'
  1437. );
  1438. return false;
  1439. }
  1440. if (strlen($rspamd_ui_pass) < 6) {
  1441. $_SESSION['return'][] = array(
  1442. 'type' => 'danger',
  1443. 'log' => array(__FUNCTION__, '*', '*'),
  1444. 'msg' => 'rspamd_ui_pw_length'
  1445. );
  1446. return false;
  1447. }
  1448. $docker_return = docker('post', 'rspamd-mailcow', 'exec', array('cmd' => 'rspamd', 'task' => 'worker_password', 'raw' => $rspamd_ui_pass), array('Content-Type: application/json'));
  1449. if ($docker_return_array = json_decode($docker_return, true)) {
  1450. if ($docker_return_array['type'] == 'success') {
  1451. $_SESSION['return'][] = array(
  1452. 'type' => 'success',
  1453. 'log' => array(__FUNCTION__, '*', '*'),
  1454. 'msg' => 'rspamd_ui_pw_set'
  1455. );
  1456. return true;
  1457. }
  1458. else {
  1459. $_SESSION['return'][] = array(
  1460. 'type' => $docker_return_array['type'],
  1461. 'log' => array(__FUNCTION__, '*', '*'),
  1462. 'msg' => $docker_return_array['msg']
  1463. );
  1464. return false;
  1465. }
  1466. }
  1467. else {
  1468. $_SESSION['return'][] = array(
  1469. 'type' => 'danger',
  1470. 'log' => array(__FUNCTION__, '*', '*'),
  1471. 'msg' => 'unknown'
  1472. );
  1473. return false;
  1474. }
  1475. break;
  1476. }
  1477. }
  1478. function get_u2f_registrations($username) {
  1479. global $pdo;
  1480. $sel = $pdo->prepare("SELECT * FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = ? AND `active` = '1'");
  1481. $sel->execute(array($username));
  1482. return $sel->fetchAll(PDO::FETCH_OBJ);
  1483. }
  1484. function get_logs($application, $lines = false) {
  1485. if ($lines === false) {
  1486. $lines = $GLOBALS['LOG_LINES'] - 1;
  1487. }
  1488. elseif(is_numeric($lines) && $lines >= 1) {
  1489. $lines = abs(intval($lines) - 1);
  1490. }
  1491. else {
  1492. list ($from, $to) = explode('-', $lines);
  1493. $from = intval($from);
  1494. $to = intval($to);
  1495. if ($from < 1 || $to < $from) { return false; }
  1496. }
  1497. global $lang;
  1498. global $redis;
  1499. global $pdo;
  1500. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1501. return false;
  1502. }
  1503. // SQL
  1504. if ($application == "mailcow-ui") {
  1505. if (isset($from) && isset($to)) {
  1506. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :from, :to");
  1507. $stmt->execute(array(
  1508. ':from' => $from - 1,
  1509. ':to' => $to
  1510. ));
  1511. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1512. }
  1513. else {
  1514. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :lines");
  1515. $stmt->execute(array(
  1516. ':lines' => $lines + 1,
  1517. ));
  1518. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1519. }
  1520. if (is_array($data)) {
  1521. return $data;
  1522. }
  1523. }
  1524. // Redis
  1525. if ($application == "dovecot-mailcow") {
  1526. if (isset($from) && isset($to)) {
  1527. $data = $redis->lRange('DOVECOT_MAILLOG', $from - 1, $to - 1);
  1528. }
  1529. else {
  1530. $data = $redis->lRange('DOVECOT_MAILLOG', 0, $lines);
  1531. }
  1532. if ($data) {
  1533. foreach ($data as $json_line) {
  1534. $data_array[] = json_decode($json_line, true);
  1535. }
  1536. return $data_array;
  1537. }
  1538. }
  1539. if ($application == "postfix-mailcow") {
  1540. if (isset($from) && isset($to)) {
  1541. $data = $redis->lRange('POSTFIX_MAILLOG', $from - 1, $to - 1);
  1542. }
  1543. else {
  1544. $data = $redis->lRange('POSTFIX_MAILLOG', 0, $lines);
  1545. }
  1546. if ($data) {
  1547. foreach ($data as $json_line) {
  1548. $data_array[] = json_decode($json_line, true);
  1549. }
  1550. return $data_array;
  1551. }
  1552. }
  1553. if ($application == "sogo-mailcow") {
  1554. if (isset($from) && isset($to)) {
  1555. $data = $redis->lRange('SOGO_LOG', $from - 1, $to - 1);
  1556. }
  1557. else {
  1558. $data = $redis->lRange('SOGO_LOG', 0, $lines);
  1559. }
  1560. if ($data) {
  1561. foreach ($data as $json_line) {
  1562. $data_array[] = json_decode($json_line, true);
  1563. }
  1564. return $data_array;
  1565. }
  1566. }
  1567. if ($application == "watchdog-mailcow") {
  1568. if (isset($from) && isset($to)) {
  1569. $data = $redis->lRange('WATCHDOG_LOG', $from - 1, $to - 1);
  1570. }
  1571. else {
  1572. $data = $redis->lRange('WATCHDOG_LOG', 0, $lines);
  1573. }
  1574. if ($data) {
  1575. foreach ($data as $json_line) {
  1576. $data_array[] = json_decode($json_line, true);
  1577. }
  1578. return $data_array;
  1579. }
  1580. }
  1581. if ($application == "acme-mailcow") {
  1582. if (isset($from) && isset($to)) {
  1583. $data = $redis->lRange('ACME_LOG', $from - 1, $to - 1);
  1584. }
  1585. else {
  1586. $data = $redis->lRange('ACME_LOG', 0, $lines);
  1587. }
  1588. if ($data) {
  1589. foreach ($data as $json_line) {
  1590. $data_array[] = json_decode($json_line, true);
  1591. }
  1592. return $data_array;
  1593. }
  1594. }
  1595. if ($application == "ratelimited") {
  1596. if (isset($from) && isset($to)) {
  1597. $data = $redis->lRange('RL_LOG', $from - 1, $to - 1);
  1598. }
  1599. else {
  1600. $data = $redis->lRange('RL_LOG', 0, $lines);
  1601. }
  1602. if ($data) {
  1603. foreach ($data as $json_line) {
  1604. $data_array[] = json_decode($json_line, true);
  1605. }
  1606. return $data_array;
  1607. }
  1608. }
  1609. if ($application == "api-mailcow") {
  1610. if (isset($from) && isset($to)) {
  1611. $data = $redis->lRange('API_LOG', $from - 1, $to - 1);
  1612. }
  1613. else {
  1614. $data = $redis->lRange('API_LOG', 0, $lines);
  1615. }
  1616. if ($data) {
  1617. foreach ($data as $json_line) {
  1618. $data_array[] = json_decode($json_line, true);
  1619. }
  1620. return $data_array;
  1621. }
  1622. }
  1623. if ($application == "netfilter-mailcow") {
  1624. if (isset($from) && isset($to)) {
  1625. $data = $redis->lRange('NETFILTER_LOG', $from - 1, $to - 1);
  1626. }
  1627. else {
  1628. $data = $redis->lRange('NETFILTER_LOG', 0, $lines);
  1629. }
  1630. if ($data) {
  1631. foreach ($data as $json_line) {
  1632. $data_array[] = json_decode($json_line, true);
  1633. }
  1634. return $data_array;
  1635. }
  1636. }
  1637. if ($application == "autodiscover-mailcow") {
  1638. if (isset($from) && isset($to)) {
  1639. $data = $redis->lRange('AUTODISCOVER_LOG', $from - 1, $to - 1);
  1640. }
  1641. else {
  1642. $data = $redis->lRange('AUTODISCOVER_LOG', 0, $lines);
  1643. }
  1644. if ($data) {
  1645. foreach ($data as $json_line) {
  1646. $data_array[] = json_decode($json_line, true);
  1647. }
  1648. return $data_array;
  1649. }
  1650. }
  1651. if ($application == "rspamd-history") {
  1652. $curl = curl_init();
  1653. curl_setopt($curl, CURLOPT_UNIX_SOCKET_PATH, '/var/lib/rspamd/rspamd.sock');
  1654. if (!is_numeric($lines)) {
  1655. list ($from, $to) = explode('-', $lines);
  1656. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?from=" . intval($from) . "&to=" . intval($to));
  1657. }
  1658. else {
  1659. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?to=" . intval($lines));
  1660. }
  1661. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  1662. $history = curl_exec($curl);
  1663. if (!curl_errno($curl)) {
  1664. $data_array = json_decode($history, true);
  1665. curl_close($curl);
  1666. return $data_array['rows'];
  1667. }
  1668. curl_close($curl);
  1669. return false;
  1670. }
  1671. return false;
  1672. }
  1673. function getGUID() {
  1674. if (function_exists('com_create_guid')) {
  1675. return com_create_guid();
  1676. }
  1677. mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
  1678. $charid = strtoupper(md5(uniqid(rand(), true)));
  1679. $hyphen = chr(45);// "-"
  1680. return substr($charid, 0, 8).$hyphen
  1681. .substr($charid, 8, 4).$hyphen
  1682. .substr($charid,12, 4).$hyphen
  1683. .substr($charid,16, 4).$hyphen
  1684. .substr($charid,20,12);
  1685. }
  1686. function solr_status() {
  1687. $curl = curl_init();
  1688. $endpoint = 'http://solr:8983/solr/admin/cores';
  1689. $params = array(
  1690. 'action' => 'STATUS',
  1691. 'core' => 'dovecot-fts',
  1692. 'indexInfo' => 'true'
  1693. );
  1694. $url = $endpoint . '?' . http_build_query($params);
  1695. curl_setopt($curl, CURLOPT_URL, $url);
  1696. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  1697. curl_setopt($curl, CURLOPT_POST, 0);
  1698. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  1699. $response_core = curl_exec($curl);
  1700. if ($response_core === false) {
  1701. $err = curl_error($curl);
  1702. curl_close($curl);
  1703. return false;
  1704. }
  1705. else {
  1706. curl_close($curl);
  1707. $curl = curl_init();
  1708. $status_core = json_decode($response_core, true);
  1709. $url = 'http://solr:8983/solr/admin/info/system';
  1710. curl_setopt($curl, CURLOPT_URL, $url);
  1711. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  1712. curl_setopt($curl, CURLOPT_POST, 0);
  1713. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  1714. $response_sysinfo = curl_exec($curl);
  1715. if ($response_sysinfo === false) {
  1716. $err = curl_error($curl);
  1717. curl_close($curl);
  1718. return false;
  1719. }
  1720. else {
  1721. curl_close($curl);
  1722. $status_sysinfo = json_decode($response_sysinfo, true);
  1723. $status = array_merge($status_core, $status_sysinfo);
  1724. return (!empty($status['status']['dovecot-fts']) && !empty($status['jvm']['memory'])) ? $status : false;
  1725. }
  1726. return (!empty($status['status']['dovecot-fts'])) ? $status['status']['dovecot-fts'] : false;
  1727. }
  1728. return false;
  1729. }
  1730. function cleanupJS($ignore = '', $folder = '/tmp/*.js') {
  1731. $now = time();
  1732. foreach (glob($folder) as $filename) {
  1733. if(strpos($filename, $ignore) !== false) {
  1734. continue;
  1735. }
  1736. if (is_file($filename)) {
  1737. if ($now - filemtime($filename) >= 60 * 60) {
  1738. unlink($filename);
  1739. }
  1740. }
  1741. }
  1742. }
  1743. function cleanupCSS($ignore = '', $folder = '/tmp/*.css') {
  1744. $now = time();
  1745. foreach (glob($folder) as $filename) {
  1746. if(strpos($filename, $ignore) !== false) {
  1747. continue;
  1748. }
  1749. if (is_file($filename)) {
  1750. if ($now - filemtime($filename) >= 60 * 60) {
  1751. unlink($filename);
  1752. }
  1753. }
  1754. }
  1755. }
  1756. ?>