functions.inc.php 60 KB

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