functions.inc.php 65 KB

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