functions.inc.php 66 KB

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