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