functions.inc.php 61 KB

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