functions.inc.php 67 KB

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