functions.inc.php 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759
  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. global $pdo;
  556. global $lang;
  557. $stmt = $pdo->query("SELECT 'OK' FROM INFORMATION_SCHEMA.TABLES
  558. WHERE TABLE_NAME = 'sogo_view'");
  559. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  560. if ($num_results != 0) {
  561. $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`)
  562. SELECT `c_uid`, `domain`, `c_name`, `c_password`, `c_cn`, `mail`, `aliases`, `ad_aliases`, `ext_acl`, `kind`, `multiple_bookings` from sogo_view");
  563. $stmt = $pdo->query("DELETE FROM _sogo_static_view WHERE `c_uid` NOT IN (SELECT `username` FROM `mailbox` WHERE `active` = '1');");
  564. }
  565. flush_memcached();
  566. }
  567. function edit_user_account($_data) {
  568. global $lang;
  569. global $pdo;
  570. $_data_log = $_data;
  571. !isset($_data_log['user_new_pass']) ?: $_data_log['user_new_pass'] = '*';
  572. !isset($_data_log['user_new_pass2']) ?: $_data_log['user_new_pass2'] = '*';
  573. !isset($_data_log['user_old_pass']) ?: $_data_log['user_old_pass'] = '*';
  574. $username = $_SESSION['mailcow_cc_username'];
  575. $role = $_SESSION['mailcow_cc_role'];
  576. $password_old = $_data['user_old_pass'];
  577. if (filter_var($username, FILTER_VALIDATE_EMAIL === false) || $role != 'user') {
  578. $_SESSION['return'][] = array(
  579. 'type' => 'danger',
  580. 'log' => array(__FUNCTION__, $_data_log),
  581. 'msg' => 'access_denied'
  582. );
  583. return false;
  584. }
  585. if (isset($_data['user_new_pass']) && isset($_data['user_new_pass2'])) {
  586. $password_new = $_data['user_new_pass'];
  587. $password_new2 = $_data['user_new_pass2'];
  588. }
  589. $stmt = $pdo->prepare("SELECT `password` FROM `mailbox`
  590. WHERE `kind` NOT REGEXP 'location|thing|group'
  591. AND `username` = :user");
  592. $stmt->execute(array(':user' => $username));
  593. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  594. if (!verify_hash($row['password'], $password_old)) {
  595. $_SESSION['return'][] = array(
  596. 'type' => 'danger',
  597. 'log' => array(__FUNCTION__, $_data_log),
  598. 'msg' => 'access_denied'
  599. );
  600. return false;
  601. }
  602. if (isset($password_new) && isset($password_new2)) {
  603. if (!empty($password_new2) && !empty($password_new)) {
  604. if ($password_new2 != $password_new) {
  605. $_SESSION['return'][] = array(
  606. 'type' => 'danger',
  607. 'log' => array(__FUNCTION__, $_data_log),
  608. 'msg' => 'password_mismatch'
  609. );
  610. return false;
  611. }
  612. if (!preg_match('/' . $GLOBALS['PASSWD_REGEP'] . '/', $password_new)) {
  613. $_SESSION['return'][] = array(
  614. 'type' => 'danger',
  615. 'log' => array(__FUNCTION__, $_data_log),
  616. 'msg' => 'password_complexity'
  617. );
  618. return false;
  619. }
  620. $password_hashed = hash_password($password_new);
  621. try {
  622. $stmt = $pdo->prepare("UPDATE `mailbox` SET `password` = :password_hashed, `attributes` = JSON_SET(`attributes`, '$.force_pw_update', '0') WHERE `username` = :username");
  623. $stmt->execute(array(
  624. ':password_hashed' => $password_hashed,
  625. ':username' => $username
  626. ));
  627. }
  628. catch (PDOException $e) {
  629. $_SESSION['return'][] = array(
  630. 'type' => 'danger',
  631. 'log' => array(__FUNCTION__, $_data_log),
  632. 'msg' => array('mysql_error', $e)
  633. );
  634. return false;
  635. }
  636. }
  637. }
  638. update_sogo_static_view();
  639. $_SESSION['return'][] = array(
  640. 'type' => 'success',
  641. 'log' => array(__FUNCTION__, $_data_log),
  642. 'msg' => array('mailbox_modified', htmlspecialchars($username))
  643. );
  644. }
  645. function user_get_alias_details($username) {
  646. global $lang;
  647. global $pdo;
  648. $data['direct_aliases'] = false;
  649. $data['shared_aliases'] = false;
  650. if ($_SESSION['mailcow_cc_role'] == "user") {
  651. $username = $_SESSION['mailcow_cc_username'];
  652. }
  653. if (!filter_var($username, FILTER_VALIDATE_EMAIL)) {
  654. return false;
  655. }
  656. $data['address'] = $username;
  657. $stmt = $pdo->prepare("SELECT `address` AS `shared_aliases`, `public_comment` FROM `alias`
  658. WHERE `goto` REGEXP :username_goto
  659. AND `address` NOT LIKE '@%'
  660. AND `goto` != :username_goto2
  661. AND `address` != :username_address");
  662. $stmt->execute(array(
  663. ':username_goto' => '(^|,)'.$username.'($|,)',
  664. ':username_goto2' => $username,
  665. ':username_address' => $username
  666. ));
  667. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  668. while ($row = array_shift($run)) {
  669. $data['shared_aliases'][$row['shared_aliases']]['public_comment'] = htmlspecialchars($row['public_comment']);
  670. //$data['shared_aliases'][] = $row['shared_aliases'];
  671. }
  672. $stmt = $pdo->prepare("SELECT `address` AS `direct_aliases`, `public_comment` FROM `alias`
  673. WHERE `goto` = :username_goto
  674. AND `address` NOT LIKE '@%'
  675. AND `address` != :username_address");
  676. $stmt->execute(
  677. array(
  678. ':username_goto' => $username,
  679. ':username_address' => $username
  680. ));
  681. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  682. while ($row = array_shift($run)) {
  683. $data['direct_aliases'][$row['direct_aliases']]['public_comment'] = htmlspecialchars($row['public_comment']);
  684. }
  685. $stmt = $pdo->prepare("SELECT CONCAT(local_part, '@', alias_domain) AS `ad_alias`, `alias_domain` FROM `mailbox`
  686. LEFT OUTER JOIN `alias_domain` on `target_domain` = `domain`
  687. WHERE `username` = :username ;");
  688. $stmt->execute(array(':username' => $username));
  689. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  690. while ($row = array_shift($run)) {
  691. if (empty($row['ad_alias'])) {
  692. continue;
  693. }
  694. $data['direct_aliases'][$row['ad_alias']]['public_comment'] = '↪ ' . $row['alias_domain'];
  695. }
  696. $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 '@%';");
  697. $stmt->execute(array(':username' => $username));
  698. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  699. while ($row = array_shift($run)) {
  700. $data['aliases_also_send_as'] = $row['send_as'];
  701. }
  702. $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 '@%';");
  703. $stmt->execute(array(':username' => $username));
  704. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  705. while ($row = array_shift($run)) {
  706. $data['aliases_send_as_all'] = $row['send_as'];
  707. }
  708. $stmt = $pdo->prepare("SELECT IFNULL(GROUP_CONCAT(`address` SEPARATOR ', '), '&#10008;') as `address` FROM `alias` WHERE `goto` REGEXP :username AND `address` LIKE '@%';");
  709. $stmt->execute(array(':username' => '(^|,)'.$username.'($|,)'));
  710. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  711. while ($row = array_shift($run)) {
  712. $data['is_catch_all'] = $row['address'];
  713. }
  714. return $data;
  715. }
  716. function is_valid_domain_name($domain_name) {
  717. if (empty($domain_name)) {
  718. return false;
  719. }
  720. $domain_name = idn_to_ascii($domain_name, 0, INTL_IDNA_VARIANT_UTS46);
  721. return (preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $domain_name)
  722. && preg_match("/^.{1,253}$/", $domain_name)
  723. && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $domain_name));
  724. }
  725. function set_tfa($_data) {
  726. global $lang;
  727. global $pdo;
  728. global $yubi;
  729. global $u2f;
  730. global $tfa;
  731. $_data_log = $_data;
  732. !isset($_data_log['confirm_password']) ?: $_data_log['confirm_password'] = '*';
  733. $username = $_SESSION['mailcow_cc_username'];
  734. if ($_SESSION['mailcow_cc_role'] != "domainadmin" &&
  735. $_SESSION['mailcow_cc_role'] != "admin") {
  736. $_SESSION['return'][] = array(
  737. 'type' => 'danger',
  738. 'log' => array(__FUNCTION__, $_data_log),
  739. 'msg' => 'access_denied'
  740. );
  741. return false;
  742. }
  743. $stmt = $pdo->prepare("SELECT `password` FROM `admin`
  744. WHERE `username` = :user");
  745. $stmt->execute(array(':user' => $username));
  746. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  747. if (!verify_hash($row['password'], $_data["confirm_password"])) {
  748. $_SESSION['return'][] = array(
  749. 'type' => 'danger',
  750. 'log' => array(__FUNCTION__, $_data_log),
  751. 'msg' => 'access_denied'
  752. );
  753. return false;
  754. }
  755. switch ($_data["tfa_method"]) {
  756. case "yubi_otp":
  757. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  758. $yubico_id = $_data['yubico_id'];
  759. $yubico_key = $_data['yubico_key'];
  760. $yubi = new Auth_Yubico($yubico_id, $yubico_key);
  761. if (!$yubi) {
  762. $_SESSION['return'][] = array(
  763. 'type' => 'danger',
  764. 'log' => array(__FUNCTION__, $_data_log),
  765. 'msg' => 'access_denied'
  766. );
  767. return false;
  768. }
  769. if (!ctype_alnum($_data["otp_token"]) || strlen($_data["otp_token"]) != 44) {
  770. $_SESSION['return'][] = array(
  771. 'type' => 'danger',
  772. 'log' => array(__FUNCTION__, $_data_log),
  773. 'msg' => 'tfa_token_invalid'
  774. );
  775. return false;
  776. }
  777. $yauth = $yubi->verify($_data["otp_token"]);
  778. if (PEAR::isError($yauth)) {
  779. $_SESSION['return'][] = array(
  780. 'type' => 'danger',
  781. 'log' => array(__FUNCTION__, $_data_log),
  782. 'msg' => array('yotp_verification_failed', $yauth->getMessage())
  783. );
  784. return false;
  785. }
  786. try {
  787. // We could also do a modhex translation here
  788. $yubico_modhex_id = substr($_data["otp_token"], 0, 12);
  789. $stmt = $pdo->prepare("DELETE FROM `tfa`
  790. WHERE `username` = :username
  791. AND (`authmech` != 'yubi_otp')
  792. OR (`authmech` = 'yubi_otp' AND `secret` LIKE :modhex)");
  793. $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id));
  794. $stmt = $pdo->prepare("INSERT INTO `tfa` (`key_id`, `username`, `authmech`, `active`, `secret`) VALUES
  795. (:key_id, :username, 'yubi_otp', '1', :secret)");
  796. $stmt->execute(array(':key_id' => $key_id, ':username' => $username, ':secret' => $yubico_id . ':' . $yubico_key . ':' . $yubico_modhex_id));
  797. }
  798. catch (PDOException $e) {
  799. $_SESSION['return'][] = array(
  800. 'type' => 'danger',
  801. 'log' => array(__FUNCTION__, $_data_log),
  802. 'msg' => array('mysql_error', $e)
  803. );
  804. return false;
  805. }
  806. $_SESSION['return'][] = array(
  807. 'type' => 'success',
  808. 'log' => array(__FUNCTION__, $_data_log),
  809. 'msg' => array('object_modified', htmlspecialchars($username))
  810. );
  811. break;
  812. case "u2f":
  813. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  814. try {
  815. $reg = $u2f->doRegister(json_decode($_SESSION['regReq']), json_decode($_data['token']));
  816. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username AND `authmech` != 'u2f'");
  817. $stmt->execute(array(':username' => $username));
  818. $stmt = $pdo->prepare("INSERT INTO `tfa` (`username`, `key_id`, `authmech`, `keyHandle`, `publicKey`, `certificate`, `counter`, `active`) VALUES (?, ?, 'u2f', ?, ?, ?, ?, '1')");
  819. $stmt->execute(array($username, $key_id, $reg->keyHandle, $reg->publicKey, $reg->certificate, $reg->counter));
  820. $_SESSION['return'][] = array(
  821. 'type' => 'success',
  822. 'log' => array(__FUNCTION__, $_data_log),
  823. 'msg' => array('object_modified', $username)
  824. );
  825. $_SESSION['regReq'] = null;
  826. }
  827. catch (Exception $e) {
  828. $_SESSION['return'][] = array(
  829. 'type' => 'danger',
  830. 'log' => array(__FUNCTION__, $_data_log),
  831. 'msg' => array('u2f_verification_failed', $e->getMessage())
  832. );
  833. $_SESSION['regReq'] = null;
  834. return false;
  835. }
  836. break;
  837. case "totp":
  838. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  839. if ($tfa->verifyCode($_POST['totp_secret'], $_POST['totp_confirm_token']) === true) {
  840. try {
  841. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
  842. $stmt->execute(array(':username' => $username));
  843. $stmt = $pdo->prepare("INSERT INTO `tfa` (`username`, `key_id`, `authmech`, `secret`, `active`) VALUES (?, ?, 'totp', ?, '1')");
  844. $stmt->execute(array($username, $key_id, $_POST['totp_secret']));
  845. }
  846. catch (PDOException $e) {
  847. $_SESSION['return'][] = array(
  848. 'type' => 'danger',
  849. 'log' => array(__FUNCTION__, $_data_log),
  850. 'msg' => array('mysql_error', $e)
  851. );
  852. return false;
  853. }
  854. $_SESSION['return'][] = array(
  855. 'type' => 'success',
  856. 'log' => array(__FUNCTION__, $_data_log),
  857. 'msg' => array('object_modified', $username)
  858. );
  859. }
  860. else {
  861. $_SESSION['return'][] = array(
  862. 'type' => 'danger',
  863. 'log' => array(__FUNCTION__, $_data_log),
  864. 'msg' => 'totp_verification_failed'
  865. );
  866. }
  867. break;
  868. case "none":
  869. try {
  870. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
  871. $stmt->execute(array(':username' => $username));
  872. }
  873. catch (PDOException $e) {
  874. $_SESSION['return'][] = array(
  875. 'type' => 'danger',
  876. 'log' => array(__FUNCTION__, $_data_log),
  877. 'msg' => array('mysql_error', $e)
  878. );
  879. return false;
  880. }
  881. $_SESSION['return'][] = array(
  882. 'type' => 'success',
  883. 'log' => array(__FUNCTION__, $_data_log),
  884. 'msg' => array('object_modified', htmlspecialchars($username))
  885. );
  886. break;
  887. }
  888. }
  889. function unset_tfa_key($_data) {
  890. // Can only unset own keys
  891. // Needs at least one key left
  892. global $pdo;
  893. global $lang;
  894. $_data_log = $_data;
  895. $id = intval($_data['unset_tfa_key']);
  896. $username = $_SESSION['mailcow_cc_username'];
  897. if ($_SESSION['mailcow_cc_role'] != "domainadmin" &&
  898. $_SESSION['mailcow_cc_role'] != "admin") {
  899. $_SESSION['return'][] = array(
  900. 'type' => 'danger',
  901. 'log' => array(__FUNCTION__, $_data_log),
  902. 'msg' => 'access_denied'
  903. );
  904. return false;
  905. }
  906. try {
  907. if (!is_numeric($id)) {
  908. $_SESSION['return'][] = array(
  909. 'type' => 'danger',
  910. 'log' => array(__FUNCTION__, $_data_log),
  911. 'msg' => 'access_denied'
  912. );
  913. return false;
  914. }
  915. $stmt = $pdo->prepare("SELECT COUNT(*) AS `keys` FROM `tfa`
  916. WHERE `username` = :username AND `active` = '1'");
  917. $stmt->execute(array(':username' => $username));
  918. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  919. if ($row['keys'] == "1") {
  920. $_SESSION['return'][] = array(
  921. 'type' => 'danger',
  922. 'log' => array(__FUNCTION__, $_data_log),
  923. 'msg' => 'last_key'
  924. );
  925. return false;
  926. }
  927. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username AND `id` = :id");
  928. $stmt->execute(array(':username' => $username, ':id' => $id));
  929. $_SESSION['return'][] = array(
  930. 'type' => 'success',
  931. 'log' => array(__FUNCTION__, $_data_log),
  932. 'msg' => array('object_modified', $username)
  933. );
  934. }
  935. catch (PDOException $e) {
  936. $_SESSION['return'][] = array(
  937. 'type' => 'danger',
  938. 'log' => array(__FUNCTION__, $_data_log),
  939. 'msg' => array('mysql_error', $e)
  940. );
  941. return false;
  942. }
  943. }
  944. function get_tfa($username = null) {
  945. global $pdo;
  946. if (isset($_SESSION['mailcow_cc_username'])) {
  947. $username = $_SESSION['mailcow_cc_username'];
  948. }
  949. elseif (empty($username)) {
  950. return false;
  951. }
  952. $stmt = $pdo->prepare("SELECT * FROM `tfa`
  953. WHERE `username` = :username AND `active` = '1'");
  954. $stmt->execute(array(':username' => $username));
  955. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  956. switch ($row["authmech"]) {
  957. case "yubi_otp":
  958. $data['name'] = "yubi_otp";
  959. $data['pretty'] = "Yubico OTP";
  960. $stmt = $pdo->prepare("SELECT `id`, `key_id`, RIGHT(`secret`, 12) AS 'modhex' FROM `tfa` WHERE `authmech` = 'yubi_otp' AND `username` = :username");
  961. $stmt->execute(array(
  962. ':username' => $username,
  963. ));
  964. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  965. while($row = array_shift($rows)) {
  966. $data['additional'][] = $row;
  967. }
  968. return $data;
  969. break;
  970. case "u2f":
  971. $data['name'] = "u2f";
  972. $data['pretty'] = "Fido U2F";
  973. $stmt = $pdo->prepare("SELECT `id`, `key_id` FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username");
  974. $stmt->execute(array(
  975. ':username' => $username,
  976. ));
  977. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  978. while($row = array_shift($rows)) {
  979. $data['additional'][] = $row;
  980. }
  981. return $data;
  982. break;
  983. case "hotp":
  984. $data['name'] = "hotp";
  985. $data['pretty'] = "HMAC-based OTP";
  986. return $data;
  987. break;
  988. case "totp":
  989. $data['name'] = "totp";
  990. $data['pretty'] = "Time-based OTP";
  991. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `secret` FROM `tfa` WHERE `authmech` = 'totp' AND `username` = :username");
  992. $stmt->execute(array(
  993. ':username' => $username,
  994. ));
  995. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  996. while($row = array_shift($rows)) {
  997. $data['additional'][] = $row;
  998. }
  999. return $data;
  1000. break;
  1001. default:
  1002. $data['name'] = 'none';
  1003. $data['pretty'] = "-";
  1004. return $data;
  1005. break;
  1006. }
  1007. }
  1008. function verify_tfa_login($username, $token) {
  1009. global $pdo;
  1010. global $lang;
  1011. global $yubi;
  1012. global $u2f;
  1013. global $tfa;
  1014. $stmt = $pdo->prepare("SELECT `authmech` FROM `tfa`
  1015. WHERE `username` = :username AND `active` = '1'");
  1016. $stmt->execute(array(':username' => $username));
  1017. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1018. switch ($row["authmech"]) {
  1019. case "yubi_otp":
  1020. if (!ctype_alnum($token) || strlen($token) != 44) {
  1021. $_SESSION['return'][] = array(
  1022. 'type' => 'danger',
  1023. 'log' => array(__FUNCTION__, $username, '*'),
  1024. 'msg' => array('yotp_verification_failed', 'token length error')
  1025. );
  1026. return false;
  1027. }
  1028. $yubico_modhex_id = substr($token, 0, 12);
  1029. $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
  1030. WHERE `username` = :username
  1031. AND `authmech` = 'yubi_otp'
  1032. AND `active`='1'
  1033. AND `secret` LIKE :modhex");
  1034. $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id));
  1035. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1036. $yubico_auth = explode(':', $row['secret']);
  1037. $yubi = new Auth_Yubico($yubico_auth[0], $yubico_auth[1]);
  1038. $yauth = $yubi->verify($token);
  1039. if (PEAR::isError($yauth)) {
  1040. $_SESSION['return'][] = array(
  1041. 'type' => 'danger',
  1042. 'log' => array(__FUNCTION__, $username, '*'),
  1043. 'msg' => array('yotp_verification_failed', $yauth->getMessage())
  1044. );
  1045. return false;
  1046. }
  1047. else {
  1048. $_SESSION['tfa_id'] = $row['id'];
  1049. $_SESSION['return'][] = array(
  1050. 'type' => 'success',
  1051. 'log' => array(__FUNCTION__, $username, '*'),
  1052. 'msg' => 'verified_yotp_login'
  1053. );
  1054. return true;
  1055. }
  1056. $_SESSION['return'][] = array(
  1057. 'type' => 'danger',
  1058. 'log' => array(__FUNCTION__, $username, '*'),
  1059. 'msg' => array('yotp_verification_failed', 'unknown')
  1060. );
  1061. return false;
  1062. break;
  1063. case "u2f":
  1064. try {
  1065. $reg = $u2f->doAuthenticate(json_decode($_SESSION['authReq']), get_u2f_registrations($username), json_decode($token));
  1066. $stmt = $pdo->prepare("SELECT `id` FROM `tfa` WHERE `keyHandle` = ?");
  1067. $stmt->execute(array($reg->keyHandle));
  1068. $row_key_id = $stmt->fetch(PDO::FETCH_ASSOC);
  1069. $_SESSION['tfa_id'] = $row_key_id['id'];
  1070. $_SESSION['authReq'] = null;
  1071. $_SESSION['return'][] = array(
  1072. 'type' => 'success',
  1073. 'log' => array(__FUNCTION__, $username, '*'),
  1074. 'msg' => 'verified_u2f_login'
  1075. );
  1076. return true;
  1077. }
  1078. catch (Exception $e) {
  1079. $_SESSION['return'][] = array(
  1080. 'type' => 'danger',
  1081. 'log' => array(__FUNCTION__, $username, '*'),
  1082. 'msg' => array('u2f_verification_failed', $e->getMessage())
  1083. );
  1084. $_SESSION['regReq'] = null;
  1085. return false;
  1086. }
  1087. $_SESSION['return'][] = array(
  1088. 'type' => 'danger',
  1089. 'log' => array(__FUNCTION__, $username, '*'),
  1090. 'msg' => array('u2f_verification_failed', 'unknown')
  1091. );
  1092. return false;
  1093. break;
  1094. case "hotp":
  1095. return false;
  1096. break;
  1097. case "totp":
  1098. try {
  1099. $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
  1100. WHERE `username` = :username
  1101. AND `authmech` = 'totp'
  1102. AND `active`='1'");
  1103. $stmt->execute(array(':username' => $username));
  1104. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1105. if ($tfa->verifyCode($row['secret'], $_POST['token']) === true) {
  1106. $_SESSION['tfa_id'] = $row['id'];
  1107. $_SESSION['return'][] = array(
  1108. 'type' => 'success',
  1109. 'log' => array(__FUNCTION__, $username, '*'),
  1110. 'msg' => 'verified_totp_login'
  1111. );
  1112. return true;
  1113. }
  1114. $_SESSION['return'][] = array(
  1115. 'type' => 'danger',
  1116. 'log' => array(__FUNCTION__, $username, '*'),
  1117. 'msg' => 'totp_verification_failed'
  1118. );
  1119. return false;
  1120. }
  1121. catch (PDOException $e) {
  1122. $_SESSION['return'][] = array(
  1123. 'type' => 'danger',
  1124. 'log' => array(__FUNCTION__, $username, '*'),
  1125. 'msg' => array('mysql_error', $e)
  1126. );
  1127. return false;
  1128. }
  1129. break;
  1130. default:
  1131. $_SESSION['return'][] = array(
  1132. 'type' => 'danger',
  1133. 'log' => array(__FUNCTION__, $username, '*'),
  1134. 'msg' => 'unknown_tfa_method'
  1135. );
  1136. return false;
  1137. break;
  1138. }
  1139. return false;
  1140. }
  1141. function admin_api($access, $action, $data = null) {
  1142. global $pdo;
  1143. global $lang;
  1144. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1145. $_SESSION['return'][] = array(
  1146. 'type' => 'danger',
  1147. 'log' => array(__FUNCTION__),
  1148. 'msg' => 'access_denied'
  1149. );
  1150. return false;
  1151. }
  1152. switch ($access) {
  1153. case "rw":
  1154. switch ($action) {
  1155. case "edit":
  1156. $active = (isset($data['active'])) ? 1 : 0;
  1157. $skip_ip_check = (isset($data['skip_ip_check'])) ? 1 : 0;
  1158. $allow_from = array_map('trim', preg_split( "/( |,|;|\n)/", $data['allow_from']));
  1159. foreach ($allow_from as $key => $val) {
  1160. if (empty($val)) {
  1161. continue;
  1162. }
  1163. if (!filter_var($val, FILTER_VALIDATE_IP)) {
  1164. $_SESSION['return'][] = array(
  1165. 'type' => 'warning',
  1166. 'log' => array(__FUNCTION__, $data),
  1167. 'msg' => array('ip_invalid', htmlspecialchars($allow_from[$key]))
  1168. );
  1169. unset($allow_from[$key]);
  1170. continue;
  1171. }
  1172. }
  1173. $allow_from = implode(',', array_unique(array_filter($allow_from)));
  1174. if (empty($allow_from) && $skip_ip_check == 0) {
  1175. $_SESSION['return'][] = array(
  1176. 'type' => 'danger',
  1177. 'log' => array(__FUNCTION__, $data),
  1178. 'msg' => 'ip_list_empty'
  1179. );
  1180. return false;
  1181. }
  1182. $api_key = implode('-', array(
  1183. strtoupper(bin2hex(random_bytes(3))),
  1184. strtoupper(bin2hex(random_bytes(3))),
  1185. strtoupper(bin2hex(random_bytes(3))),
  1186. strtoupper(bin2hex(random_bytes(3))),
  1187. strtoupper(bin2hex(random_bytes(3)))
  1188. ));
  1189. $stmt = $pdo->query("SELECT `api_key` FROM `api` WHERE `access` = 'rw'");
  1190. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  1191. if (empty($num_results)) {
  1192. $stmt = $pdo->prepare("INSERT INTO `api` (`api_key`, `skip_ip_check`, `active`, `allow_from`, `access`)
  1193. VALUES (:api_key, :skip_ip_check, :active, :allow_from, 'rw');");
  1194. $stmt->execute(array(
  1195. ':api_key' => $api_key,
  1196. ':skip_ip_check' => $skip_ip_check,
  1197. ':active' => $active,
  1198. ':allow_from' => $allow_from
  1199. ));
  1200. }
  1201. else {
  1202. if ($skip_ip_check == 0) {
  1203. $stmt = $pdo->prepare("UPDATE `api` SET `skip_ip_check` = :skip_ip_check, `active` = :active, `allow_from` = :allow_from WHERE `access` = 'rw';");
  1204. $stmt->execute(array(
  1205. ':active' => $active,
  1206. ':skip_ip_check' => $skip_ip_check,
  1207. ':allow_from' => $allow_from
  1208. ));
  1209. }
  1210. else {
  1211. $stmt = $pdo->prepare("UPDATE `api` SET `skip_ip_check` = :skip_ip_check, `active` = :active WHERE `access` = 'rw';");
  1212. $stmt->execute(array(
  1213. ':active' => $active,
  1214. ':skip_ip_check' => $skip_ip_check
  1215. ));
  1216. }
  1217. }
  1218. break;
  1219. case "regen_key":
  1220. $api_key = implode('-', array(
  1221. strtoupper(bin2hex(random_bytes(3))),
  1222. strtoupper(bin2hex(random_bytes(3))),
  1223. strtoupper(bin2hex(random_bytes(3))),
  1224. strtoupper(bin2hex(random_bytes(3))),
  1225. strtoupper(bin2hex(random_bytes(3)))
  1226. ));
  1227. $stmt = $pdo->prepare("UPDATE `api` SET `api_key` = :api_key WHERE `access` = 'rw'");
  1228. $stmt->execute(array(
  1229. ':api_key' => $api_key
  1230. ));
  1231. break;
  1232. case "get":
  1233. $stmt = $pdo->query("SELECT * FROM `api` WHERE `access` = 'rw'");
  1234. $apidata = $stmt->fetch(PDO::FETCH_ASSOC);
  1235. return $apidata;
  1236. break;
  1237. }
  1238. case "ro":
  1239. switch ($action) {
  1240. case "edit":
  1241. $active = (isset($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. continue;
  1247. }
  1248. if (!filter_var($val, FILTER_VALIDATE_IP)) {
  1249. $_SESSION['return'][] = array(
  1250. 'type' => 'warning',
  1251. 'log' => array(__FUNCTION__, $data),
  1252. 'msg' => array('ip_invalid', htmlspecialchars($allow_from[$key]))
  1253. );
  1254. unset($allow_from[$key]);
  1255. continue;
  1256. }
  1257. }
  1258. $allow_from = implode(',', array_unique(array_filter($allow_from)));
  1259. if (empty($allow_from) && $skip_ip_check == 0) {
  1260. $_SESSION['return'][] = array(
  1261. 'type' => 'danger',
  1262. 'log' => array(__FUNCTION__, $data),
  1263. 'msg' => 'ip_list_empty'
  1264. );
  1265. return false;
  1266. }
  1267. $api_key = implode('-', array(
  1268. strtoupper(bin2hex(random_bytes(3))),
  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. ));
  1274. $stmt = $pdo->query("SELECT `api_key` FROM `api` WHERE `access` = 'ro'");
  1275. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  1276. if (empty($num_results)) {
  1277. $stmt = $pdo->prepare("INSERT INTO `api` (`api_key`, `skip_ip_check`, `active`, `allow_from`, `access`)
  1278. VALUES (:api_key, :skip_ip_check, :active, :allow_from, 'ro');");
  1279. $stmt->execute(array(
  1280. ':api_key' => $api_key,
  1281. ':skip_ip_check' => $skip_ip_check,
  1282. ':active' => $active,
  1283. ':allow_from' => $allow_from
  1284. ));
  1285. }
  1286. else {
  1287. if ($skip_ip_check == 0) {
  1288. $stmt = $pdo->prepare("UPDATE `api` SET `skip_ip_check` = :skip_ip_check, `active` = :active, `allow_from` = :allow_from WHERE `access` = 'ro';");
  1289. $stmt->execute(array(
  1290. ':active' => $active,
  1291. ':skip_ip_check' => $skip_ip_check,
  1292. ':allow_from' => $allow_from
  1293. ));
  1294. }
  1295. else {
  1296. $stmt = $pdo->prepare("UPDATE `api` SET `skip_ip_check` = :skip_ip_check, `active` = :active WHERE `access` = 'ro';");
  1297. $stmt->execute(array(
  1298. ':active' => $active,
  1299. ':skip_ip_check' => $skip_ip_check
  1300. ));
  1301. }
  1302. }
  1303. break;
  1304. case "regen_key":
  1305. $api_key = implode('-', array(
  1306. strtoupper(bin2hex(random_bytes(3))),
  1307. strtoupper(bin2hex(random_bytes(3))),
  1308. strtoupper(bin2hex(random_bytes(3))),
  1309. strtoupper(bin2hex(random_bytes(3))),
  1310. strtoupper(bin2hex(random_bytes(3)))
  1311. ));
  1312. $stmt = $pdo->prepare("UPDATE `api` SET `api_key` = :api_key WHERE `access` = 'ro'");
  1313. $stmt->execute(array(
  1314. ':api_key' => $api_key
  1315. ));
  1316. break;
  1317. case "get":
  1318. $stmt = $pdo->query("SELECT * FROM `api` WHERE `access` = 'ro'");
  1319. $apidata = $stmt->fetch(PDO::FETCH_ASSOC);
  1320. return $apidata;
  1321. break;
  1322. }
  1323. break;
  1324. }
  1325. $_SESSION['return'][] = array(
  1326. 'type' => 'success',
  1327. 'log' => array(__FUNCTION__, $data),
  1328. 'msg' => 'admin_api_modified'
  1329. );
  1330. }
  1331. function license($action, $data = null) {
  1332. global $pdo;
  1333. global $redis;
  1334. global $lang;
  1335. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1336. $_SESSION['return'][] = array(
  1337. 'type' => 'danger',
  1338. 'log' => array(__FUNCTION__),
  1339. 'msg' => 'access_denied'
  1340. );
  1341. return false;
  1342. }
  1343. switch ($action) {
  1344. case "verify":
  1345. // Keep result until revalidate button is pressed or session expired
  1346. $stmt = $pdo->query("SELECT `version` FROM `versions` WHERE `application` = 'GUID'");
  1347. $versions = $stmt->fetch(PDO::FETCH_ASSOC);
  1348. $post = array('guid' => $versions['version']);
  1349. $curl = curl_init('https://verify.mailcow.email');
  1350. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  1351. curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
  1352. curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
  1353. $response = curl_exec($curl);
  1354. curl_close($curl);
  1355. $json_return = json_decode($response, true);
  1356. if ($response && $json_return) {
  1357. if ($json_return['response'] === "ok") {
  1358. $_SESSION['gal']['valid'] = "true";
  1359. $_SESSION['gal']['c'] = $json_return['c'];
  1360. $_SESSION['gal']['s'] = $json_return['s'];
  1361. if ($json_return['m'] == 'NoMoore') {
  1362. $_SESSION['gal']['m'] = '🐄';
  1363. }
  1364. else {
  1365. $_SESSION['gal']['m'] = str_repeat('🐄', substr_count($json_return['m'], 'o'));
  1366. }
  1367. }
  1368. elseif ($json_return['response'] === "invalid") {
  1369. $_SESSION['gal']['valid'] = "false";
  1370. $_SESSION['gal']['c'] = $lang['mailbox']['no'];
  1371. $_SESSION['gal']['s'] = $lang['mailbox']['no'];
  1372. $_SESSION['gal']['m'] = $lang['mailbox']['no'];
  1373. }
  1374. }
  1375. else {
  1376. $_SESSION['gal']['valid'] = "false";
  1377. $_SESSION['gal']['c'] = $lang['danger']['temp_error'];
  1378. $_SESSION['gal']['s'] = $lang['danger']['temp_error'];
  1379. $_SESSION['gal']['m'] = $lang['danger']['temp_error'];
  1380. }
  1381. try {
  1382. // json_encode needs "true"/"false" instead of true/false, to not encode it to 0 or 1
  1383. $redis->Set('LICENSE_STATUS_CACHE', json_encode($_SESSION['gal']));
  1384. }
  1385. catch (RedisException $e) {
  1386. $_SESSION['return'][] = array(
  1387. 'type' => 'danger',
  1388. 'log' => array(__FUNCTION__, $_action, $_data_log),
  1389. 'msg' => array('redis_error', $e)
  1390. );
  1391. return false;
  1392. }
  1393. return $_SESSION['gal']['valid'];
  1394. break;
  1395. case "guid":
  1396. $stmt = $pdo->query("SELECT `version` FROM `versions` WHERE `application` = 'GUID'");
  1397. $versions = $stmt->fetch(PDO::FETCH_ASSOC);
  1398. return $versions['version'];
  1399. break;
  1400. }
  1401. }
  1402. function rspamd_ui($action, $data = null) {
  1403. global $lang;
  1404. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1405. $_SESSION['return'][] = array(
  1406. 'type' => 'danger',
  1407. 'log' => array(__FUNCTION__),
  1408. 'msg' => 'access_denied'
  1409. );
  1410. return false;
  1411. }
  1412. switch ($action) {
  1413. case "edit":
  1414. $rspamd_ui_pass = $data['rspamd_ui_pass'];
  1415. $rspamd_ui_pass2 = $data['rspamd_ui_pass2'];
  1416. if (empty($rspamd_ui_pass) || empty($rspamd_ui_pass2)) {
  1417. $_SESSION['return'][] = array(
  1418. 'type' => 'danger',
  1419. 'log' => array(__FUNCTION__, '*', '*'),
  1420. 'msg' => 'password_empty'
  1421. );
  1422. return false;
  1423. }
  1424. if ($rspamd_ui_pass != $rspamd_ui_pass2) {
  1425. $_SESSION['return'][] = array(
  1426. 'type' => 'danger',
  1427. 'log' => array(__FUNCTION__, '*', '*'),
  1428. 'msg' => 'password_mismatch'
  1429. );
  1430. return false;
  1431. }
  1432. if (strlen($rspamd_ui_pass) < 6) {
  1433. $_SESSION['return'][] = array(
  1434. 'type' => 'danger',
  1435. 'log' => array(__FUNCTION__, '*', '*'),
  1436. 'msg' => 'rspamd_ui_pw_length'
  1437. );
  1438. return false;
  1439. }
  1440. $docker_return = docker('post', 'rspamd-mailcow', 'exec', array('cmd' => 'rspamd', 'task' => 'worker_password', 'raw' => $rspamd_ui_pass), array('Content-Type: application/json'));
  1441. if ($docker_return_array = json_decode($docker_return, true)) {
  1442. if ($docker_return_array['type'] == 'success') {
  1443. $_SESSION['return'][] = array(
  1444. 'type' => 'success',
  1445. 'log' => array(__FUNCTION__, '*', '*'),
  1446. 'msg' => 'rspamd_ui_pw_set'
  1447. );
  1448. return true;
  1449. }
  1450. else {
  1451. $_SESSION['return'][] = array(
  1452. 'type' => $docker_return_array['type'],
  1453. 'log' => array(__FUNCTION__, '*', '*'),
  1454. 'msg' => $docker_return_array['msg']
  1455. );
  1456. return false;
  1457. }
  1458. }
  1459. else {
  1460. $_SESSION['return'][] = array(
  1461. 'type' => 'danger',
  1462. 'log' => array(__FUNCTION__, '*', '*'),
  1463. 'msg' => 'unknown'
  1464. );
  1465. return false;
  1466. }
  1467. break;
  1468. }
  1469. }
  1470. function get_u2f_registrations($username) {
  1471. global $pdo;
  1472. $sel = $pdo->prepare("SELECT * FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = ? AND `active` = '1'");
  1473. $sel->execute(array($username));
  1474. return $sel->fetchAll(PDO::FETCH_OBJ);
  1475. }
  1476. function get_logs($application, $lines = false) {
  1477. if ($lines === false) {
  1478. $lines = $GLOBALS['LOG_LINES'] - 1;
  1479. }
  1480. elseif(is_numeric($lines) && $lines >= 1) {
  1481. $lines = abs(intval($lines) - 1);
  1482. }
  1483. else {
  1484. list ($from, $to) = explode('-', $lines);
  1485. $from = intval($from);
  1486. $to = intval($to);
  1487. if ($from < 1 || $to < $from) { return false; }
  1488. }
  1489. global $lang;
  1490. global $redis;
  1491. global $pdo;
  1492. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1493. return false;
  1494. }
  1495. // SQL
  1496. if ($application == "mailcow-ui") {
  1497. if (isset($from) && isset($to)) {
  1498. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :from, :to");
  1499. $stmt->execute(array(
  1500. ':from' => $from - 1,
  1501. ':to' => $to
  1502. ));
  1503. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1504. }
  1505. else {
  1506. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :lines");
  1507. $stmt->execute(array(
  1508. ':lines' => $lines + 1,
  1509. ));
  1510. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1511. }
  1512. if (is_array($data)) {
  1513. return $data;
  1514. }
  1515. }
  1516. // Redis
  1517. if ($application == "dovecot-mailcow") {
  1518. if (isset($from) && isset($to)) {
  1519. $data = $redis->lRange('DOVECOT_MAILLOG', $from - 1, $to - 1);
  1520. }
  1521. else {
  1522. $data = $redis->lRange('DOVECOT_MAILLOG', 0, $lines);
  1523. }
  1524. if ($data) {
  1525. foreach ($data as $json_line) {
  1526. $data_array[] = json_decode($json_line, true);
  1527. }
  1528. return $data_array;
  1529. }
  1530. }
  1531. if ($application == "postfix-mailcow") {
  1532. if (isset($from) && isset($to)) {
  1533. $data = $redis->lRange('POSTFIX_MAILLOG', $from - 1, $to - 1);
  1534. }
  1535. else {
  1536. $data = $redis->lRange('POSTFIX_MAILLOG', 0, $lines);
  1537. }
  1538. if ($data) {
  1539. foreach ($data as $json_line) {
  1540. $data_array[] = json_decode($json_line, true);
  1541. }
  1542. return $data_array;
  1543. }
  1544. }
  1545. if ($application == "sogo-mailcow") {
  1546. if (isset($from) && isset($to)) {
  1547. $data = $redis->lRange('SOGO_LOG', $from - 1, $to - 1);
  1548. }
  1549. else {
  1550. $data = $redis->lRange('SOGO_LOG', 0, $lines);
  1551. }
  1552. if ($data) {
  1553. foreach ($data as $json_line) {
  1554. $data_array[] = json_decode($json_line, true);
  1555. }
  1556. return $data_array;
  1557. }
  1558. }
  1559. if ($application == "watchdog-mailcow") {
  1560. if (isset($from) && isset($to)) {
  1561. $data = $redis->lRange('WATCHDOG_LOG', $from - 1, $to - 1);
  1562. }
  1563. else {
  1564. $data = $redis->lRange('WATCHDOG_LOG', 0, $lines);
  1565. }
  1566. if ($data) {
  1567. foreach ($data as $json_line) {
  1568. $data_array[] = json_decode($json_line, true);
  1569. }
  1570. return $data_array;
  1571. }
  1572. }
  1573. if ($application == "acme-mailcow") {
  1574. if (isset($from) && isset($to)) {
  1575. $data = $redis->lRange('ACME_LOG', $from - 1, $to - 1);
  1576. }
  1577. else {
  1578. $data = $redis->lRange('ACME_LOG', 0, $lines);
  1579. }
  1580. if ($data) {
  1581. foreach ($data as $json_line) {
  1582. $data_array[] = json_decode($json_line, true);
  1583. }
  1584. return $data_array;
  1585. }
  1586. }
  1587. if ($application == "ratelimited") {
  1588. if (isset($from) && isset($to)) {
  1589. $data = $redis->lRange('RL_LOG', $from - 1, $to - 1);
  1590. }
  1591. else {
  1592. $data = $redis->lRange('RL_LOG', 0, $lines);
  1593. }
  1594. if ($data) {
  1595. foreach ($data as $json_line) {
  1596. $data_array[] = json_decode($json_line, true);
  1597. }
  1598. return $data_array;
  1599. }
  1600. }
  1601. if ($application == "api-mailcow") {
  1602. if (isset($from) && isset($to)) {
  1603. $data = $redis->lRange('API_LOG', $from - 1, $to - 1);
  1604. }
  1605. else {
  1606. $data = $redis->lRange('API_LOG', 0, $lines);
  1607. }
  1608. if ($data) {
  1609. foreach ($data as $json_line) {
  1610. $data_array[] = json_decode($json_line, true);
  1611. }
  1612. return $data_array;
  1613. }
  1614. }
  1615. if ($application == "netfilter-mailcow") {
  1616. if (isset($from) && isset($to)) {
  1617. $data = $redis->lRange('NETFILTER_LOG', $from - 1, $to - 1);
  1618. }
  1619. else {
  1620. $data = $redis->lRange('NETFILTER_LOG', 0, $lines);
  1621. }
  1622. if ($data) {
  1623. foreach ($data as $json_line) {
  1624. $data_array[] = json_decode($json_line, true);
  1625. }
  1626. return $data_array;
  1627. }
  1628. }
  1629. if ($application == "autodiscover-mailcow") {
  1630. if (isset($from) && isset($to)) {
  1631. $data = $redis->lRange('AUTODISCOVER_LOG', $from - 1, $to - 1);
  1632. }
  1633. else {
  1634. $data = $redis->lRange('AUTODISCOVER_LOG', 0, $lines);
  1635. }
  1636. if ($data) {
  1637. foreach ($data as $json_line) {
  1638. $data_array[] = json_decode($json_line, true);
  1639. }
  1640. return $data_array;
  1641. }
  1642. }
  1643. if ($application == "rspamd-history") {
  1644. $curl = curl_init();
  1645. curl_setopt($curl, CURLOPT_UNIX_SOCKET_PATH, '/var/lib/rspamd/rspamd.sock');
  1646. if (!is_numeric($lines)) {
  1647. list ($from, $to) = explode('-', $lines);
  1648. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?from=" . intval($from) . "&to=" . intval($to));
  1649. }
  1650. else {
  1651. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?to=" . intval($lines));
  1652. }
  1653. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  1654. $history = curl_exec($curl);
  1655. if (!curl_errno($curl)) {
  1656. $data_array = json_decode($history, true);
  1657. curl_close($curl);
  1658. return $data_array['rows'];
  1659. }
  1660. curl_close($curl);
  1661. return false;
  1662. }
  1663. return false;
  1664. }
  1665. function getGUID() {
  1666. if (function_exists('com_create_guid')) {
  1667. return com_create_guid();
  1668. }
  1669. mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
  1670. $charid = strtoupper(md5(uniqid(rand(), true)));
  1671. $hyphen = chr(45);// "-"
  1672. return substr($charid, 0, 8).$hyphen
  1673. .substr($charid, 8, 4).$hyphen
  1674. .substr($charid,12, 4).$hyphen
  1675. .substr($charid,16, 4).$hyphen
  1676. .substr($charid,20,12);
  1677. }
  1678. function solr_status() {
  1679. $curl = curl_init();
  1680. $endpoint = 'http://solr:8983/solr/admin/cores';
  1681. $params = array(
  1682. 'action' => 'STATUS',
  1683. 'core' => 'dovecot-fts',
  1684. 'indexInfo' => 'true'
  1685. );
  1686. $url = $endpoint . '?' . http_build_query($params);
  1687. curl_setopt($curl, CURLOPT_URL, $url);
  1688. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  1689. curl_setopt($curl, CURLOPT_POST, 0);
  1690. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  1691. $response_core = curl_exec($curl);
  1692. if ($response_core === false) {
  1693. $err = curl_error($curl);
  1694. curl_close($curl);
  1695. return false;
  1696. }
  1697. else {
  1698. curl_close($curl);
  1699. $curl = curl_init();
  1700. $status_core = json_decode($response_core, true);
  1701. $url = 'http://solr:8983/solr/admin/info/system';
  1702. curl_setopt($curl, CURLOPT_URL, $url);
  1703. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  1704. curl_setopt($curl, CURLOPT_POST, 0);
  1705. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  1706. $response_sysinfo = curl_exec($curl);
  1707. if ($response_sysinfo === false) {
  1708. $err = curl_error($curl);
  1709. curl_close($curl);
  1710. return false;
  1711. }
  1712. else {
  1713. curl_close($curl);
  1714. $status_sysinfo = json_decode($response_sysinfo, true);
  1715. $status = array_merge($status_core, $status_sysinfo);
  1716. return (!empty($status['status']['dovecot-fts']) && !empty($status['jvm']['memory'])) ? $status : false;
  1717. }
  1718. return (!empty($status['status']['dovecot-fts'])) ? $status['status']['dovecot-fts'] : false;
  1719. }
  1720. return false;
  1721. }
  1722. function cleanupJS($ignore = '', $folder = '/tmp/*.js') {
  1723. $now = time();
  1724. foreach (glob($folder) as $filename) {
  1725. if(strpos($filename, $ignore) !== false) {
  1726. continue;
  1727. }
  1728. if (is_file($filename)) {
  1729. if ($now - filemtime($filename) >= 60 * 60) {
  1730. unlink($filename);
  1731. }
  1732. }
  1733. }
  1734. }
  1735. function cleanupCSS($ignore = '', $folder = '/tmp/*.css') {
  1736. $now = time();
  1737. foreach (glob($folder) as $filename) {
  1738. if(strpos($filename, $ignore) !== false) {
  1739. continue;
  1740. }
  1741. if (is_file($filename)) {
  1742. if ($now - filemtime($filename) >= 60 * 60) {
  1743. unlink($filename);
  1744. }
  1745. }
  1746. }
  1747. }
  1748. ?>