blob: 09e8ec193db06d715499f72dae080c1eb4c02c58 [file] [log] [blame]
Matthias Andreas Benkard4edeb9f2021-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}
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +020016function readable_random_string($length = 8) {
17 $string = '';
18 $vowels = array('a', 'e', 'i', 'o', 'u');
19 $consonants = array('b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z');
20 $max = $length / 2;
21 for ($i = 1; $i <= $max; $i++) {
22 $string .= $consonants[rand(0,19)];
23 $string .= $vowels[rand(0,4)];
24 }
25 return $string;
26}
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +010027// Validates ips and cidrs
28function valid_network($network) {
29 if (filter_var($network, FILTER_VALIDATE_IP)) {
30 return true;
31 }
32 $parts = explode('/', $network);
33 if (count($parts) != 2) {
34 return false;
35 }
36 $ip = $parts[0];
37 $netmask = $parts[1];
38 if (!preg_match("/^\d+$/", $netmask)){
39 return false;
40 }
41 $netmask = intval($parts[1]);
42 if ($netmask < 0) {
43 return false;
44 }
45 if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
46 return $netmask <= 32;
47 }
48 if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
49 return $netmask <= 128;
50 }
51 return false;
52}
53function valid_hostname($hostname) {
54 return filter_var($hostname, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME);
55}
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +020056// Validates a browser-style Origin: scheme://host[:port], no path/query/fragment/credentials
57function valid_origin($origin) {
58 $parts = parse_url($origin);
59 if ($parts === false || !isset($parts['scheme']) || !isset($parts['host'])) {
60 return false;
61 }
62 if (!in_array(strtolower($parts['scheme']), array('http', 'https'), true)) {
63 return false;
64 }
65 if (isset($parts['user']) || isset($parts['pass']) || isset($parts['path']) || isset($parts['query']) || isset($parts['fragment'])) {
66 return false;
67 }
68 $host = $parts['host'];
69 $host_without_brackets = trim($host, '[]');
70 if (!valid_hostname($host_without_brackets) && !filter_var($host_without_brackets, FILTER_VALIDATE_IP)) {
71 return false;
72 }
73 // Reject anything that doesn't round-trip to the exact same origin (e.g. stray trailing slash)
74 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
75 $rebuilt = strtolower($parts['scheme']) . '://' . strtolower($host) . $port;
76 return strtolower($origin) === $rebuilt;
77}
78// Bring an origin into the exact form a browser sends it (scheme://host[:port], lowercase).
79function normalize_cors_origin($origin) {
80 $origin = trim($origin);
81 if ($origin === '*') {
82 return '*';
83 }
84 if ($origin !== '' && !preg_match('~^[a-z][a-z0-9+.-]*://~i', $origin)) {
85 $origin = 'https://' . $origin;
86 }
87 return valid_origin($origin) ? strtolower($origin) : false;
88}
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +010089// Thanks to https://stackoverflow.com/a/49373789
90// Validates exact ip matches and ip-in-cidr, ipv4 and ipv6
91function ip_acl($ip, $networks) {
92 foreach($networks as $network) {
93 if (filter_var($network, FILTER_VALIDATE_IP)) {
94 if ($ip == $network) {
95 return true;
96 }
97 else {
98 continue;
99 }
100 }
101 $ipb = inet_pton($ip);
102 $iplen = strlen($ipb);
103 if (strlen($ipb) < 4) {
104 continue;
105 }
106 $ar = explode('/', $network);
107 $ip1 = $ar[0];
108 $ip1b = inet_pton($ip1);
109 $ip1len = strlen($ip1b);
110 if ($ip1len != $iplen) {
111 continue;
112 }
113 if (count($ar)>1) {
114 $bits=(int)($ar[1]);
115 }
116 else {
117 $bits = $iplen * 8;
118 }
119 for ($c=0; $bits>0; $c++) {
120 $bytemask = ($bits < 8) ? 0xff ^ ((1 << (8-$bits))-1) : 0xff;
121 if (((ord($ipb[$c]) ^ ord($ip1b[$c])) & $bytemask) != 0) {
122 continue 2;
123 }
124 $bits-=8;
125 }
126 return true;
127 }
128 return false;
129}
130function hash_password($password) {
131 // default_pass_scheme is determined in vars.inc.php (or corresponding local file)
132 // in case default pass scheme is not defined, falling back to BLF-CRYPT.
133 global $default_pass_scheme;
134 $pw_hash = NULL;
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200135 // support pre-hashed passwords
136 if (preg_match('/^{(ARGON2I|ARGON2ID|BLF-CRYPT|CLEAR|CLEARTEXT|CRYPT|DES-CRYPT|LDAP-MD5|MD5|MD5-CRYPT|PBKDF2|PLAIN|PLAIN-MD4|PLAIN-MD5|PLAIN-TRUNC|PLAIN-TRUNC|SHA|SHA1|SHA256|SHA256-CRYPT|SHA512|SHA512-CRYPT|SMD5|SSHA|SSHA256|SSHA512)}/i', $password)) {
137 $pw_hash = $password;
138 }
139 else {
140 switch (strtoupper($default_pass_scheme)) {
141 case "SSHA":
142 $salt_str = bin2hex(openssl_random_pseudo_bytes(8));
143 $pw_hash = "{SSHA}".base64_encode(hash('sha1', $password . $salt_str, true) . $salt_str);
144 break;
145 case "SSHA256":
146 $salt_str = bin2hex(openssl_random_pseudo_bytes(8));
147 $pw_hash = "{SSHA256}".base64_encode(hash('sha256', $password . $salt_str, true) . $salt_str);
148 break;
149 case "SSHA512":
150 $salt_str = bin2hex(openssl_random_pseudo_bytes(8));
151 $pw_hash = "{SSHA512}".base64_encode(hash('sha512', $password . $salt_str, true) . $salt_str);
152 break;
153 case "BLF-CRYPT":
154 default:
155 $pw_hash = "{BLF-CRYPT}" . password_hash($password, PASSWORD_BCRYPT);
156 break;
157 }
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100158 }
159 return $pw_hash;
160}
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200161function password_complexity($_action, $_data = null) {
162 global $redis;
163 global $lang;
164 switch ($_action) {
165 case 'edit':
166 if ($_SESSION['mailcow_cc_role'] != "admin") {
167 $_SESSION['return'][] = array(
168 'type' => 'danger',
169 'log' => array(__FUNCTION__, $_action, $_data),
170 'msg' => 'access_denied'
171 );
172 return false;
173 }
174 $is_now = password_complexity('get');
175 if (!empty($is_now)) {
176 $length = (isset($_data['length']) && intval($_data['length']) >= 3) ? intval($_data['length']) : $is_now['length'];
177 $chars = (isset($_data['chars'])) ? intval($_data['chars']) : $is_now['chars'];
178 $lowerupper = (isset($_data['lowerupper'])) ? intval($_data['lowerupper']) : $is_now['lowerupper'];
179 $special_chars = (isset($_data['special_chars'])) ? intval($_data['special_chars']) : $is_now['special_chars'];
180 $numbers = (isset($_data['numbers'])) ? intval($_data['numbers']) : $is_now['numbers'];
181 }
182 try {
183 $redis->hMSet('PASSWD_POLICY', [
184 'length' => $length,
185 'chars' => $chars,
186 'special_chars' => $special_chars,
187 'lowerupper' => $lowerupper,
188 'numbers' => $numbers
189 ]);
190 }
191 catch (RedisException $e) {
192 $_SESSION['return'][] = array(
193 'type' => 'danger',
194 'log' => array(__FUNCTION__, $_action, $_data),
195 'msg' => array('redis_error', $e)
196 );
197 return false;
198 }
199 $_SESSION['return'][] = array(
200 'type' => 'success',
201 'log' => array(__FUNCTION__, $_action, $_data),
202 'msg' => 'password_policy_saved'
203 );
204 break;
205 case 'get':
206 try {
207 $length = $redis->hGet('PASSWD_POLICY', 'length');
208 $chars = $redis->hGet('PASSWD_POLICY', 'chars');
209 $special_chars = $redis->hGet('PASSWD_POLICY', 'special_chars');
210 $lowerupper = $redis->hGet('PASSWD_POLICY', 'lowerupper');
211 $numbers = $redis->hGet('PASSWD_POLICY', 'numbers');
212 return array(
213 'length' => $length,
214 'chars' => $chars,
215 'special_chars' => $special_chars,
216 'lowerupper' => $lowerupper,
217 'numbers' => $numbers
218 );
219 }
220 catch (RedisException $e) {
221 $_SESSION['return'][] = array(
222 'type' => 'danger',
223 'log' => array(__FUNCTION__, $_action, $_data),
224 'msg' => array('redis_error', $e)
225 );
226 return false;
227 }
228 return false;
229 break;
230 case 'html':
231 $policies = password_complexity('get');
232 foreach ($policies as $name => $value) {
233 if ($value != 0) {
234 $policy_text[] = sprintf($lang['admin']["password_policy_$name"], $value);
235 }
236 }
237 return '<p class="help-block small">- ' . implode('<br>- ', (array)$policy_text) . '</p>';
238 break;
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100239 }
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200240}
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +0200241
242function password_generate(){
243 $password_complexity = password_complexity('get');
244 $min_length = max(16, intval($password_complexity['length']));
245
246 $lowercase = range('a', 'z');
247 $uppercase = range('A', 'Z');
248 $digits = range(0, 9);
249 $special_chars = str_split('!@#$%^&*()?=');
250
251 $password = [
252 $lowercase[random_int(0, count($lowercase) - 1)],
253 $uppercase[random_int(0, count($uppercase) - 1)],
254 $digits[random_int(0, count($digits) - 1)],
255 $special_chars[random_int(0, count($special_chars) - 1)],
256 ];
257
258 $all = array_merge($lowercase, $uppercase, $digits, $special_chars);
259
260 while (count($password) < $min_length) {
261 $password[] = $all[random_int(0, count($all) - 1)];
262 }
263
264 // Cryptographically secure shuffle using Fisher-Yates algorithm
265 $count = count($password);
266 for ($i = $count - 1; $i > 0; $i--) {
267 $j = random_int(0, $i);
268 $temp = $password[$i];
269 $password[$i] = $password[$j];
270 $password[$j] = $temp;
271 }
272
273 return implode('', $password);
274
275}
276
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200277function password_check($password1, $password2) {
278 $password_complexity = password_complexity('get');
279
280 if (empty($password1) || empty($password2)) {
281 $_SESSION['return'][] = array(
282 'type' => 'danger',
283 'log' => array(__FUNCTION__, $_action, $_type),
284 'msg' => 'password_complexity'
285 );
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100286 return false;
287 }
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200288
289 if ($password1 != $password2) {
290 $_SESSION['return'][] = array(
291 'type' => 'danger',
292 'log' => array(__FUNCTION__, $_action, $_type),
293 'msg' => 'password_mismatch'
294 );
295 return false;
296 }
297
298 $given_password['length'] = strlen($password1);
299 $given_password['special_chars'] = preg_match('/[^a-zA-Z\d]/', $password1);
300 $given_password['chars'] = preg_match('/[a-zA-Z]/',$password1);
301 $given_password['numbers'] = preg_match('/\d/', $password1);
302 $lower = strlen(preg_replace("/[^a-z]/", '', $password1));
303 $upper = strlen(preg_replace("/[^A-Z]/", '', $password1));
304 $given_password['lowerupper'] = ($lower > 0 && $upper > 0) ? true : false;
305
306 if (
307 ($given_password['length'] < $password_complexity['length']) ||
308 ($password_complexity['special_chars'] == 1 && (intval($given_password['special_chars']) != $password_complexity['special_chars'])) ||
309 ($password_complexity['chars'] == 1 && (intval($given_password['chars']) != $password_complexity['chars'])) ||
310 ($password_complexity['numbers'] == 1 && (intval($given_password['numbers']) != $password_complexity['numbers'])) ||
311 ($password_complexity['lowerupper'] == 1 && (intval($given_password['lowerupper']) != $password_complexity['lowerupper']))
312 ) {
313 $_SESSION['return'][] = array(
314 'type' => 'danger',
315 'log' => array(__FUNCTION__, $_action, $_type),
316 'msg' => 'password_complexity'
317 );
318 return false;
319 }
320
321 return true;
322}
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +0100323function last_login($action, $username, $sasl_limit_days = 7, $ui_offset = 1) {
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200324 global $pdo;
325 global $redis;
326 $sasl_limit_days = intval($sasl_limit_days);
327 switch ($action) {
328 case 'get':
329 if (filter_var($username, FILTER_VALIDATE_EMAIL) && hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $username)) {
Matthias Andreas Benkardb4b5cc12021-12-28 18:02:04 +0100330 $stmt = $pdo->prepare('SELECT `real_rip`, MAX(`datetime`) as `datetime`, `service`, `app_password`, MAX(`app_passwd`.`name`) as `app_password_name` FROM `sasl_log`
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200331 LEFT OUTER JOIN `app_passwd` on `sasl_log`.`app_password` = `app_passwd`.`id`
332 WHERE `username` = :username
333 AND HOUR(TIMEDIFF(NOW(), `datetime`)) < :sasl_limit_days
334 GROUP BY `real_rip`, `service`, `app_password`
335 ORDER BY `datetime` DESC;');
336 $stmt->execute(array(':username' => $username, ':sasl_limit_days' => ($sasl_limit_days * 24)));
337 $sasl = $stmt->fetchAll(PDO::FETCH_ASSOC);
338 foreach ($sasl as $k => $v) {
339 if (!filter_var($sasl[$k]['real_rip'], FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
340 $sasl[$k]['real_rip'] = 'Web/EAS/Internal (' . $sasl[$k]['real_rip'] . ')';
341 }
342 elseif (filter_var($sasl[$k]['real_rip'], FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
343 try {
344 $sasl[$k]['location'] = $redis->hGet('IP_SHORTCOUNTRY', $sasl[$k]['real_rip']);
345 }
346 catch (RedisException $e) {
347 $_SESSION['return'][] = array(
348 'type' => 'danger',
349 'log' => array(__FUNCTION__, $_action, $_data_log),
350 'msg' => array('redis_error', $e)
351 );
352 return false;
353 }
354 if (!$sasl[$k]['location']) {
355 $curl = curl_init();
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +0200356 curl_setopt($curl, CURLOPT_URL,"https://dfdata.bella.network/country/" . $sasl[$k]['real_rip']);
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200357 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
358 curl_setopt($curl, CURLOPT_USERAGENT, 'Moocow');
359 curl_setopt($curl, CURLOPT_TIMEOUT, 5);
360 $ip_data = curl_exec($curl);
361 if (!curl_errno($curl)) {
362 $ip_data_array = json_decode($ip_data, true);
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +0200363 if ($ip_data_array !== false and !empty($ip_data_array['shortcountry'])) {
364 $sasl[$k]['location'] = $ip_data_array['shortcountry'];
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200365 try {
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +0200366 $redis->hSet('IP_SHORTCOUNTRY', $sasl[$k]['real_rip'], $ip_data_array['shortcountry']);
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200367 }
368 catch (RedisException $e) {
369 $_SESSION['return'][] = array(
370 'type' => 'danger',
371 'log' => array(__FUNCTION__, $_action, $_data_log),
372 'msg' => array('redis_error', $e)
373 );
374 curl_close($curl);
375 return false;
376 }
377 }
378 }
379 curl_close($curl);
380 }
381 }
382 }
383 }
384 else {
385 $sasl = array();
386 }
387 if ($_SESSION['mailcow_cc_role'] == "admin" || $username == $_SESSION['mailcow_cc_username']) {
388 $stmt = $pdo->prepare('SELECT `remote`, `time` FROM `logs`
389 WHERE JSON_EXTRACT(`call`, "$[0]") = "check_login"
390 AND JSON_EXTRACT(`call`, "$[1]") = :username
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +0100391 AND `type` = "success" ORDER BY `time` DESC LIMIT 1 OFFSET :offset');
392 $stmt->execute(array(
393 ':username' => $username,
394 ':offset' => $ui_offset
395 ));
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200396 $ui = $stmt->fetch(PDO::FETCH_ASSOC);
397 }
398 else {
399 $ui = array();
400 }
401
402 return array('ui' => $ui, 'sasl' => $sasl);
403 break;
404 case 'reset':
405 if (filter_var($username, FILTER_VALIDATE_EMAIL) && hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $username)) {
406 $stmt = $pdo->prepare('DELETE FROM `sasl_log`
407 WHERE `username` = :username');
408 $stmt->execute(array(':username' => $username));
409 }
410 if ($_SESSION['mailcow_cc_role'] == "admin" || $username == $_SESSION['mailcow_cc_username']) {
411 $stmt = $pdo->prepare('DELETE FROM `logs`
412 WHERE JSON_EXTRACT(`call`, "$[0]") = "check_login"
413 AND JSON_EXTRACT(`call`, "$[1]") = :username
414 AND `type` = "success"');
415 $stmt->execute(array(':username' => $username));
416 }
417 return true;
418 break;
419 }
420
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100421}
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +0200422function set_sasl_log($username, $real_rip, $service){
423 global $pdo;
424
425 try {
426 if (!empty($_SESSION['app_passwd_id'])) {
427 $app_password = $_SESSION['app_passwd_id'];
428 } else {
429 $app_password = 0;
430 }
431
432 $stmt = $pdo->prepare('REPLACE INTO `sasl_log` (`username`, `real_rip`, `service`, `app_password`) VALUES (:username, :real_rip, :service, :app_password)');
433 $stmt->execute(array(
434 ':username' => $username,
435 ':real_rip' => $real_rip,
436 ':service' => $service,
437 ':app_password' => $app_password
438 ));
439 } catch (PDOException $e) {
440 $_SESSION['return'][] = array(
441 'type' => 'danger',
442 'log' => array(__FUNCTION__, $_data_log),
443 'msg' => array('mysql_error', $e)
444 );
445 return false;
446 }
447
448 return true;
449}
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100450function flush_memcached() {
451 try {
452 $m = new Memcached();
453 $m->addServer('memcached', 11211);
454 $m->flush();
455 }
456 catch ( Exception $e ) {
457 // Dunno
458 }
459}
460function sys_mail($_data) {
461 if ($_SESSION['mailcow_cc_role'] != "admin") {
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200462 $_SESSION['return'][] = array(
463 'type' => 'danger',
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100464 'log' => array(__FUNCTION__),
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200465 'msg' => 'access_denied'
466 );
467 return false;
468 }
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100469 $excludes = $_data['mass_exclude'];
470 $includes = $_data['mass_include'];
471 $mailboxes = array();
472 $mass_from = $_data['mass_from'];
473 $mass_text = $_data['mass_text'];
474 $mass_html = $_data['mass_html'];
475 $mass_subject = $_data['mass_subject'];
476 if (!filter_var($mass_from, FILTER_VALIDATE_EMAIL)) {
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200477 $_SESSION['return'][] = array(
478 'type' => 'danger',
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100479 'log' => array(__FUNCTION__),
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200480 'msg' => 'from_invalid'
481 );
482 return false;
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100483 }
484 if (empty($mass_subject)) {
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200485 $_SESSION['return'][] = array(
486 'type' => 'danger',
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100487 'log' => array(__FUNCTION__),
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200488 'msg' => 'subject_empty'
489 );
490 return false;
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100491 }
492 if (empty($mass_text)) {
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200493 $_SESSION['return'][] = array(
494 'type' => 'danger',
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100495 'log' => array(__FUNCTION__),
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200496 'msg' => 'text_empty'
497 );
498 return false;
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100499 }
500 $domains = array_merge(mailbox('get', 'domains'), mailbox('get', 'alias_domains'));
501 foreach ($domains as $domain) {
502 foreach (mailbox('get', 'mailboxes', $domain) as $mailbox) {
503 $mailboxes[] = $mailbox;
504 }
505 }
506 if (!empty($includes)) {
507 $rcpts = array_intersect($mailboxes, $includes);
508 }
509 elseif (!empty($excludes)) {
510 $rcpts = array_diff($mailboxes, $excludes);
511 }
512 else {
513 $rcpts = $mailboxes;
514 }
515 if (!empty($rcpts)) {
516 ini_set('max_execution_time', 0);
517 ini_set('max_input_time', 0);
518 $mail = new PHPMailer;
519 $mail->Timeout = 10;
520 $mail->SMTPOptions = array(
521 'ssl' => array(
522 'verify_peer' => false,
523 'verify_peer_name' => false,
524 'allow_self_signed' => true
525 )
526 );
527 $mail->isSMTP();
528 $mail->Host = 'dovecot-mailcow';
529 $mail->SMTPAuth = false;
530 $mail->Port = 24;
531 $mail->setFrom($mass_from);
532 $mail->Subject = $mass_subject;
533 $mail->CharSet ="UTF-8";
534 if (!empty($mass_html)) {
535 $mail->Body = $mass_html;
536 $mail->AltBody = $mass_text;
537 }
538 else {
539 $mail->Body = $mass_text;
540 }
541 $mail->XMailer = 'MooMassMail';
542 foreach ($rcpts as $rcpt) {
543 $mail->AddAddress($rcpt);
544 if (!$mail->send()) {
545 $_SESSION['return'][] = array(
546 'type' => 'warning',
547 'log' => array(__FUNCTION__),
548 'msg' => 'Mailer error (RCPT "' . htmlspecialchars($rcpt) . '"): ' . str_replace('https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting', '', $mail->ErrorInfo)
549 );
550 }
551 $mail->ClearAllRecipients();
552 }
553 }
554 $_SESSION['return'][] = array(
555 'type' => 'success',
556 'log' => array(__FUNCTION__),
557 'msg' => 'Mass mail job completed, sent ' . count($rcpts) . ' mails'
558 );
559}
560function logger($_data = false) {
561 /*
562 logger() will be called as last function
563 To manually log a message, logger needs to be called like below.
564
565 logger(array(
566 'return' => array(
567 array(
568 'type' => 'danger',
569 'log' => array(__FUNCTION__),
570 'msg' => $err
571 )
572 )
573 ));
574
575 These messages will not be printed as alert box.
576 To do so, push them to $_SESSION['return'] and do not call logger as they will be included automatically:
577
578 $_SESSION['return'][] = array(
579 'type' => 'danger',
580 'log' => array(__FUNCTION__, $user, '*'),
581 'msg' => $err
582 );
583 */
584 global $pdo;
585 if (!$_data) {
586 $_data = $_SESSION;
587 }
588 if (!empty($_data['return'])) {
589 $task = substr(strtoupper(md5(uniqid(rand(), true))), 0, 6);
590 foreach ($_data['return'] as $return) {
591 $type = $return['type'];
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200592 $msg = null;
593 if (isset($return['msg'])) {
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +0200594 $msg = json_encode($return['msg'], JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200595 }
596 $call = null;
597 if (isset($return['log'])) {
598 $call = json_encode($return['log'], JSON_UNESCAPED_UNICODE);
599 }
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100600 if (!empty($_SESSION["dual-login"]["username"])) {
601 $user = $_SESSION["dual-login"]["username"] . ' => ' . $_SESSION['mailcow_cc_username'];
602 $role = $_SESSION["dual-login"]["role"] . ' => ' . $_SESSION['mailcow_cc_role'];
603 }
604 elseif (!empty($_SESSION['mailcow_cc_username'])) {
605 $user = $_SESSION['mailcow_cc_username'];
606 $role = $_SESSION['mailcow_cc_role'];
607 }
608 else {
609 $user = 'unauthenticated';
610 $role = 'unauthenticated';
611 }
612 // We cannot log when logs is missing...
613 try {
614 $stmt = $pdo->prepare("INSERT INTO `logs` (`type`, `task`, `msg`, `call`, `user`, `role`, `remote`, `time`) VALUES
615 (:type, :task, :msg, :call, :user, :role, :remote, UNIX_TIMESTAMP())");
616 $stmt->execute(array(
617 ':type' => $type,
618 ':task' => $task,
619 ':call' => $call,
620 ':msg' => $msg,
621 ':user' => $user,
622 ':role' => $role,
623 ':remote' => get_remote_ip()
624 ));
625 }
Matthias Andreas Benkardd63fe562023-11-18 13:18:30 +0100626 catch (PDOException $e) {
627 # handle the exception here, as the exception handler function results in a white page
628 error_log($e->getMessage(), 0);
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100629 }
630 }
631 }
632 else {
633 return true;
634 }
635}
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +0200636function is_local_mailcow_domain($domain) {
637 // True if domain is a locally managed, active primary or alias domain
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200638 global $pdo;
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +0200639 $domain = idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46);
640 if (empty($domain)) {
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200641 return false;
642 }
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +0200643 $stmt = $pdo->prepare("SELECT 1 FROM `domain` WHERE `domain` = :d AND `active` = 1
644 UNION SELECT 1 FROM `alias_domain` WHERE `alias_domain` = :d2 AND `active` = 1 LIMIT 1");
645 $stmt->execute(array(':d' => $domain, ':d2' => $domain));
646 return (bool)$stmt->fetchColumn();
647}
648function hasDomainAccess($username, $role, $domain) {
649 global $pdo;
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200650 if (empty($domain) || !is_valid_domain_name($domain)) {
651 return false;
652 }
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +0200653 if (isset($_SESSION['access_all_exception']) && $_SESSION['access_all_exception'] == "1") {
654 return true;
655 }
656 if (!filter_var($username, FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $username))) {
657 return false;
658 }
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200659 if ($role != 'admin' && $role != 'domainadmin') {
660 return false;
661 }
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100662 if ($role == 'admin') {
663 $stmt = $pdo->prepare("SELECT `domain` FROM `domain`
664 WHERE `domain` = :domain");
665 $stmt->execute(array(':domain' => $domain));
666 $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
667 $stmt = $pdo->prepare("SELECT `alias_domain` FROM `alias_domain`
668 WHERE `alias_domain` = :domain");
669 $stmt->execute(array(':domain' => $domain));
670 $num_results = $num_results + count($stmt->fetchAll(PDO::FETCH_ASSOC));
671 if ($num_results != 0) {
672 return true;
673 }
674 }
675 elseif ($role == 'domainadmin') {
676 $stmt = $pdo->prepare("SELECT `domain` FROM `domain_admins`
677 WHERE (
678 `active`='1'
679 AND `username` = :username
680 AND (`domain` = :domain1 OR `domain` = (SELECT `target_domain` FROM `alias_domain` WHERE `alias_domain` = :domain2))
681 )");
682 $stmt->execute(array(':username' => $username, ':domain1' => $domain, ':domain2' => $domain));
683 $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
684 if (!empty($num_results)) {
685 return true;
686 }
687 }
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200688 return false;
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100689}
690function hasMailboxObjectAccess($username, $role, $object) {
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200691 global $pdo;
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +0200692 if (isset($_SESSION['access_all_exception']) && $_SESSION['access_all_exception'] == "1") {
693 return true;
694 }
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200695 if (empty($username) || empty($role) || empty($object)) {
696 return false;
697 }
698 if (!filter_var(html_entity_decode(rawurldecode($username)), FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $username))) {
699 return false;
700 }
701 if ($role != 'admin' && $role != 'domainadmin' && $role != 'user') {
702 return false;
703 }
704 if ($username == $object) {
705 return true;
706 }
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100707 $stmt = $pdo->prepare("SELECT `domain` FROM `mailbox` WHERE `username` = :object");
708 $stmt->execute(array(':object' => $object));
709 $row = $stmt->fetch(PDO::FETCH_ASSOC);
710 if (isset($row['domain']) && hasDomainAccess($username, $role, $row['domain'])) {
711 return true;
712 }
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200713 return false;
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100714}
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200715// does also verify mailboxes as a mailbox is a alias == goto
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100716function hasAliasObjectAccess($username, $role, $object) {
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200717 global $pdo;
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +0200718 if (isset($_SESSION['access_all_exception']) && $_SESSION['access_all_exception'] == "1") {
719 return true;
720 }
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200721 if (empty($username) || empty($role) || empty($object)) {
722 return false;
723 }
724 if (!filter_var(html_entity_decode(rawurldecode($username)), FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $username))) {
725 return false;
726 }
727 if ($role != 'admin' && $role != 'domainadmin' && $role != 'user') {
728 return false;
729 }
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100730 $stmt = $pdo->prepare("SELECT `domain` FROM `alias` WHERE `address` = :object");
731 $stmt->execute(array(':object' => $object));
732 $row = $stmt->fetch(PDO::FETCH_ASSOC);
733 if (isset($row['domain']) && hasDomainAccess($username, $role, $row['domain'])) {
734 return true;
735 }
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200736 return false;
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100737}
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +0200738function hasACLAccess($type) {
739 if (isset($_SESSION['access_all_exception']) && $_SESSION['access_all_exception'] == "1") {
740 return true;
741 }
742 if (isset($_SESSION['acl'][$type]) && $_SESSION['acl'][$type] == "1") {
743 return true;
744 }
745
746 return false;
747}
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100748function pem_to_der($pem_key) {
749 // Need to remove BEGIN/END PUBLIC KEY
750 $lines = explode("\n", trim($pem_key));
751 unset($lines[count($lines)-1]);
752 unset($lines[0]);
753 return base64_decode(implode('', $lines));
754}
755function expand_ipv6($ip) {
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200756 $hex = unpack("H*hex", inet_pton($ip));
757 $ip = substr(preg_replace("/([A-f0-9]{4})/", "$1:", $hex['hex']), 0, -1);
758 return $ip;
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100759}
760function generate_tlsa_digest($hostname, $port, $starttls = null) {
761 if (!is_valid_domain_name($hostname)) {
762 return "Not a valid hostname";
763 }
764 if (empty($starttls)) {
765 $context = stream_context_create(array("ssl" => array("capture_peer_cert" => true, 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true)));
766 $stream = stream_socket_client('ssl://' . $hostname . ':' . $port, $error_nr, $error_msg, 5, STREAM_CLIENT_CONNECT, $context);
767 if (!$stream) {
768 $error_msg = isset($error_msg) ? $error_msg : '-';
769 return $error_nr . ': ' . $error_msg;
770 }
771 }
772 else {
773 $stream = stream_socket_client('tcp://' . $hostname . ':' . $port, $error_nr, $error_msg, 5);
774 if (!$stream) {
775 return $error_nr . ': ' . $error_msg;
776 }
777 $banner = fread($stream, 512 );
778 if (preg_match("/^220/i", $banner)) { // SMTP
779 fwrite($stream,"HELO tlsa.generator.local\r\n");
780 fread($stream, 512);
781 fwrite($stream,"STARTTLS\r\n");
782 fread($stream, 512);
783 }
784 elseif (preg_match("/imap.+starttls/i", $banner)) { // IMAP
785 fwrite($stream,"A1 STARTTLS\r\n");
786 fread($stream, 512);
787 }
788 elseif (preg_match("/^\+OK/", $banner)) { // POP3
789 fwrite($stream,"STLS\r\n");
790 fread($stream, 512);
791 }
792 elseif (preg_match("/^OK/m", $banner)) { // Sieve
793 fwrite($stream,"STARTTLS\r\n");
794 fread($stream, 512);
795 }
796 else {
797 return 'Unknown banner: "' . htmlspecialchars(trim($banner)) . '"';
798 }
799 // Upgrade connection
800 stream_set_blocking($stream, true);
801 stream_context_set_option($stream, 'ssl', 'capture_peer_cert', true);
802 stream_context_set_option($stream, 'ssl', 'verify_peer', false);
803 stream_context_set_option($stream, 'ssl', 'verify_peer_name', false);
804 stream_context_set_option($stream, 'ssl', 'allow_self_signed', true);
805 stream_socket_enable_crypto($stream, true, STREAM_CRYPTO_METHOD_ANY_CLIENT);
806 stream_set_blocking($stream, false);
807 }
808 $params = stream_context_get_params($stream);
809 if (!empty($params['options']['ssl']['peer_certificate'])) {
810 $key_resource = openssl_pkey_get_public($params['options']['ssl']['peer_certificate']);
811 // We cannot get ['rsa']['n'], the binary data would contain BEGIN/END PUBLIC KEY
812 $key_data = openssl_pkey_get_details($key_resource)['key'];
813 return '3 1 1 ' . openssl_digest(pem_to_der($key_data), 'sha256');
814 }
815 else {
816 return 'Error: Cannot read peer certificate';
817 }
818}
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200819function alertbox_log_parser($_data) {
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100820 global $lang;
821 if (isset($_data['return'])) {
822 foreach ($_data['return'] as $return) {
823 // Get type
824 $type = $return['type'];
825 // If a lang[type][msg] string exists, use it as message
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200826 if (isset($return['type']) && isset($return['msg']) && !is_array($return['msg'])) {
827 if (isset($lang[$return['type']][$return['msg']])) {
828 $msg = $lang[$return['type']][$return['msg']];
829 }
830 else {
831 $msg = $return['msg'];
832 }
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100833 }
834 // If msg is an array, use first element as language string and run printf on it with remaining array elements
835 elseif (is_array($return['msg'])) {
836 $msg = array_shift($return['msg']);
837 $msg = vsprintf(
838 $lang[$return['type']][$msg],
839 $return['msg']
840 );
841 }
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100842 else {
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200843 $msg = '-';
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100844 }
845 $log_array[] = array('msg' => $msg, 'type' => json_encode($type));
846 }
847 if (!empty($log_array)) {
848 return $log_array;
849 }
850 }
851 return false;
852}
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200853function verify_salted_hash($hash, $password, $algo, $salt_length) {
854 // Decode hash
855 $dhash = base64_decode($hash);
856 // Get first n bytes of binary which equals a SSHA hash
857 $ohash = substr($dhash, 0, $salt_length);
858 // Remove SSHA hash from decoded hash to get original salt string
859 $osalt = str_replace($ohash, '', $dhash);
860 // Check single salted SSHA hash against extracted hash
861 if (hash_equals(hash($algo, $password . $osalt, true), $ohash)) {
862 return true;
863 }
864 return false;
865}
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100866function verify_hash($hash, $password) {
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200867 if (preg_match('/^{(.+)}(.+)/i', $hash, $hash_array)) {
868 $scheme = strtoupper($hash_array[1]);
869 $hash = $hash_array[2];
870 switch ($scheme) {
871 case "ARGON2I":
872 case "ARGON2ID":
873 case "BLF-CRYPT":
874 case "CRYPT":
875 case "DES-CRYPT":
876 case "MD5-CRYPT":
877 case "MD5":
878 case "SHA256-CRYPT":
879 case "SHA512-CRYPT":
880 return password_verify($password, $hash);
881
882 case "CLEAR":
883 case "CLEARTEXT":
884 case "PLAIN":
885 return $password == $hash;
886
887 case "LDAP-MD5":
888 $hash = base64_decode($hash);
889 return hash_equals(hash('md5', $password, true), $hash);
890
891 case "PBKDF2":
892 $components = explode('$', $hash);
893 $salt = $components[2];
894 $rounds = $components[3];
895 $hash = $components[4];
896 return hash_equals(hash_pbkdf2('sha1', $password, $salt, $rounds), $hash);
897
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +0200898 case "PBKDF2-SHA512":
899 // Handle FreeIPA-style hash: {PBKDF2-SHA512}10000$<base64_salt>$<base64_hash>
900 $components = explode('$', $hash);
901 if (count($components) !== 3) return false;
902
903 // 1st part: iteration count (integer)
904 $iterations = intval($components[0]);
905 if ($iterations <= 0) return false;
906
907 // 2nd part: salt (base64-encoded)
908 $salt = $components[1];
909 // 3rd part: hash (base64-encoded)
910 $stored_hash_b64 = $components[2];
911
912 // Decode salt and hash from base64
913 $salt_bin = base64_decode($salt, true);
914 $hash_bin = base64_decode($stored_hash_b64, true);
915 if ($salt_bin === false || $hash_bin === false) return false;
916 // Get length of hash in bytes
917 $hash_len = strlen($hash_bin);
918 if ($hash_len === 0) return false;
919
920 // Calculate PBKDF2-SHA512 hash for provided password
921 $test_hash = hash_pbkdf2('sha512', $password, $salt_bin, $iterations, $hash_len, true);
922 return hash_equals($hash_bin, $test_hash);
923
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200924 case "PLAIN-MD4":
925 return hash_equals(hash('md4', $password), $hash);
926
927 case "PLAIN-MD5":
928 return md5($password) == $hash;
929
930 case "PLAIN-TRUNC":
931 $components = explode('-', $hash);
932 if (count($components) > 1) {
933 $trunc_len = $components[0];
934 $trunc_password = $components[1];
935
936 return substr($password, 0, $trunc_len) == $trunc_password;
937 } else {
938 return $password == $hash;
939 }
940
941 case "SHA":
942 case "SHA1":
943 case "SHA256":
944 case "SHA512":
945 // SHA is an alias for SHA1
946 $scheme = $scheme == "SHA" ? "sha1" : strtolower($scheme);
947 $hash = base64_decode($hash);
948 return hash_equals(hash($scheme, $password, true), $hash);
949
950 case "SMD5":
951 return verify_salted_hash($hash, $password, 'md5', 16);
952
953 case "SSHA":
954 return verify_salted_hash($hash, $password, 'sha1', 20);
955
956 case "SSHA256":
957 return verify_salted_hash($hash, $password, 'sha256', 32);
958
959 case "SSHA512":
960 return verify_salted_hash($hash, $password, 'sha512', 64);
961
962 default:
963 return false;
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100964 }
965 }
966 return false;
967}
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100968function formatBytes($size, $precision = 2) {
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200969 if(!is_numeric($size)) {
970 return "0";
971 }
972 $base = log($size, 1024);
973 $suffixes = array(' Byte', ' KiB', ' MiB', ' GiB', ' TiB');
974 if ($size == "0") {
975 return "0";
976 }
977 return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100978}
Matthias Andreas Benkardd63fe562023-11-18 13:18:30 +0100979function update_sogo_static_view($mailbox = null) {
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100980 if (getenv('SKIP_SOGO') == "y") {
981 return true;
982 }
983 global $pdo;
984 global $lang;
Matthias Andreas Benkardd63fe562023-11-18 13:18:30 +0100985
986 $mailbox_exists = false;
987 if ($mailbox !== null) {
988 // Check if the mailbox exists
989 $stmt = $pdo->prepare("SELECT username FROM mailbox WHERE username = :mailbox AND active = '1'");
990 $stmt->execute(array(':mailbox' => $mailbox));
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +0200991 $row = $stmt->fetch(PDO::FETCH_ASSOC);
Matthias Andreas Benkardd63fe562023-11-18 13:18:30 +0100992 if ($row){
993 $mailbox_exists = true;
994 }
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100995 }
Matthias Andreas Benkardd63fe562023-11-18 13:18:30 +0100996
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +0200997 // generate random password for sogo to deny direct login
998 $random_password = base64_encode(openssl_random_pseudo_bytes(24));
999 $random_salt = base64_encode(openssl_random_pseudo_bytes(16));
1000 $random_hash = '{SSHA256}' . base64_encode(hash('sha256', base64_decode($password) . $salt, true) . $salt);
1001
1002 $subquery = "GROUP BY mailbox.username";
Matthias Andreas Benkardd63fe562023-11-18 13:18:30 +01001003 if ($mailbox_exists) {
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001004 $subquery = "AND mailbox.username = :mailbox";
Matthias Andreas Benkardd63fe562023-11-18 13:18:30 +01001005 }
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001006 $query = "INSERT INTO _sogo_static_view (`c_uid`, `domain`, `c_name`, `c_password`, `c_cn`, `mail`, `aliases`, `ad_aliases`, `ext_acl`, `kind`, `multiple_bookings`)
1007 SELECT
1008 mailbox.username,
1009 mailbox.domain,
1010 mailbox.username,
1011 :random_hash,
1012 mailbox.name,
1013 mailbox.username,
1014 IFNULL(GROUP_CONCAT(ga.aliases ORDER BY ga.aliases SEPARATOR ' '), ''),
1015 IFNULL(gda.ad_alias, ''),
1016 IFNULL(external_acl.send_as_acl, ''),
1017 mailbox.kind,
1018 mailbox.multiple_bookings
1019 FROM
1020 mailbox
1021 LEFT OUTER JOIN grouped_mail_aliases ga ON ga.username REGEXP CONCAT('(^|,)', mailbox.username, '($|,)')
1022 LEFT OUTER JOIN grouped_domain_alias_address gda ON gda.username = mailbox.username
1023 LEFT OUTER JOIN grouped_sender_acl_external external_acl ON external_acl.username = mailbox.username
1024 WHERE
1025 mailbox.active = '1'
1026 $subquery
1027 ON DUPLICATE KEY UPDATE
1028 `domain` = VALUES(`domain`),
1029 `c_name` = VALUES(`c_name`),
1030 `c_password` = VALUES(`c_password`),
1031 `c_cn` = VALUES(`c_cn`),
1032 `mail` = VALUES(`mail`),
1033 `aliases` = VALUES(`aliases`),
1034 `ad_aliases` = VALUES(`ad_aliases`),
1035 `ext_acl` = VALUES(`ext_acl`),
1036 `kind` = VALUES(`kind`),
1037 `multiple_bookings` = VALUES(`multiple_bookings`)";
1038
1039
1040 if ($mailbox_exists) {
1041 $stmt = $pdo->prepare($query);
1042 $stmt->execute(array(
1043 ':random_hash' => $random_hash,
1044 ':mailbox' => $mailbox
1045 ));
1046 } else {
1047 $stmt = $pdo->prepare($query);
1048 $stmt->execute(array(
1049 ':random_hash' => $random_hash
1050 ));
1051 }
1052
Matthias Andreas Benkardd63fe562023-11-18 13:18:30 +01001053 $stmt = $pdo->query("DELETE FROM _sogo_static_view WHERE `c_uid` NOT IN (SELECT `username` FROM `mailbox` WHERE `active` = '1');");
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001054
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001055 flush_memcached();
1056}
1057function edit_user_account($_data) {
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001058 global $lang;
1059 global $pdo;
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001060
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001061 $_data_log = $_data;
1062 !isset($_data_log['user_new_pass']) ?: $_data_log['user_new_pass'] = '*';
1063 !isset($_data_log['user_new_pass2']) ?: $_data_log['user_new_pass2'] = '*';
1064 !isset($_data_log['user_old_pass']) ?: $_data_log['user_old_pass'] = '*';
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001065
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001066 $username = $_SESSION['mailcow_cc_username'];
1067 $role = $_SESSION['mailcow_cc_role'];
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001068 $password_old = $_data['user_old_pass'];
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001069 $pw_recovery_email = $_data['pw_recovery_email'];
1070
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001071 if (filter_var($username, FILTER_VALIDATE_EMAIL === false) || $role != 'user') {
1072 $_SESSION['return'][] = array(
1073 'type' => 'danger',
1074 'log' => array(__FUNCTION__, $_data_log),
1075 'msg' => 'access_denied'
1076 );
1077 return false;
1078 }
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001079
1080 // edit password
1081 $is_forced_pw_update = !empty($_SESSION['pending_pw_update']);
1082 if (((!empty($password_old) || $is_forced_pw_update) && !empty($_data['user_new_pass']) && !empty($_data['user_new_pass2']))) {
1083 // Only verify old password if this is NOT a forced password update
1084 if (!$is_forced_pw_update) {
1085 $stmt = $pdo->prepare("SELECT `password` FROM `mailbox`
1086 WHERE `kind` NOT REGEXP 'location|thing|group'
1087 AND `username` = :user AND authsource = 'mailcow'");
1088 $stmt->execute(array(':user' => $username));
1089 $row = $stmt->fetch(PDO::FETCH_ASSOC);
1090
1091 if (!verify_hash($row['password'], $password_old)) {
1092 $_SESSION['return'][] = array(
1093 'type' => 'danger',
1094 'log' => array(__FUNCTION__, $_data_log),
1095 'msg' => 'access_denied'
1096 );
1097 return false;
1098 }
1099 }
1100
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001101 $password_new = $_data['user_new_pass'];
1102 $password_new2 = $_data['user_new_pass2'];
1103 if (password_check($password_new, $password_new2) !== true) {
1104 return false;
1105 }
1106 $password_hashed = hash_password($password_new);
1107 $stmt = $pdo->prepare("UPDATE `mailbox` SET `password` = :password_hashed,
1108 `attributes` = JSON_SET(`attributes`, '$.force_pw_update', '0'),
1109 `attributes` = JSON_SET(`attributes`, '$.passwd_update', NOW())
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001110 WHERE `username` = :username AND authsource = 'mailcow'");
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001111 $stmt->execute(array(
1112 ':password_hashed' => $password_hashed,
1113 ':username' => $username
1114 ));
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001115 $_SESSION['pending_pw_update'] = false;
1116
1117 update_sogo_static_view();
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001118 }
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001119 // edit password recovery email
1120 elseif (!empty($password_old) && isset($pw_recovery_email)) {
1121 if (!isset($_SESSION['acl']['pw_reset']) || $_SESSION['acl']['pw_reset'] != "1" ) {
1122 $_SESSION['return'][] = array(
1123 'type' => 'danger',
1124 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),
1125 'msg' => 'access_denied'
1126 );
1127 return false;
1128 }
1129
1130 $stmt = $pdo->prepare("SELECT `password` FROM `mailbox`
1131 WHERE `kind` NOT REGEXP 'location|thing|group'
1132 AND `username` = :user AND authsource = 'mailcow'");
1133 $stmt->execute(array(':user' => $username));
1134 $row = $stmt->fetch(PDO::FETCH_ASSOC);
1135
1136 if (!verify_hash($row['password'], $password_old)) {
1137 $_SESSION['return'][] = array(
1138 'type' => 'danger',
1139 'log' => array(__FUNCTION__, $_data_log),
1140 'msg' => 'access_denied'
1141 );
1142 return false;
1143 }
1144
1145 $pw_recovery_email = (!filter_var($pw_recovery_email, FILTER_VALIDATE_EMAIL)) ? '' : $pw_recovery_email;
1146 $stmt = $pdo->prepare("UPDATE `mailbox` SET `attributes` = JSON_SET(`attributes`, '$.recovery_email', :recovery_email)
1147 WHERE `username` = :username AND authsource = 'mailcow'");
1148 $stmt->execute(array(
1149 ':recovery_email' => $pw_recovery_email,
1150 ':username' => $username
1151 ));
1152 }
1153
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001154 $_SESSION['return'][] = array(
1155 'type' => 'success',
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001156 'log' => array(__FUNCTION__, $_data_log),
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001157 'msg' => array('mailbox_modified', htmlspecialchars($username))
1158 );
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001159}
1160function user_get_alias_details($username) {
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001161 global $pdo;
1162 global $lang;
1163 $data['direct_aliases'] = array();
1164 $data['shared_aliases'] = array();
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001165 if ($_SESSION['mailcow_cc_role'] == "user") {
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001166 $username = $_SESSION['mailcow_cc_username'];
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001167 }
1168 if (!filter_var($username, FILTER_VALIDATE_EMAIL)) {
1169 return false;
1170 }
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001171 if (!hasMailboxObjectAccess($username, $_SESSION['mailcow_cc_role'], $username)) {
1172 return false;
1173 }
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001174 $data['address'] = $username;
1175 $stmt = $pdo->prepare("SELECT `address` AS `shared_aliases`, `public_comment` FROM `alias`
1176 WHERE `goto` REGEXP :username_goto
1177 AND `address` NOT LIKE '@%'
1178 AND `goto` != :username_goto2
1179 AND `address` != :username_address");
1180 $stmt->execute(array(
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001181 ':username_goto' => '(^|,)'.preg_quote($username, '/').'($|,)',
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001182 ':username_goto2' => $username,
1183 ':username_address' => $username
1184 ));
1185 $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
1186 while ($row = array_shift($run)) {
1187 $data['shared_aliases'][$row['shared_aliases']]['public_comment'] = htmlspecialchars($row['public_comment']);
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001188 //$data['shared_aliases'][] = $row['shared_aliases'];
1189 }
1190
1191 $stmt = $pdo->prepare("SELECT `address` AS `direct_aliases`, `public_comment` FROM `alias`
1192 WHERE `goto` = :username_goto
1193 AND `address` NOT LIKE '@%'
1194 AND `address` != :username_address");
1195 $stmt->execute(
1196 array(
1197 ':username_goto' => $username,
1198 ':username_address' => $username
1199 ));
1200 $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
1201 while ($row = array_shift($run)) {
1202 $data['direct_aliases'][$row['direct_aliases']]['public_comment'] = htmlspecialchars($row['public_comment']);
1203 }
1204 $stmt = $pdo->prepare("SELECT CONCAT(local_part, '@', alias_domain) AS `ad_alias`, `alias_domain` FROM `mailbox`
1205 LEFT OUTER JOIN `alias_domain` on `target_domain` = `domain`
1206 WHERE `username` = :username ;");
1207 $stmt->execute(array(':username' => $username));
1208 $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
1209 while ($row = array_shift($run)) {
1210 if (empty($row['ad_alias'])) {
1211 continue;
1212 }
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001213 $data['direct_aliases'][$row['ad_alias']]['public_comment'] = $lang['add']['alias_domain'];
1214 $data['alias_domains'][] = $row['alias_domain'];
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001215 }
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001216 $stmt = $pdo->prepare("SELECT IFNULL(GROUP_CONCAT(`send_as` SEPARATOR ', '), '') AS `send_as` FROM `sender_acl` WHERE `logged_in_as` = :username AND `send_as` NOT LIKE '@%';");
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001217 $stmt->execute(array(':username' => $username));
1218 $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
1219 while ($row = array_shift($run)) {
1220 $data['aliases_also_send_as'] = $row['send_as'];
1221 }
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001222 $stmt = $pdo->prepare("SELECT CONCAT_WS(', ', IFNULL(GROUP_CONCAT(DISTINCT `send_as` SEPARATOR ', '), ''), 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 '@%';");
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001223 $stmt->execute(array(':username' => $username));
1224 $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
1225 while ($row = array_shift($run)) {
1226 $data['aliases_send_as_all'] = $row['send_as'];
1227 }
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001228 $stmt = $pdo->prepare("SELECT IFNULL(GROUP_CONCAT(`address` SEPARATOR ', '), '') as `address` FROM `alias` WHERE `goto` REGEXP :username AND `address` LIKE '@%';");
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001229 $stmt->execute(array(':username' => '(^|,)'.preg_quote($username, '/').'($|,)'));
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001230 $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
1231 while ($row = array_shift($run)) {
1232 $data['is_catch_all'] = $row['address'];
1233 }
1234 return $data;
1235}
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001236function is_valid_domain_name($domain_name, $options = array()) {
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001237 if (empty($domain_name)) {
1238 return false;
1239 }
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001240
1241 // Convert domain name to ASCII for validation
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001242 $domain_name = idn_to_ascii($domain_name, 0, INTL_IDNA_VARIANT_UTS46);
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001243
1244 if (isset($options['allow_wildcard']) && $options['allow_wildcard'] == true) {
1245 // Remove '*.' if wildcard subdomains are allowed
1246 if (strpos($domain_name, '*.') === 0) {
1247 $domain_name = substr($domain_name, 2);
1248 }
1249 }
1250
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001251 return (preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $domain_name)
1252 && preg_match("/^.{1,253}$/", $domain_name)
1253 && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $domain_name));
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001254}
1255function set_tfa($_data) {
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001256 global $pdo;
1257 global $yubi;
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001258 global $tfa;
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001259 global $iam_settings;
1260
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001261 $_data_log = $_data;
1262 !isset($_data_log['confirm_password']) ?: $_data_log['confirm_password'] = '*';
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01001263
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001264 // skip password check if this is a forced TFA enrollment after login
1265 if (!empty($_SESSION['pending_tfa_setup'])) {
1266 $username = $_SESSION['mailcow_cc_username'];
1267 if (empty($username) || !isset($_SESSION['mailcow_cc_role'])) {
1268 $_SESSION['return'][] = array('type' => 'danger', 'log' => array(__FUNCTION__, $_data_log), 'msg' => 'access_denied');
1269 return false;
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001270 }
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001271 } else {
1272 $username = $_SESSION['mailcow_cc_username'];
1273 $access_denied = null;
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01001274
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001275 if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) $access_denied = true;
1276
1277 // check admin password
1278 if ($access_denied === null) {
1279 $stmt = $pdo->prepare("SELECT `password` FROM `admin` WHERE `username` = :username");
1280 $stmt->execute(array(':username' => $username));
1281 $row = $stmt->fetch(PDO::FETCH_ASSOC);
1282 if ($row) {
1283 if (!verify_hash($row['password'], $_data["confirm_password"])) $access_denied = true;
1284 else $access_denied = false;
1285 }
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001286 }
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01001287
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001288 // check mailbox password
1289 if ($access_denied === null) {
1290 $stmt = $pdo->prepare("SELECT `password`, `authsource` FROM `mailbox` WHERE `username` = :username");
1291 $stmt->execute(array(':username' => $username));
1292 $row = $stmt->fetch(PDO::FETCH_ASSOC);
1293 if ($row) {
1294 if ($row['authsource'] == 'ldap'){
1295 if (!ldap_mbox_login($username, $_data["confirm_password"], $iam_settings)) $access_denied = true;
1296 else $access_denied = false;
1297 } else {
1298 if (!verify_hash($row['password'], $_data["confirm_password"])) $access_denied = true;
1299 else $access_denied = false;
1300 }
1301 }
1302 }
1303
1304 if ($access_denied) {
1305 $_SESSION['return'][] = array('type' => 'danger', 'log' => array(__FUNCTION__, $_data_log), 'msg' => 'access_denied');
1306 return false;
1307 }
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01001308 }
1309
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001310 switch ($_data["tfa_method"]) {
1311 case "yubi_otp":
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001312 $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
1313 $yubico_id = $_data['yubico_id'];
1314 $yubico_key = $_data['yubico_key'];
1315 $yubi = new Auth_Yubico($yubico_id, $yubico_key);
1316 if (!$yubi) {
1317 $_SESSION['return'][] = array(
1318 'type' => 'danger',
1319 'log' => array(__FUNCTION__, $_data_log),
1320 'msg' => 'access_denied'
1321 );
1322 return false;
1323 }
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001324 if (!ctype_alnum($_data["otp_token"]) || strlen($_data["otp_token"]) != 44) {
1325 $_SESSION['return'][] = array(
1326 'type' => 'danger',
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001327 'log' => array(__FUNCTION__, $_data_log),
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001328 'msg' => 'tfa_token_invalid'
1329 );
1330 return false;
1331 }
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001332 $yauth = $yubi->verify($_data["otp_token"]);
1333 if (PEAR::isError($yauth)) {
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001334 $_SESSION['return'][] = array(
1335 'type' => 'danger',
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001336 'log' => array(__FUNCTION__, $_data_log),
1337 'msg' => array('yotp_verification_failed', $yauth->getMessage())
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001338 );
1339 return false;
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001340 }
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001341 try {
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001342 // We could also do a modhex translation here
1343 $yubico_modhex_id = substr($_data["otp_token"], 0, 12);
1344 $stmt = $pdo->prepare("DELETE FROM `tfa`
1345 WHERE `username` = :username
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01001346 AND (`authmech` = 'yubi_otp' AND `secret` LIKE :modhex)");
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001347 $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id));
1348 $stmt = $pdo->prepare("INSERT INTO `tfa` (`key_id`, `username`, `authmech`, `active`, `secret`) VALUES
1349 (:key_id, :username, 'yubi_otp', '1', :secret)");
1350 $stmt->execute(array(':key_id' => $key_id, ':username' => $username, ':secret' => $yubico_id . ':' . $yubico_key . ':' . $yubico_modhex_id));
1351 }
1352 catch (PDOException $e) {
1353 $_SESSION['return'][] = array(
1354 'type' => 'danger',
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001355 'log' => array(__FUNCTION__, $_data_log),
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001356 'msg' => array('mysql_error', $e)
1357 );
1358 return false;
1359 }
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001360 unset($_SESSION['pending_tfa_setup']);
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001361 $_SESSION['return'][] = array(
1362 'type' => 'success',
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001363 'log' => array(__FUNCTION__, $_data_log),
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001364 'msg' => array('object_modified', htmlspecialchars($username))
1365 );
1366 break;
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001367 case "totp":
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001368 $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
1369 if ($tfa->verifyCode($_POST['totp_secret'], $_POST['totp_confirm_token']) === true) {
Matthias Andreas Benkardb4b5cc12021-12-28 18:02:04 +01001370 //$stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
1371 //$stmt->execute(array(':username' => $username));
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001372 $stmt = $pdo->prepare("INSERT INTO `tfa` (`username`, `key_id`, `authmech`, `secret`, `active`) VALUES (?, ?, 'totp', ?, '1')");
1373 $stmt->execute(array($username, $key_id, $_POST['totp_secret']));
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001374 unset($_SESSION['pending_tfa_setup']);
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001375 $_SESSION['return'][] = array(
1376 'type' => 'success',
1377 'log' => array(__FUNCTION__, $_data_log),
1378 'msg' => array('object_modified', $username)
1379 );
1380 }
1381 else {
1382 $_SESSION['return'][] = array(
1383 'type' => 'danger',
1384 'log' => array(__FUNCTION__, $_data_log),
1385 'msg' => 'totp_verification_failed'
1386 );
1387 }
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001388 break;
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01001389 case "webauthn":
1390 $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
1391
1392 $stmt = $pdo->prepare("INSERT INTO `tfa` (`username`, `key_id`, `authmech`, `keyHandle`, `publicKey`, `certificate`, `counter`, `active`)
1393 VALUES (?, ?, 'webauthn', ?, ?, ?, ?, '1')");
1394 $stmt->execute(array(
1395 $username,
1396 $key_id,
1397 base64_encode($_data['registration']->credentialId),
1398 $_data['registration']->credentialPublicKey,
1399 $_data['registration']->certificate,
1400 0
1401 ));
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001402
1403 unset($_SESSION['pending_tfa_setup']);
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01001404 $_SESSION['return'][] = array(
1405 'type' => 'success',
1406 'log' => array(__FUNCTION__, $_data_log),
1407 'msg' => array('object_modified', $username)
1408 );
1409 break;
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001410 case "none":
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001411 // Block TFA removal if force_tfa policy is active
1412 $is_forced_tfa = false;
1413 if ($_SESSION['mailcow_cc_role'] === 'user') {
1414 $stmt_check = $pdo->prepare("SELECT JSON_EXTRACT(`attributes`, '$.force_tfa') FROM `mailbox` WHERE `username` = ?");
1415 $stmt_check->execute(array($username));
1416 $is_forced_tfa = ($stmt_check->fetchColumn() == '1');
1417 } else {
1418 $stmt_check = $pdo->prepare("SELECT JSON_EXTRACT(`attributes`, '$.force_tfa') FROM `admin` WHERE `username` = ?");
1419 $stmt_check->execute(array($username));
1420 $is_forced_tfa = ($stmt_check->fetchColumn() == '1');
1421 }
1422 if ($is_forced_tfa) {
1423 $_SESSION['return'][] = array(
1424 'type' => 'danger',
1425 'log' => array(__FUNCTION__, $_data_log),
1426 'msg' => 'tfa_removal_blocked'
1427 );
1428 return false;
1429 }
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001430 $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
1431 $stmt->execute(array(':username' => $username));
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001432 $_SESSION['return'][] = array(
1433 'type' => 'success',
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001434 'log' => array(__FUNCTION__, $_data_log),
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001435 'msg' => array('object_modified', htmlspecialchars($username))
1436 );
1437 break;
1438 }
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001439}
1440function fido2($_data) {
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001441 global $pdo;
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001442 global $WebAuthn;
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001443 $_data_log = $_data;
1444 // Not logging registration data, only actions
1445 // Silent errors for "get" requests
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001446 switch ($_data["action"]) {
1447 case "register":
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001448 $username = $_SESSION['mailcow_cc_username'];
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001449 if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001450 $_SESSION['return'][] = array(
1451 'type' => 'danger',
1452 'log' => array(__FUNCTION__, $_data["action"]),
1453 'msg' => 'access_denied'
1454 );
1455 return false;
1456 }
1457 $stmt = $pdo->prepare("INSERT INTO `fido2` (`username`, `rpId`, `credentialPublicKey`, `certificateChain`, `certificate`, `certificateIssuer`, `certificateSubject`, `signatureCounter`, `AAGUID`, `credentialId`)
1458 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
1459 $stmt->execute(array(
1460 $username,
1461 $_data['registration']->rpId,
1462 $_data['registration']->credentialPublicKey,
1463 $_data['registration']->certificateChain,
1464 $_data['registration']->certificate,
1465 $_data['registration']->certificateIssuer,
1466 $_data['registration']->certificateSubject,
1467 $_data['registration']->signatureCounter,
1468 $_data['registration']->AAGUID,
1469 $_data['registration']->credentialId)
1470 );
1471 $_SESSION['return'][] = array(
1472 'type' => 'success',
1473 'log' => array(__FUNCTION__, $_data["action"]),
1474 'msg' => array('object_modified', $username)
1475 );
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001476 break;
1477 case "get_user_cids":
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001478 // Used to exclude existing CredentialIds while registering
1479 $username = $_SESSION['mailcow_cc_username'];
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001480 if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
1481 return false;
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001482 }
1483 $stmt = $pdo->prepare("SELECT `credentialId` FROM `fido2` WHERE `username` = :username");
1484 $stmt->execute(array(':username' => $username));
1485 $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
1486 while($row = array_shift($rows)) {
1487 $cids[] = $row['credentialId'];
1488 }
1489 return $cids;
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001490 break;
1491 case "get_all_cids":
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001492 // Only needed when using fido2 with username
1493 $stmt = $pdo->query("SELECT `credentialId` FROM `fido2`");
1494 $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
1495 while($row = array_shift($rows)) {
1496 $cids[] = $row['credentialId'];
1497 }
1498 return $cids;
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001499 break;
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001500 case "get_by_b64cid":
1501 if (!isset($_data['cid']) || empty($_data['cid'])) {
1502 return false;
1503 }
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01001504 $stmt = $pdo->prepare("SELECT `certificateSubject`, `username`, `credentialPublicKey`, SHA2(`credentialId`, 256) AS `cid` FROM `fido2` WHERE `credentialId` = :cid");
1505 $stmt->execute(array(':cid' => base64_decode($_data['cid'])));
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001506 $row = $stmt->fetch(PDO::FETCH_ASSOC);
1507 if (empty($row) || empty($row['credentialPublicKey']) || empty($row['username'])) {
1508 return false;
1509 }
1510 $data['pub_key'] = $row['credentialPublicKey'];
1511 $data['username'] = $row['username'];
1512 $data['subject'] = $row['certificateSubject'];
1513 $data['cid'] = $row['cid'];
1514 return $data;
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001515 break;
1516 case "get_friendly_names":
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001517 $username = $_SESSION['mailcow_cc_username'];
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001518 if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
1519 return false;
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001520 }
1521 $stmt = $pdo->prepare("SELECT SHA2(`credentialId`, 256) AS `cid`, `created`, `certificateSubject`, `friendlyName` FROM `fido2` WHERE `username` = :username");
1522 $stmt->execute(array(':username' => $username));
1523 $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
1524 while($row = array_shift($rows)) {
1525 $fns[] = array(
1526 "subject" => (empty($row['certificateSubject']) ? 'Unknown (' . $row['created'] . ')' : $row['certificateSubject']),
1527 "fn" => $row['friendlyName'],
1528 "cid" => $row['cid']
1529 );
1530 }
1531 return $fns;
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001532 break;
1533 case "unset_fido2_key":
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001534 $username = $_SESSION['mailcow_cc_username'];
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001535 if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
1536 $_SESSION['return'][] = array(
1537 'type' => 'danger',
1538 'log' => array(__FUNCTION__, $_data["action"]),
1539 'msg' => 'access_denied'
1540 );
1541 return false;
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001542 }
1543 $stmt = $pdo->prepare("DELETE FROM `fido2` WHERE `username` = :username AND SHA2(`credentialId`, 256) = :cid");
1544 $stmt->execute(array(
1545 ':username' => $username,
1546 ':cid' => $_data['post_data']['unset_fido2_key']
1547 ));
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001548 $_SESSION['return'][] = array(
1549 'type' => 'success',
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001550 'log' => array(__FUNCTION__, $_data_log),
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001551 'msg' => array('object_modified', htmlspecialchars($username))
1552 );
1553 break;
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001554 case "edit_fn":
1555 $username = $_SESSION['mailcow_cc_username'];
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001556 if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
1557 $_SESSION['return'][] = array(
1558 'type' => 'danger',
1559 'log' => array(__FUNCTION__, $_data["action"]),
1560 'msg' => 'access_denied'
1561 );
1562 return false;
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001563 }
1564 $stmt = $pdo->prepare("UPDATE `fido2` SET `friendlyName` = :friendlyName WHERE SHA2(`credentialId`, 256) = :cid AND `username` = :username");
1565 $stmt->execute(array(
1566 ':username' => $username,
1567 ':friendlyName' => $_data['fido2_attrs']['fido2_fn'],
1568 ':cid' => $_data['fido2_attrs']['fido2_cid']
1569 ));
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001570 $_SESSION['return'][] = array(
1571 'type' => 'success',
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001572 'log' => array(__FUNCTION__, $_data_log),
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001573 'msg' => array('object_modified', htmlspecialchars($username))
1574 );
1575 break;
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001576 case "verify":
1577 $role = "";
1578 $tokenData = json_decode($_data['token']);
1579 $clientDataJSON = base64_decode($tokenData->clientDataJSON);
1580 $authenticatorData = base64_decode($tokenData->authenticatorData);
1581 $signature = base64_decode($tokenData->signature);
1582 $id = base64_decode($tokenData->id);
1583 $challenge = $_SESSION['challenge'];
1584 $process_fido2 = fido2(array("action" => "get_by_b64cid", "cid" => $tokenData->id));
1585 if ($process_fido2['pub_key'] === false) {
1586 $_SESSION['return'][] = array(
1587 'type' => 'danger',
1588 'log' => array("fido2_login", $_data['user'], $process_fido2['username']),
1589 'msg' => "login_failed"
1590 );
1591 return false;
1592 }
1593 try {
1594 $WebAuthn->processGet($clientDataJSON, $authenticatorData, $signature, $process_fido2['pub_key'], $challenge, null, $GLOBALS['FIDO2_UV_FLAG_LOGIN'], $GLOBALS['FIDO2_USER_PRESENT_FLAG']);
1595 }
1596 catch (Throwable $ex) {
1597 unset($process_fido2);
1598 $_SESSION['return'][] = array(
1599 'type' => 'danger',
1600 'log' => array("fido2_login", $_data['user'], $process_fido2['username'], $ex->getMessage()),
1601 'msg' => "login_failed"
1602 );
1603 return false;
1604 }
1605 $return = new stdClass();
1606 $return->success = true;
1607 $stmt = $pdo->prepare("SELECT `superadmin` FROM `admin` WHERE `username` = :username");
1608 $stmt->execute(array(':username' => $process_fido2['username']));
1609 $obj_props = $stmt->fetch(PDO::FETCH_ASSOC);
1610 if ($obj_props['superadmin'] === 1 && (!$_data['user'] || $_data['user'] == "admin")) {
1611 $role = "admin";
1612 }
1613 elseif ($obj_props['superadmin'] === 0 && (!$_data['user'] || $_data['user'] == "domainadmin")) {
1614 $role = "domainadmin";
1615 }
1616 elseif (!isset($obj_props['superadmin']) && (!$_data['user'] || $_data['user'] == "user")) {
1617 $stmt = $pdo->prepare("SELECT `username` FROM `mailbox` WHERE `username` = :username");
1618 $stmt->execute(array(':username' => $process_fido2['username']));
1619 $row = $stmt->fetch(PDO::FETCH_ASSOC);
1620 if ($row['username'] == $process_fido2['username']) {
1621 $role = "user";
1622 }
1623 }
1624 else {
1625 $_SESSION['return'][] = array(
1626 'type' => 'danger',
1627 'log' => array("fido2_login", $_data['user'], $process_fido2['username']),
1628 'msg' => 'login_failed'
1629 );
1630 return false;
1631 }
1632 if (empty($role)) {
1633 session_unset();
1634 session_destroy();
1635 $_SESSION['return'][] = array(
1636 'type' => 'danger',
1637 'log' => array("fido2_login", $_data['user'], $process_fido2['username']),
1638 'msg' => 'login_failed'
1639 );
1640 return false;
1641 }
1642 unset($_SESSION["challenge"]);
1643 $_SESSION['return'][] = array(
1644 'type' => 'success',
1645 'log' => array("fido2_login", $_data['user'], $process_fido2['username']),
1646 'msg' => array('logged_in_as', $process_fido2['username'])
1647 );
1648 return array(
1649 "role" => $role,
1650 "username" => $process_fido2['username'],
1651 "cid" => $process_fido2['cid']
1652 );
1653 break;
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001654 }
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001655}
1656function unset_tfa_key($_data) {
1657 // Can only unset own keys
1658 // Needs at least one key left
1659 global $pdo;
1660 global $lang;
1661 $_data_log = $_data;
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01001662 $access_denied = null;
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001663 $id = intval($_data['unset_tfa_key']);
1664 $username = $_SESSION['mailcow_cc_username'];
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01001665
1666 // check for empty user and role
1667 if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) $access_denied = true;
1668
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001669 try {
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01001670 if (!is_numeric($id)) $access_denied = true;
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001671
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01001672 // set access_denied error
1673 if ($access_denied){
1674 $_SESSION['return'][] = array(
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001675 'type' => 'danger',
1676 'log' => array(__FUNCTION__, $_data_log),
1677 'msg' => 'access_denied'
1678 );
1679 return false;
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001680 }
1681
1682 // Block key removal if force_tfa policy is active
1683 $is_forced_tfa = false;
1684 if ($_SESSION['mailcow_cc_role'] === 'user') {
1685 $stmt_check = $pdo->prepare("SELECT JSON_EXTRACT(`attributes`, '$.force_tfa') FROM `mailbox` WHERE `username` = ?");
1686 $stmt_check->execute(array($username));
1687 $is_forced_tfa = ($stmt_check->fetchColumn() == '1');
1688 } else {
1689 $stmt_check = $pdo->prepare("SELECT JSON_EXTRACT(`attributes`, '$.force_tfa') FROM `admin` WHERE `username` = ?");
1690 $stmt_check->execute(array($username));
1691 $is_forced_tfa = ($stmt_check->fetchColumn() == '1');
1692 }
1693 if ($is_forced_tfa) {
1694 $_SESSION['return'][] = array(
1695 'type' => 'danger',
1696 'log' => array(__FUNCTION__, $_data_log),
1697 'msg' => 'tfa_removal_blocked'
1698 );
1699 return false;
1700 }
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01001701
1702 // check if it's last key
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001703 $stmt = $pdo->prepare("SELECT COUNT(*) AS `keys` FROM `tfa`
1704 WHERE `username` = :username AND `active` = '1'");
1705 $stmt->execute(array(':username' => $username));
1706 $row = $stmt->fetch(PDO::FETCH_ASSOC);
1707 if ($row['keys'] == "1") {
1708 $_SESSION['return'][] = array(
1709 'type' => 'danger',
1710 'log' => array(__FUNCTION__, $_data_log),
1711 'msg' => 'last_key'
1712 );
1713 return false;
1714 }
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01001715
1716 // delete key
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001717 $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username AND `id` = :id");
1718 $stmt->execute(array(':username' => $username, ':id' => $id));
1719 $_SESSION['return'][] = array(
1720 'type' => 'success',
1721 'log' => array(__FUNCTION__, $_data_log),
1722 'msg' => array('object_modified', $username)
1723 );
1724 }
1725 catch (PDOException $e) {
1726 $_SESSION['return'][] = array(
1727 'type' => 'danger',
1728 'log' => array(__FUNCTION__, $_data_log),
1729 'msg' => array('mysql_error', $e)
1730 );
1731 return false;
1732 }
1733}
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001734function tfa_exists($username) {
1735 global $pdo;
1736 if (empty($username)) {
1737 return false;
1738 }
1739 $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM `tfa` WHERE `username` = :username");
1740 $stmt->execute(array(':username' => $username));
1741 return $stmt->fetch(PDO::FETCH_ASSOC)['count'] > 0;
1742}
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01001743function get_tfa($username = null, $id = null) {
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001744 global $pdo;
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001745 if (empty($username) && isset($_SESSION['mailcow_cc_username'])) {
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001746 $username = $_SESSION['mailcow_cc_username'];
1747 }
1748 elseif (empty($username)) {
1749 return false;
1750 }
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001751
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01001752 if (!isset($id)){
1753 // fetch all tfa methods - just get information about possible authenticators
1754 $stmt = $pdo->prepare("SELECT `id`, `key_id`, `authmech` FROM `tfa`
1755 WHERE `username` = :username AND `active` = '1'");
1756 $stmt->execute(array(':username' => $username));
1757 $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001758
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01001759 // no tfa methods found
1760 if (count($results) == 0) {
1761 $data['name'] = 'none';
1762 $data['pretty'] = "-";
1763 $data['additional'] = array();
1764 return $data;
1765 }
1766
1767 $data['additional'] = $results;
1768 return $data;
1769 } else {
1770 // fetch specific authenticator details by id
1771 $stmt = $pdo->prepare("SELECT * FROM `tfa`
1772 WHERE `username` = :username AND `id` = :id AND `active` = '1'");
1773 $stmt->execute(array(':username' => $username, ':id' => $id));
1774 $row = $stmt->fetch(PDO::FETCH_ASSOC);
1775
1776 if (isset($row["authmech"])) {
1777 switch ($row["authmech"]) {
1778 case "yubi_otp":
1779 $data['name'] = "yubi_otp";
1780 $data['pretty'] = "Yubico OTP";
1781 $stmt = $pdo->prepare("SELECT `id`, `key_id`, RIGHT(`secret`, 12) AS 'modhex' FROM `tfa` WHERE `authmech` = 'yubi_otp' AND `username` = :username AND `id` = :id");
1782 $stmt->execute(array(
1783 ':username' => $username,
1784 ':id' => $id
1785 ));
1786 $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
1787 while($row = array_shift($rows)) {
1788 $data['additional'][] = $row;
1789 }
1790 return $data;
1791 break;
1792 // u2f - deprecated, should be removed
1793 case "u2f":
1794 $data['name'] = "u2f";
1795 $data['pretty'] = "Fido U2F";
1796 $stmt = $pdo->prepare("SELECT `id`, `key_id` FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username AND `id` = :id");
1797 $stmt->execute(array(
1798 ':username' => $username,
1799 ':id' => $id
1800 ));
1801 $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
1802 while($row = array_shift($rows)) {
1803 $data['additional'][] = $row;
1804 }
1805 return $data;
1806 break;
1807 case "hotp":
1808 $data['name'] = "hotp";
1809 $data['pretty'] = "HMAC-based OTP";
1810 return $data;
1811 break;
1812 case "totp":
1813 $data['name'] = "totp";
1814 $data['pretty'] = "Time-based OTP";
1815 $stmt = $pdo->prepare("SELECT `id`, `key_id`, `secret` FROM `tfa` WHERE `authmech` = 'totp' AND `username` = :username AND `id` = :id");
1816 $stmt->execute(array(
1817 ':username' => $username,
1818 ':id' => $id
1819 ));
1820 $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
1821 while($row = array_shift($rows)) {
1822 $data['additional'][] = $row;
1823 }
1824 return $data;
1825 break;
1826 case "webauthn":
1827 $data['name'] = "webauthn";
1828 $data['pretty'] = "WebAuthn";
1829 $stmt = $pdo->prepare("SELECT `id`, `key_id` FROM `tfa` WHERE `authmech` = 'webauthn' AND `username` = :username AND `id` = :id");
1830 $stmt->execute(array(
1831 ':username' => $username,
1832 ':id' => $id
1833 ));
1834 $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
1835 while($row = array_shift($rows)) {
1836 $data['additional'][] = $row;
1837 }
1838 return $data;
1839 break;
1840 default:
1841 $data['name'] = 'none';
1842 $data['pretty'] = "-";
1843 return $data;
1844 break;
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001845 }
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01001846 }
1847 else {
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001848 $data['name'] = 'none';
1849 $data['pretty'] = "-";
1850 return $data;
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01001851 }
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001852 }
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001853}
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01001854function verify_tfa_login($username, $_data) {
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02001855 global $pdo;
1856 global $yubi;
1857 global $u2f;
1858 global $tfa;
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01001859 global $WebAuthn;
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001860
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01001861 if ($_data['tfa_method'] != 'u2f'){
1862
1863 switch ($_data["tfa_method"]) {
1864 case "yubi_otp":
1865 if (!ctype_alnum($_data['token']) || strlen($_data['token']) != 44) {
1866 $_SESSION['return'][] = array(
1867 'type' => 'danger',
1868 'log' => array(__FUNCTION__, $username, '*'),
1869 'msg' => array('yotp_verification_failed', 'token length error')
1870 );
1871 return false;
1872 }
1873 $yubico_modhex_id = substr($_data['token'], 0, 12);
1874 $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
1875 WHERE `username` = :username
1876 AND `authmech` = 'yubi_otp'
1877 AND `active` = '1'
1878 AND `secret` LIKE :modhex");
1879 $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id));
1880 $row = $stmt->fetch(PDO::FETCH_ASSOC);
1881 $yubico_auth = explode(':', $row['secret']);
1882 $yubi = new Auth_Yubico($yubico_auth[0], $yubico_auth[1]);
1883 $yauth = $yubi->verify($_data['token']);
1884 if (PEAR::isError($yauth)) {
1885 $_SESSION['return'][] = array(
1886 'type' => 'danger',
1887 'log' => array(__FUNCTION__, $username, '*'),
1888 'msg' => array('yotp_verification_failed', $yauth->getMessage())
1889 );
1890 return false;
1891 }
1892 else {
1893 $_SESSION['tfa_id'] = $row['id'];
1894 $_SESSION['return'][] = array(
1895 'type' => 'success',
1896 'log' => array(__FUNCTION__, $username, '*'),
1897 'msg' => 'verified_yotp_login'
1898 );
1899 return true;
1900 }
1901 $_SESSION['return'][] = array(
1902 'type' => 'danger',
1903 'log' => array(__FUNCTION__, $username, '*'),
1904 'msg' => array('yotp_verification_failed', 'unknown')
1905 );
1906 return false;
1907 break;
1908 case "hotp":
1909 return false;
1910 break;
1911 case "totp":
1912 try {
1913 $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
1914 WHERE `username` = :username
1915 AND `authmech` = 'totp'
1916 AND `id` = :id
1917 AND `active`='1'");
1918 $stmt->execute(array(':username' => $username, ':id' => $_data['id']));
1919 $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
1920 foreach ($rows as $row) {
1921 if ($tfa->verifyCode($row['secret'], $_data['token']) === true) {
1922 $_SESSION['tfa_id'] = $row['id'];
1923 $_SESSION['return'][] = array(
1924 'type' => 'success',
1925 'log' => array(__FUNCTION__, $username, '*'),
1926 'msg' => 'verified_totp_login'
1927 );
1928 return true;
1929 }
1930 }
1931 $_SESSION['return'][] = array(
1932 'type' => 'danger',
1933 'log' => array(__FUNCTION__, $username, '*'),
1934 'msg' => 'totp_verification_failed'
1935 );
1936 return false;
1937 }
1938 catch (PDOException $e) {
1939 $_SESSION['return'][] = array(
1940 'type' => 'danger',
1941 'log' => array(__FUNCTION__, $username, '*'),
1942 'msg' => array('mysql_error', $e)
1943 );
1944 return false;
1945 }
1946 break;
1947 case "webauthn":
1948 $tokenData = json_decode($_data['token']);
1949 $clientDataJSON = base64_decode($tokenData->clientDataJSON);
1950 $authenticatorData = base64_decode($tokenData->authenticatorData);
1951 $signature = base64_decode($tokenData->signature);
1952 $id = base64_decode($tokenData->id);
1953 $challenge = $_SESSION['challenge'];
1954
1955 $stmt = $pdo->prepare("SELECT `id`, `key_id`, `keyHandle`, `username`, `publicKey` FROM `tfa` WHERE `id` = :id AND `active`='1'");
1956 $stmt->execute(array(':id' => $_data['id']));
1957 $process_webauthn = $stmt->fetch(PDO::FETCH_ASSOC);
1958
1959 if (empty($process_webauthn)){
1960 $_SESSION['return'][] = array(
1961 'type' => 'danger',
1962 'log' => array(__FUNCTION__, $username, '*'),
Matthias Andreas Benkardd63fe562023-11-18 13:18:30 +01001963 'msg' => array('webauthn_authenticator_failed')
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01001964 );
1965 return false;
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001966 }
1967
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01001968 if (empty($process_webauthn['publicKey']) || $process_webauthn['publicKey'] === false) {
1969 $_SESSION['return'][] = array(
1970 'type' => 'danger',
1971 'log' => array(__FUNCTION__, $username, '*'),
Matthias Andreas Benkardd63fe562023-11-18 13:18:30 +01001972 'msg' => array('webauthn_publickey_failed')
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01001973 );
1974 return false;
1975 }
1976
Matthias Andreas Benkardd63fe562023-11-18 13:18:30 +01001977 if ($process_webauthn['username'] != $_SESSION['pending_mailcow_cc_username']){
1978 $_SESSION['return'][] = array(
1979 'type' => 'danger',
1980 'log' => array(__FUNCTION__, $username, '*'),
1981 'msg' => array('webauthn_username_failed')
1982 );
1983 return false;
1984 }
1985
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01001986 try {
1987 $WebAuthn->processGet($clientDataJSON, $authenticatorData, $signature, $process_webauthn['publicKey'], $challenge, null, $GLOBALS['WEBAUTHN_UV_FLAG_LOGIN'], $GLOBALS['WEBAUTHN_USER_PRESENT_FLAG']);
1988 }
1989 catch (Throwable $ex) {
1990 $_SESSION['return'][] = array(
1991 'type' => 'danger',
1992 'log' => array(__FUNCTION__, $username, '*'),
1993 'msg' => array('webauthn_verification_failed', $ex->getMessage())
1994 );
1995 return false;
1996 }
1997
1998 $stmt = $pdo->prepare("SELECT `superadmin` FROM `admin` WHERE `username` = :username");
1999 $stmt->execute(array(':username' => $process_webauthn['username']));
2000 $obj_props = $stmt->fetch(PDO::FETCH_ASSOC);
2001 if ($obj_props['superadmin'] === 1) {
2002 $_SESSION["mailcow_cc_role"] = "admin";
2003 }
2004 elseif ($obj_props['superadmin'] === 0) {
2005 $_SESSION["mailcow_cc_role"] = "domainadmin";
2006 }
2007 else {
2008 $stmt = $pdo->prepare("SELECT `username` FROM `mailbox` WHERE `username` = :username");
2009 $stmt->execute(array(':username' => $process_webauthn['username']));
2010 $row = $stmt->fetch(PDO::FETCH_ASSOC);
2011 if (!empty($row['username'])) {
2012 $_SESSION["mailcow_cc_role"] = "user";
2013 } else {
2014 $_SESSION['return'][] = array(
2015 'type' => 'danger',
2016 'log' => array(__FUNCTION__, $username, '*'),
Matthias Andreas Benkardd63fe562023-11-18 13:18:30 +01002017 'msg' => array('webauthn_role_failed')
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01002018 );
2019 return false;
2020 }
2021 }
2022
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01002023 $_SESSION["mailcow_cc_username"] = $process_webauthn['username'];
2024 $_SESSION['tfa_id'] = $process_webauthn['id'];
2025 $_SESSION['authReq'] = null;
2026 unset($_SESSION["challenge"]);
2027 $_SESSION['return'][] = array(
2028 'type' => 'success',
2029 'log' => array("webauthn_login"),
2030 'msg' => array('logged_in_as', $process_webauthn['username'])
2031 );
2032 return true;
2033 break;
2034 default:
2035 $_SESSION['return'][] = array(
2036 'type' => 'danger',
Matthias Andreas Benkardb4b5cc12021-12-28 18:02:04 +01002037 'log' => array(__FUNCTION__, $username, '*'),
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01002038 'msg' => 'unknown_tfa_method'
2039 );
2040 return false;
2041 break;
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01002042 }
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01002043
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01002044 return false;
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01002045 } else {
2046 // delete old keys that used u2f
2047 $stmt = $pdo->prepare("SELECT * FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username");
2048 $stmt->execute(array(':username' => $username));
2049 $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
2050 if (count($rows) == 0) return false;
2051
2052 $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username");
2053 $stmt->execute(array(':username' => $username));
2054 return true;
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02002055 }
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01002056}
2057function admin_api($access, $action, $data = null) {
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02002058 global $pdo;
2059 if ($_SESSION['mailcow_cc_role'] != "admin") {
2060 $_SESSION['return'][] = array(
2061 'type' => 'danger',
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01002062 'log' => array(__FUNCTION__),
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02002063 'msg' => 'access_denied'
2064 );
2065 return false;
2066 }
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01002067 if ($access !== "ro" && $access !== "rw") {
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02002068 $_SESSION['return'][] = array(
2069 'type' => 'danger',
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01002070 'log' => array(__FUNCTION__),
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02002071 'msg' => 'invalid access type'
2072 );
2073 return false;
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01002074 }
2075 if ($action == "edit") {
2076 $active = (!empty($data['active'])) ? 1 : 0;
2077 $skip_ip_check = (isset($data['skip_ip_check'])) ? 1 : 0;
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02002078 $allow_from = array();
2079 if (isset($data['allow_from'])) {
2080 $allow_from = array_map('trim', preg_split( "/( |,|;|\n)/", $data['allow_from']));
2081 }
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01002082 foreach ($allow_from as $key => $val) {
2083 if (empty($val)) {
2084 unset($allow_from[$key]);
2085 continue;
2086 }
2087 if (valid_network($val) !== true) {
2088 $_SESSION['return'][] = array(
2089 'type' => 'warning',
2090 'log' => array(__FUNCTION__, $data),
2091 'msg' => array('ip_invalid', htmlspecialchars($allow_from[$key]))
2092 );
2093 unset($allow_from[$key]);
2094 continue;
2095 }
2096 }
2097 $allow_from = implode(',', array_unique(array_filter($allow_from)));
2098 if (empty($allow_from) && $skip_ip_check == 0) {
2099 $_SESSION['return'][] = array(
2100 'type' => 'danger',
2101 'log' => array(__FUNCTION__, $data),
2102 'msg' => 'ip_list_empty'
2103 );
2104 return false;
2105 }
2106 $api_key = implode('-', array(
2107 strtoupper(bin2hex(random_bytes(3))),
2108 strtoupper(bin2hex(random_bytes(3))),
2109 strtoupper(bin2hex(random_bytes(3))),
2110 strtoupper(bin2hex(random_bytes(3))),
2111 strtoupper(bin2hex(random_bytes(3)))
2112 ));
2113 $stmt = $pdo->query("SELECT `api_key` FROM `api` WHERE `access` = '" . $access . "'");
2114 $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
2115 if (empty($num_results)) {
2116 $stmt = $pdo->prepare("INSERT INTO `api` (`api_key`, `skip_ip_check`, `active`, `allow_from`, `access`)
2117 VALUES (:api_key, :skip_ip_check, :active, :allow_from, :access);");
2118 $stmt->execute(array(
2119 ':api_key' => $api_key,
2120 ':skip_ip_check' => $skip_ip_check,
2121 ':active' => $active,
2122 ':allow_from' => $allow_from,
2123 ':access' => $access
2124 ));
2125 }
2126 else {
2127 if ($skip_ip_check == 0) {
2128 $stmt = $pdo->prepare("UPDATE `api` SET `skip_ip_check` = :skip_ip_check,
2129 `active` = :active,
2130 `allow_from` = :allow_from
2131 WHERE `access` = :access;");
2132 $stmt->execute(array(
2133 ':active' => $active,
2134 ':skip_ip_check' => $skip_ip_check,
2135 ':allow_from' => $allow_from,
2136 ':access' => $access
2137 ));
2138 }
2139 else {
2140 $stmt = $pdo->prepare("UPDATE `api` SET `skip_ip_check` = :skip_ip_check,
2141 `active` = :active
2142 WHERE `access` = :access;");
2143 $stmt->execute(array(
2144 ':active' => $active,
2145 ':skip_ip_check' => $skip_ip_check,
2146 ':access' => $access
2147 ));
2148 }
2149 }
2150 }
2151 elseif ($action == "regen_key") {
2152 $api_key = implode('-', array(
2153 strtoupper(bin2hex(random_bytes(3))),
2154 strtoupper(bin2hex(random_bytes(3))),
2155 strtoupper(bin2hex(random_bytes(3))),
2156 strtoupper(bin2hex(random_bytes(3))),
2157 strtoupper(bin2hex(random_bytes(3)))
2158 ));
2159 $stmt = $pdo->prepare("UPDATE `api` SET `api_key` = :api_key WHERE `access` = :access");
2160 $stmt->execute(array(
2161 ':api_key' => $api_key,
2162 ':access' => $access
2163 ));
2164 }
2165 elseif ($action == "get") {
2166 $stmt = $pdo->query("SELECT * FROM `api` WHERE `access` = '" . $access . "'");
2167 $apidata = $stmt->fetch(PDO::FETCH_ASSOC);
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02002168 if ($apidata !== false) {
2169 $apidata['allow_from'] = str_replace(',', PHP_EOL, $apidata['allow_from']);
2170 }
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01002171 return $apidata;
2172 }
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02002173 $_SESSION['return'][] = array(
2174 'type' => 'success',
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01002175 'log' => array(__FUNCTION__, $data),
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02002176 'msg' => 'admin_api_modified'
2177 );
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01002178}
2179function license($action, $data = null) {
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02002180 global $pdo;
2181 global $redis;
2182 global $lang;
2183 if ($_SESSION['mailcow_cc_role'] != "admin") {
2184 $_SESSION['return'][] = array(
2185 'type' => 'danger',
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01002186 'log' => array(__FUNCTION__),
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02002187 'msg' => 'access_denied'
2188 );
2189 return false;
2190 }
2191 switch ($action) {
2192 case "verify":
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01002193 // Keep result until revalidate button is pressed or session expired
2194 $stmt = $pdo->query("SELECT `version` FROM `versions` WHERE `application` = 'GUID'");
2195 $versions = $stmt->fetch(PDO::FETCH_ASSOC);
2196 $post = array('guid' => $versions['version']);
2197 $curl = curl_init('https://verify.mailcow.email');
2198 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
2199 curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
2200 curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
2201 $response = curl_exec($curl);
2202 curl_close($curl);
2203 $json_return = json_decode($response, true);
2204 if ($response && $json_return) {
2205 if ($json_return['response'] === "ok") {
2206 $_SESSION['gal']['valid'] = "true";
2207 $_SESSION['gal']['c'] = $json_return['c'];
2208 $_SESSION['gal']['s'] = $json_return['s'];
2209 if ($json_return['m'] == 'NoMoore') {
2210 $_SESSION['gal']['m'] = '🐄';
2211 }
2212 else {
2213 $_SESSION['gal']['m'] = str_repeat('🐄', substr_count($json_return['m'], 'o'));
2214 }
2215 }
2216 elseif ($json_return['response'] === "invalid") {
2217 $_SESSION['gal']['valid'] = "false";
2218 $_SESSION['gal']['c'] = $lang['mailbox']['no'];
2219 $_SESSION['gal']['s'] = $lang['mailbox']['no'];
2220 $_SESSION['gal']['m'] = $lang['mailbox']['no'];
2221 }
2222 }
2223 else {
2224 $_SESSION['gal']['valid'] = "false";
2225 $_SESSION['gal']['c'] = $lang['danger']['temp_error'];
2226 $_SESSION['gal']['s'] = $lang['danger']['temp_error'];
2227 $_SESSION['gal']['m'] = $lang['danger']['temp_error'];
2228 }
2229 try {
2230 // json_encode needs "true"/"false" instead of true/false, to not encode it to 0 or 1
2231 $redis->Set('LICENSE_STATUS_CACHE', json_encode($_SESSION['gal']));
2232 }
2233 catch (RedisException $e) {
2234 $_SESSION['return'][] = array(
2235 'type' => 'danger',
2236 'log' => array(__FUNCTION__, $_action, $_data_log),
2237 'msg' => array('redis_error', $e)
2238 );
2239 return false;
2240 }
2241 return $_SESSION['gal']['valid'];
2242 break;
2243 case "guid":
2244 $stmt = $pdo->query("SELECT `version` FROM `versions` WHERE `application` = 'GUID'");
2245 $versions = $stmt->fetch(PDO::FETCH_ASSOC);
2246 return $versions['version'];
2247 break;
2248 }
2249}
2250function rspamd_ui($action, $data = null) {
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02002251 if ($_SESSION['mailcow_cc_role'] != "admin") {
2252 $_SESSION['return'][] = array(
2253 'type' => 'danger',
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01002254 'log' => array(__FUNCTION__),
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02002255 'msg' => 'access_denied'
2256 );
2257 return false;
2258 }
2259 switch ($action) {
2260 case "edit":
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01002261 $rspamd_ui_pass = $data['rspamd_ui_pass'];
2262 $rspamd_ui_pass2 = $data['rspamd_ui_pass2'];
2263 if (empty($rspamd_ui_pass) || empty($rspamd_ui_pass2)) {
2264 $_SESSION['return'][] = array(
2265 'type' => 'danger',
2266 'log' => array(__FUNCTION__, '*', '*'),
2267 'msg' => 'password_empty'
2268 );
2269 return false;
2270 }
2271 if ($rspamd_ui_pass != $rspamd_ui_pass2) {
2272 $_SESSION['return'][] = array(
2273 'type' => 'danger',
2274 'log' => array(__FUNCTION__, '*', '*'),
2275 'msg' => 'password_mismatch'
2276 );
2277 return false;
2278 }
2279 if (strlen($rspamd_ui_pass) < 6) {
2280 $_SESSION['return'][] = array(
2281 'type' => 'danger',
2282 'log' => array(__FUNCTION__, '*', '*'),
2283 'msg' => 'rspamd_ui_pw_length'
2284 );
2285 return false;
2286 }
2287 $docker_return = docker('post', 'rspamd-mailcow', 'exec', array('cmd' => 'rspamd', 'task' => 'worker_password', 'raw' => $rspamd_ui_pass), array('Content-Type: application/json'));
2288 if ($docker_return_array = json_decode($docker_return, true)) {
2289 if ($docker_return_array['type'] == 'success') {
2290 $_SESSION['return'][] = array(
2291 'type' => 'success',
2292 'log' => array(__FUNCTION__, '*', '*'),
2293 'msg' => 'rspamd_ui_pw_set'
2294 );
2295 return true;
2296 }
2297 else {
2298 $_SESSION['return'][] = array(
2299 'type' => $docker_return_array['type'],
2300 'log' => array(__FUNCTION__, '*', '*'),
2301 'msg' => $docker_return_array['msg']
2302 );
2303 return false;
2304 }
2305 }
2306 else {
2307 $_SESSION['return'][] = array(
2308 'type' => 'danger',
2309 'log' => array(__FUNCTION__, '*', '*'),
2310 'msg' => 'unknown'
2311 );
2312 return false;
2313 }
2314 break;
2315 }
2316}
Matthias Andreas Benkardd63fe562023-11-18 13:18:30 +01002317function cors($action, $data = null) {
2318 global $redis;
2319
2320 switch ($action) {
2321 case "edit":
2322 if ($_SESSION['mailcow_cc_role'] != "admin") {
2323 $_SESSION['return'][] = array(
2324 'type' => 'danger',
2325 'log' => array(__FUNCTION__, $action, $data),
2326 'msg' => 'access_denied'
2327 );
2328 return false;
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02002329 }
Matthias Andreas Benkardd63fe562023-11-18 13:18:30 +01002330
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02002331 $allowed_origins = isset($data['allowed_origins']) ? $data['allowed_origins'] : array(getBaseURL());
Matthias Andreas Benkardd63fe562023-11-18 13:18:30 +01002332 $allowed_origins = !is_array($allowed_origins) ? array_filter(array_map('trim', explode("\n", $allowed_origins))) : $allowed_origins;
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02002333 foreach ($allowed_origins as &$origin) {
2334 if ($origin === '*') {
2335 continue;
2336 }
2337 if (!valid_origin($origin)) {
Matthias Andreas Benkardd63fe562023-11-18 13:18:30 +01002338 $_SESSION['return'][] = array(
2339 'type' => 'danger',
2340 'log' => array(__FUNCTION__, $action, $data),
2341 'msg' => 'cors_invalid_origin'
2342 );
2343 return false;
2344 }
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02002345 // browsers always send a lowercase scheme/host in the Origin header, so normalize to match
2346 $origin = strtolower($origin);
Matthias Andreas Benkardd63fe562023-11-18 13:18:30 +01002347 }
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02002348 unset($origin);
Matthias Andreas Benkardd63fe562023-11-18 13:18:30 +01002349
2350 $allowed_methods = isset($data['allowed_methods']) ? $data['allowed_methods'] : array('GET', 'POST', 'PUT', 'DELETE');
2351 $allowed_methods = !is_array($allowed_methods) ? array_map('trim', preg_split( "/( |,|;|\n)/", $allowed_methods)) : $allowed_methods;
2352 $available_methods = array('GET', 'POST', 'PUT', 'DELETE');
2353 foreach ($allowed_methods as $method) {
2354 if (!in_array($method, $available_methods)) {
2355 $_SESSION['return'][] = array(
2356 'type' => 'danger',
2357 'log' => array(__FUNCTION__, $action, $data),
2358 'msg' => 'cors_invalid_method'
2359 );
2360 return false;
2361 }
2362 }
2363
2364 try {
2365 $redis->hMSet('CORS_SETTINGS', array(
2366 'allowed_origins' => implode(', ', $allowed_origins),
2367 'allowed_methods' => implode(', ', $allowed_methods)
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02002368 ));
Matthias Andreas Benkardd63fe562023-11-18 13:18:30 +01002369 } catch (RedisException $e) {
2370 $_SESSION['return'][] = array(
2371 'type' => 'danger',
2372 'log' => array(__FUNCTION__, $action, $data),
2373 'msg' => array('redis_error', $e)
2374 );
2375 return false;
2376 }
2377
2378 $_SESSION['return'][] = array(
2379 'type' => 'success',
2380 'log' => array(__FUNCTION__, $action, $data),
2381 'msg' => 'cors_headers_edited'
2382 );
2383 return true;
2384 break;
2385 case "get":
2386 try {
2387 $cors_settings = $redis->hMGet('CORS_SETTINGS', array('allowed_origins', 'allowed_methods'));
2388 } catch (RedisException $e) {
2389 $_SESSION['return'][] = array(
2390 'type' => 'danger',
2391 'log' => array(__FUNCTION__, $action, $data),
2392 'msg' => array('redis_error', $e)
2393 );
2394 }
2395
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02002396 $cors_settings = !$cors_settings ? array('allowed_origins' => getBaseURL(), 'allowed_methods' => 'GET, POST, PUT, DELETE') : $cors_settings;
2397 $cors_settings['allowed_origins'] = empty($cors_settings['allowed_origins']) ? getBaseURL() : $cors_settings['allowed_origins'];
Matthias Andreas Benkardd63fe562023-11-18 13:18:30 +01002398 $cors_settings['allowed_methods'] = empty($cors_settings['allowed_methods']) ? 'GET, POST, PUT, DELETE, OPTION' : $cors_settings['allowed_methods'];
2399
2400 return $cors_settings;
2401 break;
2402 case "set_headers":
2403 $cors_settings = cors('get');
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02002404 // normalize the stored list; it may still hold bare hostnames written before origins were validated as origins
2405 $allowed_origins = array_filter(array_map('normalize_cors_origin', explode(',', $cors_settings['allowed_origins'])));
2406 $origin = isset($_SERVER['HTTP_ORIGIN']) ? normalize_cors_origin($_SERVER['HTTP_ORIGIN']) : false;
Matthias Andreas Benkardd63fe562023-11-18 13:18:30 +01002407 // check if requested origin is in allowed origins
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02002408 $allow_origin = null;
2409 if (in_array('*', $allowed_origins, true)) {
2410 $allow_origin = '*';
2411 } else if ($origin !== false && in_array($origin, $allowed_origins, true)) {
2412 $allow_origin = $origin;
Matthias Andreas Benkardd63fe562023-11-18 13:18:30 +01002413 }
2414 // always allow OPTIONS for preflight request
2415 $cors_settings["allowed_methods"] = empty($cors_settings["allowed_methods"]) ? 'OPTIONS' : $cors_settings["allowed_methods"] . ', ' . 'OPTIONS';
2416
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02002417 // a disallowed origin gets no Access-Control-Allow-Origin at all; echoing a different origin than the requesting one tells a browser nothing
2418 if ($allow_origin !== null) {
2419 header('Access-Control-Allow-Origin: ' . $allow_origin);
2420 }
2421 if ($allow_origin !== '*') {
2422 // the response depends on the request origin, keep caches from mixing them up
2423 header('Vary: Origin', false);
2424 }
Matthias Andreas Benkardd63fe562023-11-18 13:18:30 +01002425 header('Access-Control-Allow-Methods: '. $cors_settings['allowed_methods']);
2426 header('Access-Control-Allow-Headers: Accept, Content-Type, X-Api-Key, Origin');
2427
2428 // Access-Control settings requested, this is just a preflight request
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02002429 if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS' &&
Matthias Andreas Benkardd63fe562023-11-18 13:18:30 +01002430 isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']) &&
2431 isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02002432
Matthias Andreas Benkardd63fe562023-11-18 13:18:30 +01002433 $allowed_methods = explode(', ', $cors_settings["allowed_methods"]);
2434 if (in_array($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'], $allowed_methods, true))
2435 // method allowed send 200 OK
2436 http_response_code(200);
2437 else
2438 // method not allowed send 405 METHOD NOT ALLOWED
2439 http_response_code(405);
2440
2441 exit;
2442 }
2443 break;
2444 }
2445}
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02002446function getBaseURL($protocol = null) {
2447 // Get current server name
2448 $host = strtolower($_SERVER['SERVER_NAME']);
2449
2450 // craft allowed server name list
2451 $mailcow_hostname = strtolower(getenv("MAILCOW_HOSTNAME"));
2452 $additional_server_names = strtolower(getenv("ADDITIONAL_SERVER_NAMES")) ?: "";
2453 $additional_server_names = preg_replace('/\s+/', '', $additional_server_names);
2454 $allowed_server_names = $additional_server_names !== "" ? explode(',', $additional_server_names) : array();
2455 array_push($allowed_server_names, $mailcow_hostname);
2456
2457 // Fallback to MAILCOW HOSTNAME if current server name is not in allowed list
2458 if (!in_array($host, $allowed_server_names)) {
2459 $host = $mailcow_hostname;
2460 }
2461
2462 if (!isset($protocol)) {
2463 $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
2464 }
Matthias Andreas Benkard9dabdab2024-03-06 13:12:09 +01002465 $base_url = $protocol . '://' . $host;
2466
2467 return $base_url;
2468}
2469function uuid4() {
2470 $data = openssl_random_pseudo_bytes(16);
2471
2472 $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
2473 $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
2474
2475 return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
2476}
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02002477function identity_provider($_action = null, $_data = null, $_extra = null) {
2478 global $pdo;
2479 global $iam_provider;
2480 global $iam_settings;
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +01002481
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02002482 $data_log = $_data;
2483 if (isset($data_log['client_secret'])) $data_log['client_secret'] = '*';
2484 if (isset($data_log['access_token'])) $data_log['access_token'] = '*';
2485
2486 switch ($_action) {
2487 case 'get':
2488 $settings = array();
2489 $stmt = $pdo->prepare("SELECT * FROM `identity_provider`;");
2490 $stmt->execute();
2491 $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
2492 foreach($rows as $row){
2493 switch ($row["key"]) {
2494 case "redirect_url_extra":
2495 case "mappers":
2496 case "templates":
2497 $settings[$row["key"]] = json_decode($row["value"]);
2498 break;
2499 case "use_ssl":
2500 case "use_tls":
2501 case "login_provisioning":
2502 case "ignore_ssl_errors":
2503 $settings[$row["key"]] = boolval($row["value"]);
2504 break;
2505 default:
2506 $settings[$row["key"]] = $row["value"];
2507 break;
2508 }
2509 }
2510 // set login_provisioning if not exists
2511 if (!array_key_exists('login_provisioning', $settings)) {
2512 $settings['login_provisioning'] = 1;
2513 }
2514 // return default client_scopes for generic-oidc if none is set
2515 if ($settings["authsource"] == "generic-oidc" && empty($settings["client_scopes"])){
2516 $settings["client_scopes"] = "openid profile email mailcow_template";
2517 }
2518 if ($_extra['hide_sensitive']){
2519 $settings['client_secret'] = '';
2520 $settings['access_token'] = '';
2521 }
2522 // return default ldap options
2523 if ($settings["authsource"] == "ldap"){
2524 $settings['use_ssl'] = !isset($settings['use_ssl']) ? false : $settings['use_ssl'];
2525 $settings['use_tls'] = !isset($settings['use_tls']) ? false : $settings['use_tls'];
2526 $settings['ignore_ssl_errors'] = !isset($settings['ignore_ssl_errors']) ? false : $settings['ignore_ssl_errors'];
2527 }
2528 return $settings;
2529 break;
2530 case 'edit':
2531 if ($_SESSION['mailcow_cc_role'] != "admin") {
2532 $_SESSION['return'][] = array(
2533 'type' => 'danger',
2534 'log' => array(__FUNCTION__, $_action, $_data),
2535 'msg' => 'access_denied'
2536 );
2537 return false;
2538 }
2539 if (!isset($_data['authsource'])){
2540 $_SESSION['return'][] = array(
2541 'type' => 'danger',
2542 'log' => array(__FUNCTION__, $_action, $data_log),
2543 'msg' => array('required_data_missing', '')
2544 );
2545 return false;
2546 }
2547
2548 $available_authsources = array(
2549 "keycloak",
2550 "generic-oidc",
2551 "ldap"
2552 );
2553 $_data['authsource'] = strtolower($_data['authsource']);
2554 if (!in_array($_data['authsource'], $available_authsources)){
2555 $_SESSION['return'][] = array(
2556 'type' => 'danger',
2557 'log' => array(__FUNCTION__, $_action, $data_log),
2558 'msg' => array('invalid_authsource', $setting)
2559 );
2560 return false;
2561 }
2562
2563 $stmt = $pdo->prepare("SELECT * FROM `mailbox`
2564 WHERE `authsource` != 'mailcow'
2565 AND `authsource` IS NOT NULL
2566 AND `authsource` != :authsource");
2567 $stmt->execute(array(':authsource' => $_data['authsource']));
2568 $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
2569 if ($rows) {
2570 $_SESSION['return'][] = array(
2571 'type' => 'danger',
2572 'log' => array(__FUNCTION__, $_action, $data_log),
2573 'msg' => array('authsource_in_use', $setting)
2574 );
2575 return false;
2576 }
2577
2578 $_data['ignore_ssl_error'] = isset($_data['ignore_ssl_error']) ? boolval($_data['ignore_ssl_error']) : false;
2579 $_data['login_provisioning'] = isset($_data['login_provisioning']) ? boolval($_data['login_provisioning']) : false;
2580 switch ($_data['authsource']) {
2581 case "keycloak":
2582 $_data['server_url'] = (!empty($_data['server_url'])) ? rtrim($_data['server_url'], '/') : null;
2583 $_data['mailpassword_flow'] = isset($_data['mailpassword_flow']) ? intval($_data['mailpassword_flow']) : 0;
2584 $_data['periodic_sync'] = isset($_data['periodic_sync']) ? intval($_data['periodic_sync']) : 0;
2585 $_data['import_users'] = isset($_data['import_users']) ? intval($_data['import_users']) : 0;
2586 $_data['sync_interval'] = (!empty($_data['sync_interval'])) ? intval($_data['sync_interval']) : 15;
2587 $_data['sync_interval'] = $_data['sync_interval'] < 1 ? 1 : $_data['sync_interval'];
2588 $required_settings = array('authsource', 'server_url', 'realm', 'client_id', 'client_secret', 'redirect_url', 'version', 'mailpassword_flow', 'periodic_sync', 'import_users', 'sync_interval', 'ignore_ssl_error', 'login_provisioning');
2589 break;
2590 case "generic-oidc":
2591 $_data['authorize_url'] = (!empty($_data['authorize_url'])) ? $_data['authorize_url'] : null;
2592 $_data['token_url'] = (!empty($_data['token_url'])) ? $_data['token_url'] : null;
2593 $_data['userinfo_url'] = (!empty($_data['userinfo_url'])) ? $_data['userinfo_url'] : null;
2594 $_data['client_scopes'] = (!empty($_data['client_scopes'])) ? $_data['client_scopes'] : "openid profile email mailcow_template";
2595 $required_settings = array('authsource', 'authorize_url', 'token_url', 'client_id', 'client_secret', 'redirect_url', 'userinfo_url', 'client_scopes', 'ignore_ssl_error', 'login_provisioning');
2596 break;
2597 case "ldap":
2598 $_data['host'] = (!empty($_data['host'])) ? str_replace(" ", "", $_data['host']) : "";
2599 $_data['port'] = (!empty($_data['port'])) ? intval($_data['port']) : 389;
2600 $_data['username_field'] = (!empty($_data['username_field'])) ? strtolower($_data['username_field']) : "mail";
2601 $_data['attribute_field'] = (!empty($_data['attribute_field'])) ? strtolower($_data['attribute_field']) : "";
2602 $_data['filter'] = (!empty($_data['filter'])) ? $_data['filter'] : "";
2603 $_data['periodic_sync'] = isset($_data['periodic_sync']) ? intval($_data['periodic_sync']) : 0;
2604 $_data['import_users'] = isset($_data['import_users']) ? intval($_data['import_users']) : 0;
2605 $_data['use_ssl'] = isset($_data['use_ssl']) ? boolval($_data['use_ssl']) : false;
2606 $_data['use_tls'] = isset($_data['use_tls']) && !$_data['use_ssl'] ? boolval($_data['use_tls']) : false;
2607 $_data['sync_interval'] = (!empty($_data['sync_interval'])) ? intval($_data['sync_interval']) : 15;
2608 $_data['sync_interval'] = $_data['sync_interval'] < 1 ? 1 : $_data['sync_interval'];
2609 $required_settings = array('authsource', 'host', 'port', 'basedn', 'username_field', 'filter', 'attribute_field', 'binddn', 'bindpass', 'periodic_sync', 'import_users', 'sync_interval', 'use_ssl', 'use_tls', 'ignore_ssl_error', 'login_provisioning');
2610 break;
2611 }
2612
2613 $pdo->beginTransaction();
2614 $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES (:key, :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
2615 // add connection settings
2616 foreach($required_settings as $setting){
2617 if (!isset($_data[$setting])){
2618 $_SESSION['return'][] = array(
2619 'type' => 'danger',
2620 'log' => array(__FUNCTION__, $_action, $data_log),
2621 'msg' => array('required_data_missing', $setting)
2622 );
2623 $pdo->rollback();
2624 return false;
2625 }
2626
2627 $stmt->bindParam(':key', $setting);
2628 $stmt->bindParam(':value', $_data[$setting]);
2629 $stmt->execute();
2630 }
2631 $pdo->commit();
2632
2633 // add redirect_url_extra
2634 if (isset($_data['redirect_url_extra'])){
2635 $_data['redirect_url_extra'] = (!is_array($_data['redirect_url_extra'])) ? array($_data['redirect_url_extra']) : $_data['redirect_url_extra'];
2636
2637 $redirect_url_extra = array_filter($_data['redirect_url_extra']);
2638 $redirect_url_extra = json_encode($redirect_url_extra);
2639
2640 $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES ('redirect_url_extra', :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
2641 $stmt->bindParam(':value', $redirect_url_extra);
2642 $stmt->execute();
2643 }
2644
2645 // add default template
2646 if (isset($_data['default_template'])) {
2647 $_data['default_template'] = (empty($_data['default_template'])) ? "" : $_data['default_template'];
2648 $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES ('default_template', :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
2649 $stmt->bindParam(':value', $_data['default_template']);
2650 $stmt->execute();
2651 }
2652
2653 // add mappers
2654 if (isset($_data['mappers']) && isset($_data['templates'])){
2655 $_data['mappers'] = (!is_array($_data['mappers'])) ? array($_data['mappers']) : $_data['mappers'];
2656 $_data['templates'] = (!is_array($_data['templates'])) ? array($_data['templates']) : $_data['templates'];
2657
2658 $mappers = array_filter($_data['mappers']);
2659 $templates = array_filter($_data['templates']);
2660 if (count($mappers) == count($templates)){
2661 $mappers = json_encode($mappers);
2662 $templates = json_encode($templates);
2663
2664 $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES ('mappers', :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
2665 $stmt->bindParam(':value', $mappers);
2666 $stmt->execute();
2667 $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES ('templates', :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
2668 $stmt->bindParam(':value', $templates);
2669 $stmt->execute();
2670 }
2671 }
2672
2673 // delete old access_token
2674 $stmt = $pdo->query("INSERT INTO identity_provider (`key`, `value`) VALUES ('access_token', '') ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
2675
2676 $_SESSION['return'][] = array(
2677 'type' => 'success',
2678 'log' => array(__FUNCTION__, $_action, $data_log),
2679 'msg' => array('object_modified', '')
2680 );
2681 return true;
2682 break;
2683 case 'test':
2684 if ($_SESSION['mailcow_cc_role'] != "admin") {
2685 $_SESSION['return'][] = array(
2686 'type' => 'danger',
2687 'log' => array(__FUNCTION__, $_action, $_data),
2688 'msg' => 'access_denied'
2689 );
2690 return false;
2691 }
2692
2693 switch ($_data['authsource']) {
2694 case 'keycloak':
2695 $url = "{$_data['server_url']}/realms/{$_data['realm']}/protocol/openid-connect/token";
2696 $req = http_build_query(array(
2697 'grant_type' => 'client_credentials',
2698 'client_id' => $_data['client_id'],
2699 'client_secret' => $_data['client_secret']
2700 ));
2701 $curl = curl_init();
2702 curl_setopt($curl, CURLOPT_URL, $url);
2703 curl_setopt($curl, CURLOPT_TIMEOUT, 7);
2704 curl_setopt($curl, CURLOPT_POST, 1);
2705 curl_setopt($curl, CURLOPT_POSTFIELDS, $req);
2706 curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
2707 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
2708 if ($_data['ignore_ssl_error'] == "1"){
2709 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
2710 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
2711 }
2712 $res = curl_exec($curl);
2713 $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
2714 curl_close ($curl);
2715
2716 if ($code != 200) {
2717 return false;
2718 }
2719 break;
2720 case 'generic-oidc':
2721 $url = $_data['token_url'];
2722 $curl = curl_init();
2723 curl_setopt($curl, CURLOPT_URL, $url);
2724 curl_setopt($curl, CURLOPT_TIMEOUT, 7);
2725 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
2726 curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "OPTIONS");
2727 if ($_data['ignore_ssl_error'] == "1"){
2728 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
2729 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
2730 }
2731 $res = curl_exec($curl);
2732 $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
2733 curl_close ($curl);
2734
2735 if ($code != 200) {
2736 return false;
2737 }
2738 break;
2739 case 'ldap':
2740 if (!$_data['host'] || !$_data['port'] || !$_data['basedn'] ||
2741 !$_data['binddn'] || !$_data['bindpass']){
2742 return false;
2743 }
2744 $_data['use_ssl'] = isset($_data['use_ssl']) ? boolval($_data['use_ssl']) : false;
2745 $_data['use_tls'] = isset($_data['use_tls']) && !$_data['use_ssl'] ? boolval($_data['use_tls']) : false;
2746 $_data['ignore_ssl_error'] = isset($_data['ignore_ssl_error']) ? boolval($_data['ignore_ssl_error']) : false;
2747 $options = array();
2748 if ($_data['ignore_ssl_error']) {
2749 $options[LDAP_OPT_X_TLS_REQUIRE_CERT] = LDAP_OPT_X_TLS_NEVER;
2750 }
2751 $provider = new \LdapRecord\Connection([
2752 'hosts' => explode(",", $_data['host']),
2753 'port' => $_data['port'],
2754 'base_dn' => $_data['basedn'],
2755 'username' => $_data['binddn'],
2756 'password' => $_data['bindpass'],
2757 'use_ssl' => $_data['use_ssl'],
2758 'use_tls' => $_data['use_tls'],
2759 'options' => $options
2760 ]);
2761 try {
2762 $provider->connect();
2763 } catch (Throwable $e) {
2764 return false;
2765 }
2766 break;
2767 }
2768
2769 return true;
2770 break;
2771 case "delete":
2772 if ($_SESSION['mailcow_cc_role'] != "admin") {
2773 $_SESSION['return'][] = array(
2774 'type' => 'danger',
2775 'log' => array(__FUNCTION__, $_action, $_data),
2776 'msg' => 'access_denied'
2777 );
2778 return false;
2779 }
2780
2781 $stmt = $pdo->query("SELECT * FROM `mailbox`
2782 WHERE `authsource` != 'mailcow'
2783 AND `authsource` IS NOT NULL");
2784 $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
2785 if ($rows) {
2786 $_SESSION['return'][] = array(
2787 'type' => 'danger',
2788 'log' => array(__FUNCTION__, $_action, $data_log),
2789 'msg' => array('authsource_in_use', $setting)
2790 );
2791 return false;
2792 }
2793
2794 $stmt = $pdo->query("DELETE FROM identity_provider;");
2795
2796 $_SESSION['return'][] = array(
2797 'type' => 'success',
2798 'log' => array(__FUNCTION__, $_action, $data_log),
2799 'msg' => array('item_deleted', '')
2800 );
2801 return true;
2802 break;
2803 case "init":
2804 $settings = identity_provider('get');
2805 $provider = null;
2806
2807 switch ($settings['authsource']) {
2808 case "keycloak":
2809 if ($settings['server_url'] && $settings['realm'] && $settings['client_id'] &&
2810 $settings['client_secret'] && $settings['redirect_url'] && $settings['version']){
2811 $guzzyClient = new GuzzleHttp\Client([
2812 'defaults' => [
2813 \GuzzleHttp\RequestOptions::CONNECT_TIMEOUT => 5,
2814 \GuzzleHttp\RequestOptions::ALLOW_REDIRECTS => true],
2815 \GuzzleHttp\RequestOptions::VERIFY => !$settings['ignore_ssl_error'],
2816 ]
2817 );
2818 $provider = new Stevenmaguire\OAuth2\Client\Provider\Keycloak([
2819 'authServerUrl' => $settings['server_url'],
2820 'realm' => $settings['realm'],
2821 'clientId' => $settings['client_id'],
2822 'clientSecret' => $settings['client_secret'],
2823 'redirectUri' => $settings['redirect_url'],
2824 'version' => $settings['version'],
2825 // 'encryptionAlgorithm' => 'RS256', // optional
2826 // 'encryptionKeyPath' => '../key.pem' // optional
2827 // 'encryptionKey' => 'contents_of_key_or_certificate' // optional
2828 ]);
2829 $provider->setHttpClient($guzzyClient);
2830 }
2831 break;
2832 case "generic-oidc":
2833 if ($settings['client_id'] && $settings['client_secret'] && $settings['redirect_url'] &&
2834 $settings['authorize_url'] && $settings['token_url'] && $settings['userinfo_url']){
2835 $guzzyClient = new GuzzleHttp\Client([
2836 'defaults' => [
2837 \GuzzleHttp\RequestOptions::CONNECT_TIMEOUT => 5,
2838 \GuzzleHttp\RequestOptions::ALLOW_REDIRECTS => true],
2839 \GuzzleHttp\RequestOptions::VERIFY => !$settings['ignore_ssl_error'],
2840 ]
2841 );
2842 $provider = new \League\OAuth2\Client\Provider\GenericProvider([
2843 'clientId' => $settings['client_id'],
2844 'clientSecret' => $settings['client_secret'],
2845 'redirectUri' => $settings['redirect_url'],
2846 'urlAuthorize' => $settings['authorize_url'],
2847 'urlAccessToken' => $settings['token_url'],
2848 'urlResourceOwnerDetails' => $settings['userinfo_url'],
2849 'scopes' => $settings['client_scopes']
2850 ]);
2851 $provider->setHttpClient($guzzyClient);
2852 }
2853 break;
2854 case "ldap":
2855 if ($settings['host'] && $settings['port'] && $settings['basedn'] &&
2856 $settings['binddn'] && $settings['bindpass']){
2857 $options = array();
2858 if ($settings['ignore_ssl_error']) {
2859 $options[LDAP_OPT_X_TLS_REQUIRE_CERT] = LDAP_OPT_X_TLS_NEVER;
2860 }
2861 $provider = new \LdapRecord\Connection([
2862 'hosts' => explode(",", $settings['host']),
2863 'port' => $settings['port'],
2864 'base_dn' => $settings['basedn'],
2865 'username' => $settings['binddn'],
2866 'password' => $settings['bindpass'],
2867 'use_ssl' => $settings['use_ssl'],
2868 'use_tls' => $settings['use_tls'],
2869 'options' => $options
2870 ]);
2871 try {
2872 $provider->connect();
2873 } catch (Throwable $e) {
2874 $provider = null;
2875 }
2876 }
2877 break;
2878 }
2879 return $provider;
2880 break;
2881 case "verify-sso":
2882 if ($iam_settings['authsource'] != 'keycloak' && $iam_settings['authsource'] != 'generic-oidc'){
2883 $_SESSION['return'][] = array(
2884 'type' => 'danger',
2885 'log' => array(__FUNCTION__, "no OIDC provider configured"),
2886 'msg' => 'login_failed'
2887 );
2888 return false;
2889 }
2890
2891 try {
2892 $token = $iam_provider->getAccessToken('authorization_code', ['code' => $_GET['code']]);
2893 $plain_token = $token->getToken();
2894 $plain_refreshtoken = $token->getRefreshToken();
2895 $info = $iam_provider->getResourceOwner($token)->toArray();
2896 } catch (Throwable $e) {
2897 $_SESSION['return'][] = array(
2898 'type' => 'danger',
2899 'log' => array(__FUNCTION__, $e->getMessage()),
2900 'msg' => 'login_failed'
2901 );
2902 return false;
2903 }
2904 // check if email address is given
2905 if (empty($info['email'])) {
2906 $_SESSION['return'][] = array(
2907 'type' => 'danger',
2908 'log' => array(__FUNCTION__, 'No email address found for user'),
2909 'msg' => 'login_failed'
2910 );
2911 return false;
2912 }
2913
2914 // get mapped template
2915 $user_template = $info['mailcow_template'];
2916 $mapper_key = array_search($user_template, $iam_settings['mappers']);
2917
2918 // token valid, get mailbox
2919 $stmt = $pdo->prepare("SELECT
2920 mailbox.*,
2921 domain.active AS d_active
2922 FROM `mailbox`
2923 INNER JOIN domain on mailbox.domain = domain.domain
2924 WHERE `kind` NOT REGEXP 'location|thing|group'
2925 AND `username` = :user");
2926 $stmt->execute(array(':user' => $info['email']));
2927 $row = $stmt->fetch(PDO::FETCH_ASSOC);
2928 if ($row){
2929 if (!in_array($row['authsource'], array("keycloak", "generic-oidc"))) {
2930 clear_session();
2931 $_SESSION['return'][] = array(
2932 'type' => 'danger',
2933 'log' => array(__FUNCTION__, $info['email'], "The user's authentication source is not of type OIDC"),
2934 'msg' => 'login_failed'
2935 );
2936 return false;
2937 }
2938 if ($mapper_key !== false) {
2939 // update user
2940 $_SESSION['access_all_exception'] = '1';
2941 mailbox('edit', 'mailbox_from_template', array(
2942 'username' => $info['email'],
2943 'name' => $info['name'],
2944 'template' => $iam_settings['templates'][$mapper_key]
2945 ));
2946 $_SESSION['access_all_exception'] = '0';
2947
2948 // get updated row
2949 $stmt = $pdo->prepare("SELECT
2950 mailbox.*,
2951 domain.active AS d_active
2952 FROM `mailbox`
2953 INNER JOIN domain on mailbox.domain = domain.domain
2954 WHERE `kind` NOT REGEXP 'location|thing|group'
2955 AND `username` = :user");
2956 $stmt->execute(array(':user' => $info['email']));
2957 $row = $stmt->fetch(PDO::FETCH_ASSOC);
2958 }
2959 if ($row['active'] != 1 || $row['d_active'] != 1) {
2960 clear_session();
2961 $_SESSION['return'][] = array(
2962 'type' => 'danger',
2963 'log' => array(__FUNCTION__, $info['email'], 'Domain or mailbox is inactive'),
2964 'msg' => 'login_failed'
2965 );
2966 return false;
2967 }
2968 set_user_loggedin_session($info['email']);
2969 $_SESSION['iam_token'] = $plain_token;
2970 $_SESSION['iam_refresh_token'] = $plain_refreshtoken;
2971 $_SESSION['return'][] = array(
2972 'type' => 'success',
2973 'log' => array(__FUNCTION__, $_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role']),
2974 'msg' => array('logged_in_as', $_SESSION['mailcow_cc_username'])
2975 );
2976 return true;
2977 }
2978
2979 // user doesn't exist, check if login provisioning is enabled
2980 if (!$iam_settings['login_provisioning']){
2981 $_SESSION['return'][] = array(
2982 'type' => 'danger',
2983 'log' => array(__FUNCTION__, "Auto-create users on login is deactivated"),
2984 'msg' => 'login_failed'
2985 );
2986 return false;
2987 }
2988
2989 if (empty($iam_settings['mappers']) || empty($user_template) || $mapper_key === false){
2990 if (!empty($iam_settings['default_template'])) {
2991 $mbox_template = $iam_settings['default_template'];
2992 } else {
2993 clear_session();
2994 $_SESSION['return'][] = array(
2995 'type' => 'danger',
2996 'log' => array(__FUNCTION__, $info['email'], 'No matching attribute mapping was found'),
2997 'msg' => 'login_failed'
2998 );
2999 return false;
3000 }
3001 } else {
3002 $mbox_template = $iam_settings['templates'][$mapper_key];
3003 }
3004
3005 // create mailbox
3006 $_SESSION['access_all_exception'] = '1';
3007 $create_res = mailbox('add', 'mailbox_from_template', array(
3008 'domain' => explode('@', $info['email'])[1],
3009 'local_part' => explode('@', $info['email'])[0],
3010 'name' => $info['name'],
3011 'authsource' => $iam_settings['authsource'],
3012 'template' => $mbox_template
3013 ));
3014 $_SESSION['access_all_exception'] = '0';
3015 if (!$create_res){
3016 clear_session();
3017 $_SESSION['return'][] = array(
3018 'type' => 'danger',
3019 'log' => array(__FUNCTION__, $info['email'], 'Could not create mailbox on login'),
3020 'msg' => 'login_failed'
3021 );
3022 return false;
3023 }
3024
3025 // double check if mailbox and domain is active
3026 $stmt = $pdo->prepare("SELECT * FROM `mailbox`
3027 INNER JOIN domain on mailbox.domain = domain.domain
3028 WHERE `kind` NOT REGEXP 'location|thing|group'
3029 AND `mailbox`.`active`='1'
3030 AND `domain`.`active`='1'
3031 AND `username` = :user");
3032 $stmt->execute(array(':user' => $info['email']));
3033 $row = $stmt->fetch(PDO::FETCH_ASSOC);
3034 if (empty($row)) {
3035 clear_session();
3036 $_SESSION['return'][] = array(
3037 'type' => 'danger',
3038 'log' => array(__FUNCTION__, $info['email'], 'Domain or mailbox is inactive'),
3039 'msg' => 'login_failed'
3040 );
3041 return false;
3042 }
3043
3044 set_user_loggedin_session($info['email']);
3045 $_SESSION['iam_token'] = $plain_token;
3046 $_SESSION['iam_refresh_token'] = $plain_refreshtoken;
3047 $_SESSION['return'][] = array(
3048 'type' => 'success',
3049 'log' => array(__FUNCTION__, $_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role']),
3050 'msg' => array('logged_in_as', $_SESSION['mailcow_cc_username'])
3051 );
3052 return true;
3053 break;
3054 case "refresh-token":
3055 try {
3056 $token = $iam_provider->getAccessToken('refresh_token', ['refresh_token' => $_SESSION['iam_refresh_token']]);
3057 $plain_token = $token->getToken();
3058 $plain_refreshtoken = $token->getRefreshToken();
3059 $info = $iam_provider->getResourceOwner($token)->toArray();
3060 } catch (Throwable $e) {
3061 clear_session();
3062 $_SESSION['return'][] = array(
3063 'type' => 'danger',
3064 'log' => array(__FUNCTION__),
3065 'msg' => array('refresh_login_failed', $e->getMessage())
3066 );
3067 return false;
3068 }
3069
3070 if (empty($info['email'])){
3071 clear_session();
3072 $_SESSION['return'][] = array(
3073 'type' => 'danger',
3074 'log' => array(__FUNCTION__, $_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role']),
3075 'msg' => 'refresh_login_failed'
3076 );
3077 return false;
3078 }
3079
3080 set_user_loggedin_session($info['email']);
3081 $_SESSION['iam_token'] = $plain_token;
3082 $_SESSION['iam_refresh_token'] = $plain_refreshtoken;
3083 return true;
3084 break;
3085 case "get-redirect":
3086 if ($iam_settings['authsource'] != 'keycloak' && $iam_settings['authsource'] != 'generic-oidc')
3087 return false;
3088 $options = [];
3089 if (isset($iam_settings['redirect_url_extra'])) {
3090 // check if the current domain is used in an extra redirect URL
3091 $targetDomain = strtolower($_SERVER['HTTP_HOST']);
3092 foreach ($iam_settings['redirect_url_extra'] as $testUrl) {
3093 $testUrlParsed = parse_url($testUrl);
3094 if (isset($testUrlParsed['host']) && strtolower($testUrlParsed['host']) == $targetDomain) {
3095 $options['redirect_uri'] = $testUrl;
3096 break;
3097 }
3098 }
3099 }
3100 $authUrl = $iam_provider->getAuthorizationUrl($options);
3101 $_SESSION['oauth2state'] = $iam_provider->getState();
3102 return $authUrl;
3103 break;
3104 case "get-keycloak-admin-token":
3105 // get access_token for service account of mailcow client
3106 if ($iam_settings['authsource'] !== 'keycloak') return false;
3107 if (isset($iam_settings['access_token'])) {
3108 // check if access_token is valid
3109 $url = "{$iam_settings['server_url']}/realms/{$iam_settings['realm']}/protocol/openid-connect/token/introspect";
3110 $req = http_build_query(array(
3111 'token' => $iam_settings['access_token'],
3112 'client_id' => $iam_settings['client_id'],
3113 'client_secret' => $iam_settings['client_secret']
3114 ));
3115 $curl = curl_init();
3116 curl_setopt($curl, CURLOPT_URL, $url);
3117 curl_setopt($curl, CURLOPT_TIMEOUT, 7);
3118 curl_setopt($curl, CURLOPT_POST, 1);
3119 curl_setopt($curl, CURLOPT_POSTFIELDS, $req);
3120 curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
3121 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
3122 curl_setopt($curl, CURLOPT_TIMEOUT, 5);
3123 $res = json_decode(curl_exec($curl), true);
3124 $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
3125 curl_close ($curl);
3126 if ($code == 200 && $res['active'] == true) {
3127 // token is valid
3128 return $iam_settings['access_token'];
3129 }
3130 }
3131
3132 $url = "{$iam_settings['server_url']}/realms/{$iam_settings['realm']}/protocol/openid-connect/token";
3133 $req = http_build_query(array(
3134 'grant_type' => 'client_credentials',
3135 'client_id' => $iam_settings['client_id'],
3136 'client_secret' => $iam_settings['client_secret']
3137 ));
3138 $curl = curl_init();
3139 curl_setopt($curl, CURLOPT_URL, $url);
3140 curl_setopt($curl, CURLOPT_TIMEOUT, 7);
3141 curl_setopt($curl, CURLOPT_POST, 1);
3142 curl_setopt($curl, CURLOPT_POSTFIELDS, $req);
3143 curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
3144 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
3145 curl_setopt($curl, CURLOPT_TIMEOUT, 5);
3146 $res = json_decode(curl_exec($curl), true);
3147 $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
3148 curl_close ($curl);
3149 if ($code != 200) {
3150 return false;
3151 }
3152
3153 $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES (:key, :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
3154 $stmt->execute(array(
3155 ':key' => 'access_token',
3156 ':value' => $res['access_token']
3157 ));
3158 return $res['access_token'];
3159 break;
3160 }
3161}
3162function reset_password($action, $data = null) {
3163 global $pdo;
3164 global $redis;
3165 global $mailcow_hostname;
3166 global $PW_RESET_TOKEN_LIMIT;
3167 global $PW_RESET_TOKEN_LIFETIME;
3168
3169 $_data_log = $data;
3170 if (isset($_data_log['new_password'])) $_data_log['new_password'] = '*';
3171 if (isset($_data_log['new_password2'])) $_data_log['new_password2'] = '*';
3172
3173 switch ($action) {
3174 case 'check':
3175 $token = $data;
3176
3177 $stmt = $pdo->prepare("SELECT `t1`.`username` FROM `reset_password` AS `t1` JOIN `mailbox` AS `t2` ON `t1`.`username` = `t2`.`username` WHERE `t1`.`token` = :token AND `t1`.`created` > DATE_SUB(NOW(), INTERVAL :lifetime MINUTE) AND `t2`.`active` = 1 AND `t2`.`authsource` = 'mailcow';");
3178 $stmt->execute(array(
3179 ':token' => preg_replace('/[^a-zA-Z0-9-]/', '', $token),
3180 ':lifetime' => $PW_RESET_TOKEN_LIFETIME
3181 ));
3182 $return = $stmt->fetch(PDO::FETCH_ASSOC);
3183 return empty($return['username']) ? false : $return['username'];
3184 break;
3185 case 'issue':
3186 $username = $data;
3187
3188 // perform cleanup
3189 $stmt = $pdo->prepare("DELETE FROM `reset_password` WHERE created < DATE_SUB(NOW(), INTERVAL :lifetime MINUTE);");
3190 $stmt->execute(array(':lifetime' => $PW_RESET_TOKEN_LIFETIME));
3191
3192 if (filter_var($username, FILTER_VALIDATE_EMAIL) === false) {
3193 $_SESSION['return'][] = array(
3194 'type' => 'danger',
3195 'log' => array(__FUNCTION__, $action, $_data_log),
3196 'msg' => 'access_denied'
3197 );
3198 return false;
3199 }
3200
3201 $pw_reset_notification = reset_password('get_notification', 'raw');
3202 if (!$pw_reset_notification) return false;
3203 if (empty($pw_reset_notification['from']) || empty($pw_reset_notification['subject'])) {
3204 $_SESSION['return'][] = array(
3205 'type' => 'danger',
3206 'log' => array(__FUNCTION__, $action, $_data_log),
3207 'msg' => 'password_reset_na'
3208 );
3209 return false;
3210 }
3211
3212 $stmt = $pdo->prepare("SELECT * FROM `mailbox`
3213 WHERE `username` = :username AND authsource = 'mailcow'");
3214 $stmt->execute(array(':username' => $username));
3215 $mailbox_data = $stmt->fetch(PDO::FETCH_ASSOC);
3216
3217 if (empty($mailbox_data)) {
3218 $_SESSION['return'][] = array(
3219 'type' => 'danger',
3220 'log' => array(__FUNCTION__, $action, $_data_log),
3221 'msg' => 'password_reset_invalid_user'
3222 );
3223 return false;
3224 }
3225
3226 $mailbox_attr = json_decode($mailbox_data['attributes'], true);
3227 if (empty($mailbox_attr['recovery_email']) || filter_var($mailbox_attr['recovery_email'], FILTER_VALIDATE_EMAIL) === false) {
3228 $_SESSION['return'][] = array(
3229 'type' => 'danger',
3230 'log' => array(__FUNCTION__, $action, $_data_log),
3231 'msg' => "password_reset_invalid_user"
3232 );
3233 return false;
3234 }
3235
3236 $stmt = $pdo->prepare("SELECT * FROM `reset_password`
3237 WHERE `username` = :username");
3238 $stmt->execute(array(':username' => $username));
3239 $generated_token_count = count($stmt->fetchAll(PDO::FETCH_ASSOC));
3240 if ($generated_token_count >= $PW_RESET_TOKEN_LIMIT) {
3241 $_SESSION['return'][] = array(
3242 'type' => 'danger',
3243 'log' => array(__FUNCTION__, $action, $_data_log),
3244 'msg' => "reset_token_limit_exceeded"
3245 );
3246 return false;
3247 }
3248
3249 $token = implode('-', array(
3250 strtoupper(bin2hex(random_bytes(3))),
3251 strtoupper(bin2hex(random_bytes(3))),
3252 strtoupper(bin2hex(random_bytes(3))),
3253 strtoupper(bin2hex(random_bytes(3))),
3254 strtoupper(bin2hex(random_bytes(3)))
3255 ));
3256
3257 $stmt = $pdo->prepare("INSERT INTO `reset_password` (`username`, `token`)
3258 VALUES (:username, :token)");
3259 $stmt->execute(array(
3260 ':username' => $username,
3261 ':token' => $token
3262 ));
3263
3264 $reset_link = getBaseURL() . "/reset-password?token=" . $token;
3265
3266 $request_date = new DateTime();
3267 $locale_date = locale_get_default();
3268 $date_formatter = new IntlDateFormatter(
3269 $locale_date,
3270 IntlDateFormatter::FULL,
3271 IntlDateFormatter::FULL
3272 );
3273 $formatted_request_date = $date_formatter->format($request_date);
3274
3275 // set template vars
3276 // subject
3277 $pw_reset_notification['subject'] = str_replace('{{hostname}}', $mailcow_hostname, $pw_reset_notification['subject']);
3278 $pw_reset_notification['subject'] = str_replace('{{link}}', $reset_link, $pw_reset_notification['subject']);
3279 $pw_reset_notification['subject'] = str_replace('{{username}}', $username, $pw_reset_notification['subject']);
3280 $pw_reset_notification['subject'] = str_replace('{{username2}}', $mailbox_attr['recovery_email'], $pw_reset_notification['subject']);
3281 $pw_reset_notification['subject'] = str_replace('{{date}}', $formatted_request_date, $pw_reset_notification['subject']);
3282 $pw_reset_notification['subject'] = str_replace('{{token_lifetime}}', $PW_RESET_TOKEN_LIFETIME, $pw_reset_notification['subject']);
3283 // text
3284 $pw_reset_notification['text_tmpl'] = str_replace('{{hostname}}', $mailcow_hostname, $pw_reset_notification['text_tmpl']);
3285 $pw_reset_notification['text_tmpl'] = str_replace('{{link}}', $reset_link, $pw_reset_notification['text_tmpl']);
3286 $pw_reset_notification['text_tmpl'] = str_replace('{{username}}', $username, $pw_reset_notification['text_tmpl']);
3287 $pw_reset_notification['text_tmpl'] = str_replace('{{username2}}', $mailbox_attr['recovery_email'], $pw_reset_notification['text_tmpl']);
3288 $pw_reset_notification['text_tmpl'] = str_replace('{{date}}', $formatted_request_date, $pw_reset_notification['text_tmpl']);
3289 $pw_reset_notification['text_tmpl'] = str_replace('{{token_lifetime}}', $PW_RESET_TOKEN_LIFETIME, $pw_reset_notification['text_tmpl']);
3290 // html
3291 $pw_reset_notification['html_tmpl'] = str_replace('{{hostname}}', $mailcow_hostname, $pw_reset_notification['html_tmpl']);
3292 $pw_reset_notification['html_tmpl'] = str_replace('{{link}}', $reset_link, $pw_reset_notification['html_tmpl']);
3293 $pw_reset_notification['html_tmpl'] = str_replace('{{username}}', $username, $pw_reset_notification['html_tmpl']);
3294 $pw_reset_notification['html_tmpl'] = str_replace('{{username2}}', $mailbox_attr['recovery_email'], $pw_reset_notification['html_tmpl']);
3295 $pw_reset_notification['html_tmpl'] = str_replace('{{date}}', $formatted_request_date, $pw_reset_notification['html_tmpl']);
3296 $pw_reset_notification['html_tmpl'] = str_replace('{{token_lifetime}}', $PW_RESET_TOKEN_LIFETIME, $pw_reset_notification['html_tmpl']);
3297
3298
3299 $email_sent = reset_password('send_mail', array(
3300 "from" => $pw_reset_notification['from'],
3301 "to" => $mailbox_attr['recovery_email'],
3302 "subject" => $pw_reset_notification['subject'],
3303 "text" => $pw_reset_notification['text_tmpl'],
3304 "html" => $pw_reset_notification['html_tmpl']
3305 ));
3306
3307 if (!$email_sent){
3308 $_SESSION['return'][] = array(
3309 'type' => 'danger',
3310 'log' => array(__FUNCTION__, $action, $_data_log),
3311 'msg' => "recovery_email_failed"
3312 );
3313 return false;
3314 }
3315
3316 list($localPart, $domainPart) = explode('@', $mailbox_attr['recovery_email']);
3317 if (strlen($localPart) > 1) {
3318 $maskedLocalPart = $localPart[0] . str_repeat('*', strlen($localPart) - 1);
3319 } else {
3320 $maskedLocalPart = "*";
3321 }
3322 $_SESSION['return'][] = array(
3323 'type' => 'success',
3324 'log' => array(__FUNCTION__, $action, $_data_log),
3325 'msg' => array("recovery_email_sent", $maskedLocalPart . '@' . $domainPart)
3326 );
3327 return array(
3328 "username" => $username,
3329 "issue" => "success"
3330 );
3331 break;
3332 case 'reset':
3333 $token = $data['token'];
3334 $new_password = $data['new_password'];
3335 $new_password2 = $data['new_password2'];
3336 $username = $data['username'];
3337 $check_tfa = $data['check_tfa'];
3338
3339 if (!$username || !$token) {
3340 $_SESSION['return'][] = array(
3341 'type' => 'danger',
3342 'log' => array(__FUNCTION__, $action, $_data_log),
3343 'msg' => 'invalid_reset_token'
3344 );
3345 return false;
3346 }
3347
3348 # check new password
3349 if (!password_check($new_password, $new_password2)) {
3350 return false;
3351 }
3352
3353 if ($check_tfa){
3354 // check for tfa authenticators
3355 $authenticators = get_tfa($username);
3356 if (isset($authenticators['additional']) && is_array($authenticators['additional']) && count($authenticators['additional']) > 0) {
3357 $_SESSION['pending_mailcow_cc_username'] = $username;
3358 $_SESSION['pending_pw_reset_token'] = $token;
3359 $_SESSION['pending_pw_new_password'] = $new_password;
3360 $_SESSION['pending_tfa_methods'] = $authenticators['additional'];
3361 $_SESSION['return'][] = array(
3362 'type' => 'info',
3363 'log' => array(__FUNCTION__, $user, '*'),
3364 'msg' => 'awaiting_tfa_confirmation'
3365 );
3366 return false;
3367 }
3368 }
3369
3370 # set new password
3371 $password_hashed = hash_password($new_password);
3372 $stmt = $pdo->prepare("UPDATE `mailbox` SET
3373 `password` = :password_hashed,
3374 `attributes` = JSON_SET(`attributes`, '$.passwd_update', NOW())
3375 WHERE `username` = :username AND authsource = 'mailcow'");
3376 $stmt->execute(array(
3377 ':password_hashed' => $password_hashed,
3378 ':username' => $username
3379 ));
3380
3381 // perform cleanup
3382 $stmt = $pdo->prepare("DELETE FROM `reset_password` WHERE `username` = :username;");
3383 $stmt->execute(array(
3384 ':username' => $username
3385 ));
3386
3387 update_sogo_static_view($username);
3388
3389 $_SESSION['return'][] = array(
3390 'type' => 'success',
3391 'log' => array(__FUNCTION__, $action, $_data_log),
3392 'msg' => 'password_changed_success'
3393 );
3394 return true;
3395 break;
3396 case 'get_notification':
3397 $type = $data;
3398
3399 try {
3400 $settings['from'] = $redis->Get('PW_RESET_FROM');
3401 $settings['subject'] = $redis->Get('PW_RESET_SUBJ');
3402 $settings['html_tmpl'] = $redis->Get('PW_RESET_HTML');
3403 $settings['text_tmpl'] = $redis->Get('PW_RESET_TEXT');
3404 if (empty($settings['html_tmpl']) && empty($settings['text_tmpl'])) {
3405 $settings['html_tmpl'] = file_get_contents("/tpls/pw_reset_html.tpl");
3406 $settings['text_tmpl'] = file_get_contents("/tpls/pw_reset_text.tpl");
3407 }
3408
3409 if ($type != "raw") {
3410 $settings['html_tmpl'] = htmlspecialchars($settings['html_tmpl']);
3411 $settings['text_tmpl'] = htmlspecialchars($settings['text_tmpl']);
3412 }
3413 }
3414 catch (RedisException $e) {
3415 $_SESSION['return'][] = array(
3416 'type' => 'danger',
3417 'log' => array(__FUNCTION__, $action, $_data_log),
3418 'msg' => array('redis_error', $e)
3419 );
3420 return false;
3421 }
3422
3423 return $settings;
3424 break;
3425 case 'send_mail':
3426 $from = $data['from'];
3427 $to = $data['to'];
3428 $text = $data['text'];
3429 $html = $data['html'];
3430 $subject = $data['subject'];
3431
3432 if (!filter_var($from, FILTER_VALIDATE_EMAIL)) {
3433 $_SESSION['return'][] = array(
3434 'type' => 'danger',
3435 'log' => array(__FUNCTION__, $action, $_data_log),
3436 'msg' => 'from_invalid'
3437 );
3438 return false;
3439 }
3440 if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
3441 $_SESSION['return'][] = array(
3442 'type' => 'danger',
3443 'log' => array(__FUNCTION__, $action, $_data_log),
3444 'msg' => 'to_invalid'
3445 );
3446 return false;
3447 }
3448 if (empty($subject)) {
3449 $_SESSION['return'][] = array(
3450 'type' => 'danger',
3451 'log' => array(__FUNCTION__, $action, $_data_log),
3452 'msg' => 'subject_empty'
3453 );
3454 return false;
3455 }
3456 if (empty($text)) {
3457 $_SESSION['return'][] = array(
3458 'type' => 'danger',
3459 'log' => array(__FUNCTION__, $action, $_data_log),
3460 'msg' => 'text_empty'
3461 );
3462 return false;
3463 }
3464
3465 ini_set('max_execution_time', 0);
3466 ini_set('max_input_time', 0);
3467 $mail = new PHPMailer;
3468 $mail->Timeout = 10;
3469 $mail->SMTPOptions = array(
3470 'ssl' => array(
3471 'verify_peer' => false,
3472 'verify_peer_name' => false,
3473 'allow_self_signed' => true
3474 )
3475 );
3476 $mail->isSMTP();
3477 $mail->Host = 'postfix-mailcow';
3478 $mail->SMTPAuth = false;
3479 $mail->Port = 25;
3480 $mail->setFrom($from);
3481 $mail->Subject = $subject;
3482 $mail->CharSet ="UTF-8";
3483 if (!empty($html)) {
3484 $mail->Body = $html;
3485 $mail->AltBody = $text;
3486 }
3487 else {
3488 $mail->Body = $text;
3489 }
3490 $mail->XMailer = 'MooMail';
3491 $mail->AddAddress($to);
3492 if (!$mail->send()) {
3493 return false;
3494 }
3495 $mail->ClearAllRecipients();
3496
3497 return true;
3498 break;
3499 }
3500
3501 if ($_SESSION['mailcow_cc_role'] != "admin") {
3502 $_SESSION['return'][] = array(
3503 'type' => 'danger',
3504 'log' => array(__FUNCTION__, $action, $_data_log),
3505 'msg' => 'access_denied'
3506 );
3507 return false;
3508 }
3509
3510 switch ($action) {
3511 case 'edit_notification':
3512 $subject = $data['subject'];
3513 $from = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $data['from']);
3514
3515 $from = (!filter_var($from, FILTER_VALIDATE_EMAIL)) ? "" : $from;
3516 $subject = (empty($subject)) ? "" : $subject;
3517 $text = (empty($data['text_tmpl'])) ? "" : $data['text_tmpl'];
3518 $html = (empty($data['html_tmpl'])) ? "" : $data['html_tmpl'];
3519
3520 try {
3521 $redis->Set('PW_RESET_FROM', $from);
3522 $redis->Set('PW_RESET_SUBJ', $subject);
3523 $redis->Set('PW_RESET_HTML', $html);
3524 $redis->Set('PW_RESET_TEXT', $text);
3525 }
3526 catch (RedisException $e) {
3527 $_SESSION['return'][] = array(
3528 'type' => 'danger',
3529 'log' => array(__FUNCTION__, $action, $_data_log),
3530 'msg' => array('redis_error', $e)
3531 );
3532 return false;
3533 }
3534
3535 $_SESSION['return'][] = array(
3536 'type' => 'success',
3537 'log' => array(__FUNCTION__, $action, $_data_log),
3538 'msg' => 'saved_settings'
3539 );
3540 break;
3541 }
3542}
3543function clear_session(){
3544 session_regenerate_id(true);
3545 session_unset();
3546 session_destroy();
3547 session_write_close();
3548}
3549function set_user_loggedin_session($user) {
3550 session_regenerate_id(true);
3551 $_SESSION['mailcow_cc_username'] = $user;
3552 $_SESSION['mailcow_cc_role'] = 'user';
3553 $sogo_sso_pass = file_get_contents("/etc/sogo-sso/sogo-sso.pass");
3554 $_SESSION['sogo-sso-user-allowed'][] = $user;
3555 $_SESSION['sogo-sso-pass'] = $sogo_sso_pass;
3556 unset($_SESSION['pending_mailcow_cc_username']);
3557 unset($_SESSION['pending_mailcow_cc_role']);
3558 unset($_SESSION['pending_tfa_methods']);
3559}
3560function protect_route($allowed_roles = ['admin', 'domainadmin', 'user'], $redirects = []) {
3561 // Check if user is authenticated
3562 if (!isset($_SESSION['mailcow_cc_role'])) {
3563 if (isset($redirects['unauthenticated'])) {
3564 header('Location: ' . $redirects['unauthenticated']);
3565 } else {
3566 // Send a deep link to the login page for its area instead of the user login at /,
3567 // e.g. /admin/dashboard -> /admin rather than /
3568 $request_uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
3569 if (strpos($request_uri, '/admin/') === 0) {
3570 header('Location: /admin');
3571 } elseif (strpos($request_uri, '/domainadmin/') === 0) {
3572 header('Location: /domainadmin');
3573 } else {
3574 header('Location: /');
3575 }
3576 }
3577 exit();
3578 }
3579
3580 // Check for pending actions (2FA setup, password update)
3581 if (!empty($_SESSION['pending_tfa_setup']) || !empty($_SESSION['pending_pw_update'])) {
3582 $pending_redirect = '/';
3583 if ($_SESSION['mailcow_cc_role'] === 'admin') {
3584 $pending_redirect = '/admin';
3585 } elseif ($_SESSION['mailcow_cc_role'] === 'domainadmin') {
3586 $pending_redirect = '/domainadmin';
3587 }
3588 header('Location: ' . $pending_redirect);
3589 exit();
3590 }
3591
3592 // Check if user's role is in the allowed roles for the route
3593 if (!in_array($_SESSION['mailcow_cc_role'], $allowed_roles)) {
3594 if (isset($_SESSION['mailcow_cc_role']) && $_SESSION['mailcow_cc_role'] == 'admin') {
3595 header('Location: /admin/dashboard');
3596 exit();
3597 }
3598 elseif (isset($_SESSION['mailcow_cc_role']) && $_SESSION['mailcow_cc_role'] == 'domainadmin') {
3599 header('Location: /domainadmin/mailbox');
3600 exit();
3601 }
3602 elseif (isset($_SESSION['mailcow_cc_role']) && $_SESSION['mailcow_cc_role'] == 'user') {
3603 header('Location: /user');
3604 exit();
3605 }
3606 else {
3607 header('Location: /');
3608 exit();
3609 }
3610 }
3611}
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01003612function get_logs($application, $lines = false) {
3613 if ($lines === false) {
3614 $lines = $GLOBALS['LOG_LINES'] - 1;
3615 }
3616 elseif(is_numeric($lines) && $lines >= 1) {
3617 $lines = abs(intval($lines) - 1);
3618 }
3619 else {
3620 list ($from, $to) = explode('-', $lines);
3621 $from = intval($from);
3622 $to = intval($to);
3623 if ($from < 1 || $to < $from) { return false; }
3624 }
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02003625 global $redis;
3626 global $pdo;
3627 if ($_SESSION['mailcow_cc_role'] != "admin") {
3628 return false;
3629 }
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01003630 // SQL
3631 if ($application == "mailcow-ui") {
3632 if (isset($from) && isset($to)) {
3633 $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :from, :to");
3634 $stmt->execute(array(
3635 ':from' => $from - 1,
3636 ':to' => $to
3637 ));
3638 $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
3639 }
3640 else {
3641 $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :lines");
3642 $stmt->execute(array(
3643 ':lines' => $lines + 1,
3644 ));
3645 $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
3646 }
3647 if (is_array($data)) {
3648 return $data;
3649 }
3650 }
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02003651 if ($application == "sasl") {
3652 if (isset($from) && isset($to)) {
3653 $stmt = $pdo->prepare("SELECT * FROM `sasl_log` ORDER BY `datetime` DESC LIMIT :from, :to");
3654 $stmt->execute(array(
3655 ':from' => $from - 1,
3656 ':to' => $to
3657 ));
3658 $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
3659 }
3660 else {
3661 $stmt = $pdo->prepare("SELECT * FROM `sasl_log` ORDER BY `datetime` DESC LIMIT :lines");
3662 $stmt->execute(array(
3663 ':lines' => $lines + 1,
3664 ));
3665 $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
3666 }
3667 if (is_array($data)) {
3668 return $data;
3669 }
3670 }
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01003671 // Redis
3672 if ($application == "dovecot-mailcow") {
3673 if (isset($from) && isset($to)) {
3674 $data = $redis->lRange('DOVECOT_MAILLOG', $from - 1, $to - 1);
3675 }
3676 else {
3677 $data = $redis->lRange('DOVECOT_MAILLOG', 0, $lines);
3678 }
3679 if ($data) {
3680 foreach ($data as $json_line) {
3681 $data_array[] = json_decode($json_line, true);
3682 }
3683 return $data_array;
3684 }
3685 }
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02003686 if ($application == "cron-mailcow") {
3687 if (isset($from) && isset($to)) {
3688 $data = $redis->lRange('CRON_LOG', $from - 1, $to - 1);
3689 }
3690 else {
3691 $data = $redis->lRange('CRON_LOG', 0, $lines);
3692 }
3693 if ($data) {
3694 foreach ($data as $json_line) {
3695 $data_array[] = json_decode($json_line, true);
3696 }
3697 return $data_array;
3698 }
3699 }
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01003700 if ($application == "postfix-mailcow") {
3701 if (isset($from) && isset($to)) {
3702 $data = $redis->lRange('POSTFIX_MAILLOG', $from - 1, $to - 1);
3703 }
3704 else {
3705 $data = $redis->lRange('POSTFIX_MAILLOG', 0, $lines);
3706 }
3707 if ($data) {
3708 foreach ($data as $json_line) {
3709 $data_array[] = json_decode($json_line, true);
3710 }
3711 return $data_array;
3712 }
3713 }
3714 if ($application == "sogo-mailcow") {
3715 if (isset($from) && isset($to)) {
3716 $data = $redis->lRange('SOGO_LOG', $from - 1, $to - 1);
3717 }
3718 else {
3719 $data = $redis->lRange('SOGO_LOG', 0, $lines);
3720 }
3721 if ($data) {
3722 foreach ($data as $json_line) {
3723 $data_array[] = json_decode($json_line, true);
3724 }
3725 return $data_array;
3726 }
3727 }
3728 if ($application == "watchdog-mailcow") {
3729 if (isset($from) && isset($to)) {
3730 $data = $redis->lRange('WATCHDOG_LOG', $from - 1, $to - 1);
3731 }
3732 else {
3733 $data = $redis->lRange('WATCHDOG_LOG', 0, $lines);
3734 }
3735 if ($data) {
3736 foreach ($data as $json_line) {
3737 $data_array[] = json_decode($json_line, true);
3738 }
3739 return $data_array;
3740 }
3741 }
3742 if ($application == "acme-mailcow") {
3743 if (isset($from) && isset($to)) {
3744 $data = $redis->lRange('ACME_LOG', $from - 1, $to - 1);
3745 }
3746 else {
3747 $data = $redis->lRange('ACME_LOG', 0, $lines);
3748 }
3749 if ($data) {
3750 foreach ($data as $json_line) {
3751 $data_array[] = json_decode($json_line, true);
3752 }
3753 return $data_array;
3754 }
3755 }
3756 if ($application == "ratelimited") {
3757 if (isset($from) && isset($to)) {
3758 $data = $redis->lRange('RL_LOG', $from - 1, $to - 1);
3759 }
3760 else {
3761 $data = $redis->lRange('RL_LOG', 0, $lines);
3762 }
3763 if ($data) {
3764 foreach ($data as $json_line) {
3765 $data_array[] = json_decode($json_line, true);
3766 }
3767 return $data_array;
3768 }
3769 }
3770 if ($application == "api-mailcow") {
3771 if (isset($from) && isset($to)) {
3772 $data = $redis->lRange('API_LOG', $from - 1, $to - 1);
3773 }
3774 else {
3775 $data = $redis->lRange('API_LOG', 0, $lines);
3776 }
3777 if ($data) {
3778 foreach ($data as $json_line) {
3779 $data_array[] = json_decode($json_line, true);
3780 }
3781 return $data_array;
3782 }
3783 }
3784 if ($application == "netfilter-mailcow") {
3785 if (isset($from) && isset($to)) {
3786 $data = $redis->lRange('NETFILTER_LOG', $from - 1, $to - 1);
3787 }
3788 else {
3789 $data = $redis->lRange('NETFILTER_LOG', 0, $lines);
3790 }
3791 if ($data) {
3792 foreach ($data as $json_line) {
3793 $data_array[] = json_decode($json_line, true);
3794 }
3795 return $data_array;
3796 }
3797 }
3798 if ($application == "autodiscover-mailcow") {
3799 if (isset($from) && isset($to)) {
3800 $data = $redis->lRange('AUTODISCOVER_LOG', $from - 1, $to - 1);
3801 }
3802 else {
3803 $data = $redis->lRange('AUTODISCOVER_LOG', 0, $lines);
3804 }
3805 if ($data) {
3806 foreach ($data as $json_line) {
3807 $data_array[] = json_decode($json_line, true);
3808 }
3809 return $data_array;
3810 }
3811 }
3812 if ($application == "rspamd-history") {
3813 $curl = curl_init();
3814 curl_setopt($curl, CURLOPT_UNIX_SOCKET_PATH, '/var/lib/rspamd/rspamd.sock');
3815 if (!is_numeric($lines)) {
3816 list ($from, $to) = explode('-', $lines);
3817 curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?from=" . intval($from) . "&to=" . intval($to));
3818 }
3819 else {
3820 curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?to=" . intval($lines));
3821 }
3822 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
3823 $history = curl_exec($curl);
3824 if (!curl_errno($curl)) {
3825 $data_array = json_decode($history, true);
3826 curl_close($curl);
3827 return $data_array['rows'];
3828 }
3829 curl_close($curl);
3830 return false;
3831 }
3832 if ($application == "rspamd-stats") {
3833 $curl = curl_init();
3834 curl_setopt($curl, CURLOPT_UNIX_SOCKET_PATH, '/var/lib/rspamd/rspamd.sock');
3835 curl_setopt($curl, CURLOPT_URL,"http://rspamd/stat");
3836 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
3837 $stats = curl_exec($curl);
3838 if (!curl_errno($curl)) {
3839 $data_array = json_decode($stats, true);
3840 curl_close($curl);
3841 return $data_array;
3842 }
3843 curl_close($curl);
3844 return false;
3845 }
3846 return false;
3847}
3848function getGUID() {
3849 if (function_exists('com_create_guid')) {
3850 return com_create_guid();
3851 }
3852 mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
3853 $charid = strtoupper(md5(uniqid(rand(), true)));
3854 $hyphen = chr(45);// "-"
3855 return substr($charid, 0, 8).$hyphen
3856 .substr($charid, 8, 4).$hyphen
3857 .substr($charid,12, 4).$hyphen
3858 .substr($charid,16, 4).$hyphen
3859 .substr($charid,20,12);
3860}
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01003861
3862function cleanupJS($ignore = '', $folder = '/tmp/*.js') {
3863 $now = time();
3864 foreach (glob($folder) as $filename) {
3865 if(strpos($filename, $ignore) !== false) {
3866 continue;
3867 }
3868 if (is_file($filename)) {
3869 if ($now - filemtime($filename) >= 60 * 60) {
3870 unlink($filename);
3871 }
3872 }
3873 }
3874}
3875
3876function cleanupCSS($ignore = '', $folder = '/tmp/*.css') {
3877 $now = time();
3878 foreach (glob($folder) as $filename) {
3879 if(strpos($filename, $ignore) !== false) {
3880 continue;
3881 }
3882 if (is_file($filename)) {
3883 if ($now - filemtime($filename) >= 60 * 60) {
3884 unlink($filename);
3885 }
3886 }
3887 }
3888}
3889
3890?>