functions.inc.php 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504
  1. <?php
  2. function hash_password($password) {
  3. $salt_str = bin2hex(openssl_random_pseudo_bytes(8));
  4. return "{SSHA256}".base64_encode(hash('sha256', $password . $salt_str, true) . $salt_str);
  5. }
  6. function last_login($user) {
  7. global $pdo;
  8. $stmt = $pdo->prepare('SELECT `remote`, `time` FROM `logs`
  9. WHERE JSON_EXTRACT(`call`, "$[0]") = "check_login"
  10. AND JSON_EXTRACT(`call`, "$[1]") = :user
  11. AND `type` = "success" ORDER BY `time` DESC LIMIT 1');
  12. $stmt->execute(array(':user' => $user));
  13. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  14. if (!empty($row)) {
  15. return $row;
  16. }
  17. else {
  18. return false;
  19. }
  20. }
  21. function flush_memcached() {
  22. try {
  23. $m = new Memcached();
  24. $m->addServer('memcached', 11211);
  25. $m->flush();
  26. }
  27. catch ( Exception $e ) {
  28. // Dunno
  29. }
  30. }
  31. function sys_mail($_data) {
  32. if ($_SESSION['mailcow_cc_role'] != "admin") {
  33. $_SESSION['return'][] = array(
  34. 'type' => 'danger',
  35. 'log' => array(__FUNCTION__),
  36. 'msg' => 'access_denied'
  37. );
  38. return false;
  39. }
  40. $excludes = $_data['mass_exclude'];
  41. $includes = $_data['mass_include'];
  42. $mailboxes = array();
  43. $mass_from = $_data['mass_from'];
  44. $mass_text = $_data['mass_text'];
  45. $mass_subject = $_data['mass_subject'];
  46. if (!filter_var($mass_from, FILTER_VALIDATE_EMAIL)) {
  47. $_SESSION['return'][] = array(
  48. 'type' => 'danger',
  49. 'log' => array(__FUNCTION__),
  50. 'msg' => 'from_invalid'
  51. );
  52. return false;
  53. }
  54. if (empty($mass_subject)) {
  55. $_SESSION['return'][] = array(
  56. 'type' => 'danger',
  57. 'log' => array(__FUNCTION__),
  58. 'msg' => 'subject_empty'
  59. );
  60. return false;
  61. }
  62. if (empty($mass_text)) {
  63. $_SESSION['return'][] = array(
  64. 'type' => 'danger',
  65. 'log' => array(__FUNCTION__),
  66. 'msg' => 'text_empty'
  67. );
  68. return false;
  69. }
  70. $domains = array_merge(mailbox('get', 'domains'), mailbox('get', 'alias_domains'));
  71. foreach ($domains as $domain) {
  72. foreach (mailbox('get', 'mailboxes', $domain) as $mailbox) {
  73. $mailboxes[] = $mailbox;
  74. }
  75. }
  76. if (!empty($includes)) {
  77. $rcpts = array_intersect($mailboxes, $includes);
  78. }
  79. elseif (!empty($excludes)) {
  80. $rcpts = array_diff($mailboxes, $excludes);
  81. }
  82. else {
  83. $rcpts = $mailboxes;
  84. }
  85. if (!empty($rcpts)) {
  86. ini_set('max_execution_time', 0);
  87. ini_set('max_input_time', 0);
  88. $mail = new PHPMailer;
  89. $mail->Timeout = 10;
  90. $mail->SMTPOptions = array(
  91. 'ssl' => array(
  92. 'verify_peer' => false,
  93. 'verify_peer_name' => false,
  94. 'allow_self_signed' => true
  95. )
  96. );
  97. $mail->isSMTP();
  98. $mail->Host = 'dovecot-mailcow';
  99. $mail->SMTPAuth = false;
  100. $mail->Port = 24;
  101. $mail->setFrom($mass_from);
  102. $mail->Subject = $mass_subject;
  103. $mail->CharSet ="UTF-8";
  104. $mail->Body = $mass_text;
  105. $mail->XMailer = 'MooMassMail';
  106. foreach ($rcpts as $rcpt) {
  107. $mail->AddAddress($rcpt);
  108. if (!$mail->send()) {
  109. $_SESSION['return'][] = array(
  110. 'type' => 'warning',
  111. 'log' => array(__FUNCTION__),
  112. 'msg' => 'Mailer error (RCPT "' . htmlspecialchars($rcpt) . '"): ' . str_replace('https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting', '', $mail->ErrorInfo)
  113. );
  114. }
  115. $mail->ClearAllRecipients();
  116. }
  117. }
  118. $_SESSION['return'][] = array(
  119. 'type' => 'success',
  120. 'log' => array(__FUNCTION__),
  121. 'msg' => 'Mass mail job completed, sent ' . count($rcpts) . ' mails'
  122. );
  123. }
  124. function logger($_data = false) {
  125. /*
  126. logger() will be called as last function
  127. To manually log a message, logger needs to be called like below.
  128. logger(array(
  129. 'return' => array(
  130. array(
  131. 'type' => 'danger',
  132. 'log' => array(__FUNCTION__),
  133. 'msg' => $err
  134. )
  135. )
  136. ));
  137. These messages will not be printed as alert box.
  138. To do so, push them to $_SESSION['return'] and do not call logger as they will be included automatically:
  139. $_SESSION['return'][] = array(
  140. 'type' => 'danger',
  141. 'log' => array(__FUNCTION__, $user, '*'),
  142. 'msg' => $err
  143. );
  144. */
  145. global $pdo;
  146. if (!$_data) {
  147. $_data = $_SESSION;
  148. }
  149. if (!empty($_data['return'])) {
  150. $task = substr(strtoupper(md5(uniqid(rand(), true))), 0, 6);
  151. foreach ($_data['return'] as $return) {
  152. $type = $return['type'];
  153. $msg = json_encode($return['msg'], JSON_UNESCAPED_UNICODE);
  154. $call = json_encode($return['log'], JSON_UNESCAPED_UNICODE);
  155. if (!empty($_SESSION["dual-login"]["username"])) {
  156. $user = $_SESSION["dual-login"]["username"] . ' => ' . $_SESSION['mailcow_cc_username'];
  157. $role = $_SESSION["dual-login"]["role"] . ' => ' . $_SESSION['mailcow_cc_role'];
  158. }
  159. elseif (!empty($_SESSION['mailcow_cc_username'])) {
  160. $user = $_SESSION['mailcow_cc_username'];
  161. $role = $_SESSION['mailcow_cc_role'];
  162. }
  163. else {
  164. $user = 'unauthenticated';
  165. $role = 'unauthenticated';
  166. }
  167. // We cannot log when logs is missing...
  168. try {
  169. $stmt = $pdo->prepare("INSERT INTO `logs` (`type`, `task`, `msg`, `call`, `user`, `role`, `remote`, `time`) VALUES
  170. (:type, :task, :msg, :call, :user, :role, :remote, UNIX_TIMESTAMP())");
  171. $stmt->execute(array(
  172. ':type' => $type,
  173. ':task' => $task,
  174. ':call' => $call,
  175. ':msg' => $msg,
  176. ':user' => $user,
  177. ':role' => $role,
  178. ':remote' => get_remote_ip()
  179. ));
  180. }
  181. catch (Exception $e) {
  182. // Do nothing
  183. }
  184. }
  185. }
  186. else {
  187. return true;
  188. }
  189. }
  190. function hasDomainAccess($username, $role, $domain) {
  191. global $pdo;
  192. if (!filter_var($username, FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $username))) {
  193. return false;
  194. }
  195. if (empty($domain) || !is_valid_domain_name($domain)) {
  196. return false;
  197. }
  198. if ($role != 'admin' && $role != 'domainadmin') {
  199. return false;
  200. }
  201. if ($role == 'admin') {
  202. $stmt = $pdo->prepare("SELECT `domain` FROM `domain`
  203. WHERE `domain` = :domain");
  204. $stmt->execute(array(':domain' => $domain));
  205. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  206. $stmt = $pdo->prepare("SELECT `alias_domain` FROM `alias_domain`
  207. WHERE `alias_domain` = :domain");
  208. $stmt->execute(array(':domain' => $domain));
  209. $num_results = $num_results + count($stmt->fetchAll(PDO::FETCH_ASSOC));
  210. if ($num_results != 0) {
  211. return true;
  212. }
  213. }
  214. elseif ($role == 'domainadmin') {
  215. $stmt = $pdo->prepare("SELECT `domain` FROM `domain_admins`
  216. WHERE (
  217. `active`='1'
  218. AND `username` = :username
  219. AND (`domain` = :domain1 OR `domain` = (SELECT `target_domain` FROM `alias_domain` WHERE `alias_domain` = :domain2))
  220. )");
  221. $stmt->execute(array(':username' => $username, ':domain1' => $domain, ':domain2' => $domain));
  222. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  223. if (!empty($num_results)) {
  224. return true;
  225. }
  226. }
  227. return false;
  228. }
  229. function hasMailboxObjectAccess($username, $role, $object) {
  230. global $pdo;
  231. if (!filter_var(html_entity_decode(rawurldecode($username)), FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $username))) {
  232. return false;
  233. }
  234. if ($role != 'admin' && $role != 'domainadmin' && $role != 'user') {
  235. return false;
  236. }
  237. if ($username == $object) {
  238. return true;
  239. }
  240. $stmt = $pdo->prepare("SELECT `domain` FROM `mailbox` WHERE `username` = :object");
  241. $stmt->execute(array(':object' => $object));
  242. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  243. if (isset($row['domain']) && hasDomainAccess($username, $role, $row['domain'])) {
  244. return true;
  245. }
  246. return false;
  247. }
  248. function pem_to_der($pem_key) {
  249. // Need to remove BEGIN/END PUBLIC KEY
  250. $lines = explode("\n", trim($pem_key));
  251. unset($lines[count($lines)-1]);
  252. unset($lines[0]);
  253. return base64_decode(implode('', $lines));
  254. }
  255. function generate_tlsa_digest($hostname, $port, $starttls = null) {
  256. if (!is_valid_domain_name($hostname)) {
  257. return "Not a valid hostname";
  258. }
  259. if (empty($starttls)) {
  260. $context = stream_context_create(array("ssl" => array("capture_peer_cert" => true, 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true)));
  261. $stream = stream_socket_client('ssl://' . $hostname . ':' . $port, $error_nr, $error_msg, 5, STREAM_CLIENT_CONNECT, $context);
  262. if (!$stream) {
  263. $error_msg = isset($error_msg) ? $error_msg : '-';
  264. return $error_nr . ': ' . $error_msg;
  265. }
  266. }
  267. else {
  268. $stream = stream_socket_client('tcp://' . $hostname . ':' . $port, $error_nr, $error_msg, 5);
  269. if (!$stream) {
  270. return $error_nr . ': ' . $error_msg;
  271. }
  272. $banner = fread($stream, 512 );
  273. if (preg_match("/^220/i", $banner)) { // SMTP
  274. fwrite($stream,"HELO tlsa.generator.local\r\n");
  275. fread($stream, 512);
  276. fwrite($stream,"STARTTLS\r\n");
  277. fread($stream, 512);
  278. }
  279. elseif (preg_match("/imap.+starttls/i", $banner)) { // IMAP
  280. fwrite($stream,"A1 STARTTLS\r\n");
  281. fread($stream, 512);
  282. }
  283. elseif (preg_match("/^\+OK/", $banner)) { // POP3
  284. fwrite($stream,"STLS\r\n");
  285. fread($stream, 512);
  286. }
  287. elseif (preg_match("/^OK/m", $banner)) { // Sieve
  288. fwrite($stream,"STARTTLS\r\n");
  289. fread($stream, 512);
  290. }
  291. else {
  292. return 'Unknown banner: "' . htmlspecialchars(trim($banner)) . '"';
  293. }
  294. // Upgrade connection
  295. stream_set_blocking($stream, true);
  296. stream_context_set_option($stream, 'ssl', 'capture_peer_cert', true);
  297. stream_context_set_option($stream, 'ssl', 'verify_peer', false);
  298. stream_context_set_option($stream, 'ssl', 'verify_peer_name', false);
  299. stream_context_set_option($stream, 'ssl', 'allow_self_signed', true);
  300. stream_socket_enable_crypto($stream, true, STREAM_CRYPTO_METHOD_ANY_CLIENT);
  301. stream_set_blocking($stream, false);
  302. }
  303. $params = stream_context_get_params($stream);
  304. if (!empty($params['options']['ssl']['peer_certificate'])) {
  305. $key_resource = openssl_pkey_get_public($params['options']['ssl']['peer_certificate']);
  306. // We cannot get ['rsa']['n'], the binary data would contain BEGIN/END PUBLIC KEY
  307. $key_data = openssl_pkey_get_details($key_resource)['key'];
  308. return '3 1 1 ' . openssl_digest(pem_to_der($key_data), 'sha256');
  309. }
  310. else {
  311. return 'Error: Cannot read peer certificate';
  312. }
  313. }
  314. function alertbox_log_parser($_data){
  315. global $lang;
  316. if (isset($_data['return'])) {
  317. foreach ($_data['return'] as $return) {
  318. // Get type
  319. $type = $return['type'];
  320. // If a lang[type][msg] string exists, use it as message
  321. if (is_string($lang[$return['type']][$return['msg']])) {
  322. $msg = $lang[$return['type']][$return['msg']];
  323. }
  324. // If msg is an array, use first element as language string and run printf on it with remaining array elements
  325. elseif (is_array($return['msg'])) {
  326. $msg = array_shift($return['msg']);
  327. $msg = vsprintf(
  328. $lang[$return['type']][$msg],
  329. $return['msg']
  330. );
  331. }
  332. // If none applies, use msg as returned message
  333. else {
  334. $msg = $return['msg'];
  335. }
  336. $log_array[] = array('msg' => json_encode($msg), 'type' => json_encode($type));
  337. }
  338. if (!empty($log_array)) {
  339. return $log_array;
  340. }
  341. }
  342. return false;
  343. }
  344. function verify_hash($hash, $password) {
  345. if (preg_match('/^{SSHA256}/i', $hash)) {
  346. // Remove tag if any
  347. $hash = preg_replace('/^{SSHA256}/i', '', $hash);
  348. // Decode hash
  349. $dhash = base64_decode($hash);
  350. // Get first 32 bytes of binary which equals a SHA256 hash
  351. $ohash = substr($dhash, 0, 32);
  352. // Remove SHA256 hash from decoded hash to get original salt string
  353. $osalt = str_replace($ohash, '', $dhash);
  354. // Check single salted SHA256 hash against extracted hash
  355. if (hash_equals(hash('sha256', $password . $osalt, true), $ohash)) {
  356. return true;
  357. }
  358. }
  359. elseif (preg_match('/^{SHA512-CRYPT}/i', $hash)) {
  360. // Remove tag if any
  361. $hash = preg_replace('/^{SHA512-CRYPT}/i', '', $hash);
  362. // Decode hash
  363. preg_match('/\\$6\\$(.*)\\$(.*)/i', $hash, $hash_array);
  364. $osalt = $hash_array[1];
  365. $ohash = $hash_array[2];
  366. if (hash_equals(crypt($password, '$6$' . $osalt . '$'), $hash)) {
  367. return true;
  368. }
  369. }
  370. elseif (preg_match('/^{SSHA512}/i', $hash)) {
  371. $hash = preg_replace('/^{SSHA512}/i', '', $hash);
  372. // Decode hash
  373. $dhash = base64_decode($hash);
  374. // Get first 64 bytes of binary which equals a SHA512 hash
  375. $ohash = substr($dhash, 0, 64);
  376. // Remove SHA512 hash from decoded hash to get original salt string
  377. $osalt = str_replace($ohash, '', $dhash);
  378. // Check single salted SHA512 hash against extracted hash
  379. if (hash_equals(hash('sha512', $password . $osalt, true), $ohash)) {
  380. return true;
  381. }
  382. }
  383. elseif (preg_match('/^{MD5-CRYPT}/i', $hash)) {
  384. $hash = preg_replace('/^{MD5-CRYPT}/i', '', $hash);
  385. if (password_verify($password, $hash)) {
  386. return true;
  387. }
  388. }
  389. return false;
  390. }
  391. function check_login($user, $pass) {
  392. global $pdo;
  393. global $redis;
  394. global $imap_server;
  395. if (!filter_var($user, FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $user))) {
  396. $_SESSION['return'][] = array(
  397. 'type' => 'danger',
  398. 'log' => array(__FUNCTION__, $user, '*'),
  399. 'msg' => 'malformed_username'
  400. );
  401. return false;
  402. }
  403. $user = strtolower(trim($user));
  404. $stmt = $pdo->prepare("SELECT `password` FROM `admin`
  405. WHERE `superadmin` = '1'
  406. AND `username` = :user");
  407. $stmt->execute(array(':user' => $user));
  408. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  409. foreach ($rows as $row) {
  410. if (verify_hash($row['password'], $pass)) {
  411. if (get_tfa($user)['name'] != "none") {
  412. $_SESSION['pending_mailcow_cc_username'] = $user;
  413. $_SESSION['pending_mailcow_cc_role'] = "admin";
  414. $_SESSION['pending_tfa_method'] = get_tfa($user)['name'];
  415. unset($_SESSION['ldelay']);
  416. $_SESSION['return'][] = array(
  417. 'type' => 'info',
  418. 'log' => array(__FUNCTION__, $user, '*'),
  419. 'msg' => 'awaiting_tfa_confirmation'
  420. );
  421. return "pending";
  422. }
  423. else {
  424. unset($_SESSION['ldelay']);
  425. // Reactivate TFA if it was set to "deactivate TFA for next login"
  426. $stmt = $pdo->prepare("UPDATE `tfa` SET `active`='1' WHERE `username` = :user");
  427. $stmt->execute(array(':user' => $user));
  428. $_SESSION['return'][] = array(
  429. 'type' => 'success',
  430. 'log' => array(__FUNCTION__, $user, '*'),
  431. 'msg' => array('logged_in_as', $user)
  432. );
  433. return "admin";
  434. }
  435. }
  436. }
  437. $stmt = $pdo->prepare("SELECT `password` FROM `admin`
  438. WHERE `superadmin` = '0'
  439. AND `active`='1'
  440. AND `username` = :user");
  441. $stmt->execute(array(':user' => $user));
  442. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  443. foreach ($rows as $row) {
  444. if (verify_hash($row['password'], $pass) !== false) {
  445. if (get_tfa($user)['name'] != "none") {
  446. $_SESSION['pending_mailcow_cc_username'] = $user;
  447. $_SESSION['pending_mailcow_cc_role'] = "domainadmin";
  448. $_SESSION['pending_tfa_method'] = get_tfa($user)['name'];
  449. unset($_SESSION['ldelay']);
  450. $_SESSION['return'][] = array(
  451. 'type' => 'info',
  452. 'log' => array(__FUNCTION__, $user, '*'),
  453. 'msg' => 'awaiting_tfa_confirmation'
  454. );
  455. return "pending";
  456. }
  457. else {
  458. unset($_SESSION['ldelay']);
  459. // Reactivate TFA if it was set to "deactivate TFA for next login"
  460. $stmt = $pdo->prepare("UPDATE `tfa` SET `active`='1' WHERE `username` = :user");
  461. $stmt->execute(array(':user' => $user));
  462. $_SESSION['return'][] = array(
  463. 'type' => 'success',
  464. 'log' => array(__FUNCTION__, $user, '*'),
  465. 'msg' => array('logged_in_as', $user)
  466. );
  467. return "domainadmin";
  468. }
  469. }
  470. }
  471. $stmt = $pdo->prepare("SELECT `password` FROM `mailbox`
  472. WHERE `kind` NOT REGEXP 'location|thing|group'
  473. AND `active`='1'
  474. AND `username` = :user");
  475. $stmt->execute(array(':user' => $user));
  476. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  477. foreach ($rows as $row) {
  478. if (verify_hash($row['password'], $pass) !== false) {
  479. unset($_SESSION['ldelay']);
  480. $_SESSION['return'][] = array(
  481. 'type' => 'success',
  482. 'log' => array(__FUNCTION__, $user, '*'),
  483. 'msg' => array('logged_in_as', $user)
  484. );
  485. return "user";
  486. }
  487. }
  488. if (!isset($_SESSION['ldelay'])) {
  489. $_SESSION['ldelay'] = "0";
  490. $redis->publish("F2B_CHANNEL", "mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  491. error_log("mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  492. }
  493. elseif (!isset($_SESSION['mailcow_cc_username'])) {
  494. $_SESSION['ldelay'] = $_SESSION['ldelay']+0.5;
  495. $redis->publish("F2B_CHANNEL", "mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  496. error_log("mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  497. }
  498. $_SESSION['return'][] = array(
  499. 'type' => 'danger',
  500. 'log' => array(__FUNCTION__, $user, '*'),
  501. 'msg' => 'login_failed'
  502. );
  503. sleep($_SESSION['ldelay']);
  504. return false;
  505. }
  506. function formatBytes($size, $precision = 2) {
  507. if(!is_numeric($size)) {
  508. return "0";
  509. }
  510. $base = log($size, 1024);
  511. $suffixes = array(' Byte', ' KiB', ' MiB', ' GiB', ' TiB');
  512. if ($size == "0") {
  513. return "0";
  514. }
  515. return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
  516. }
  517. function update_sogo_static_view() {
  518. global $pdo;
  519. global $lang;
  520. $stmt = $pdo->query("SELECT 'OK' FROM INFORMATION_SCHEMA.TABLES
  521. WHERE TABLE_NAME = 'sogo_view'");
  522. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  523. if ($num_results != 0) {
  524. $stmt = $pdo->query("REPLACE INTO _sogo_static_view (`c_uid`, `domain`, `c_name`, `c_password`, `c_cn`, `mail`, `aliases`, `ad_aliases`, `kind`, `multiple_bookings`)
  525. SELECT `c_uid`, `domain`, `c_name`, `c_password`, `c_cn`, `mail`, `aliases`, `ad_aliases`, `kind`, `multiple_bookings` from sogo_view");
  526. $stmt = $pdo->query("DELETE FROM _sogo_static_view WHERE `c_uid` NOT IN (SELECT `username` FROM `mailbox` WHERE `active` = '1');");
  527. }
  528. flush_memcached();
  529. }
  530. function edit_user_account($_data) {
  531. global $lang;
  532. global $pdo;
  533. $_data_log = $_data;
  534. !isset($_data_log['user_new_pass']) ?: $_data_log['user_new_pass'] = '*';
  535. !isset($_data_log['user_new_pass2']) ?: $_data_log['user_new_pass2'] = '*';
  536. !isset($_data_log['user_old_pass']) ?: $_data_log['user_old_pass'] = '*';
  537. $username = $_SESSION['mailcow_cc_username'];
  538. $role = $_SESSION['mailcow_cc_role'];
  539. $password_old = $_data['user_old_pass'];
  540. if (filter_var($username, FILTER_VALIDATE_EMAIL === false) || $role != 'user') {
  541. $_SESSION['return'][] = array(
  542. 'type' => 'danger',
  543. 'log' => array(__FUNCTION__, $_data_log),
  544. 'msg' => 'access_denied'
  545. );
  546. return false;
  547. }
  548. if (isset($_data['user_new_pass']) && isset($_data['user_new_pass2'])) {
  549. $password_new = $_data['user_new_pass'];
  550. $password_new2 = $_data['user_new_pass2'];
  551. }
  552. $stmt = $pdo->prepare("SELECT `password` FROM `mailbox`
  553. WHERE `kind` NOT REGEXP 'location|thing|group'
  554. AND `username` = :user");
  555. $stmt->execute(array(':user' => $username));
  556. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  557. if (!verify_hash($row['password'], $password_old)) {
  558. $_SESSION['return'][] = array(
  559. 'type' => 'danger',
  560. 'log' => array(__FUNCTION__, $_data_log),
  561. 'msg' => 'access_denied'
  562. );
  563. return false;
  564. }
  565. if (isset($password_new) && isset($password_new2)) {
  566. if (!empty($password_new2) && !empty($password_new)) {
  567. if ($password_new2 != $password_new) {
  568. $_SESSION['return'][] = array(
  569. 'type' => 'danger',
  570. 'log' => array(__FUNCTION__, $_data_log),
  571. 'msg' => 'password_mismatch'
  572. );
  573. return false;
  574. }
  575. if (!preg_match('/' . $GLOBALS['PASSWD_REGEP'] . '/', $password_new)) {
  576. $_SESSION['return'][] = array(
  577. 'type' => 'danger',
  578. 'log' => array(__FUNCTION__, $_data_log),
  579. 'msg' => 'password_complexity'
  580. );
  581. return false;
  582. }
  583. $password_hashed = hash_password($password_new);
  584. try {
  585. $stmt = $pdo->prepare("UPDATE `mailbox` SET `password` = :password_hashed, `attributes` = JSON_SET(`attributes`, '$.force_pw_update', '0') WHERE `username` = :username");
  586. $stmt->execute(array(
  587. ':password_hashed' => $password_hashed,
  588. ':username' => $username
  589. ));
  590. }
  591. catch (PDOException $e) {
  592. $_SESSION['return'][] = array(
  593. 'type' => 'danger',
  594. 'log' => array(__FUNCTION__, $_data_log),
  595. 'msg' => array('mysql_error', $e)
  596. );
  597. return false;
  598. }
  599. }
  600. }
  601. update_sogo_static_view();
  602. $_SESSION['return'][] = array(
  603. 'type' => 'success',
  604. 'log' => array(__FUNCTION__, $_data_log),
  605. 'msg' => array('mailbox_modified', htmlspecialchars($username))
  606. );
  607. }
  608. function user_get_alias_details($username) {
  609. global $lang;
  610. global $pdo;
  611. $data['direct_aliases'] = false;
  612. $data['shared_aliases'] = false;
  613. if ($_SESSION['mailcow_cc_role'] == "user") {
  614. $username = $_SESSION['mailcow_cc_username'];
  615. }
  616. if (!filter_var($username, FILTER_VALIDATE_EMAIL)) {
  617. return false;
  618. }
  619. $data['address'] = $username;
  620. $stmt = $pdo->prepare("SELECT `address` AS `shared_aliases`, `public_comment` FROM `alias`
  621. WHERE `goto` REGEXP :username_goto
  622. AND `address` NOT LIKE '@%'
  623. AND `goto` != :username_goto2
  624. AND `address` != :username_address");
  625. $stmt->execute(array(
  626. ':username_goto' => '(^|,)'.$username.'($|,)',
  627. ':username_goto2' => $username,
  628. ':username_address' => $username
  629. ));
  630. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  631. while ($row = array_shift($run)) {
  632. $data['shared_aliases'][] = $row['shared_aliases'];
  633. }
  634. $stmt = $pdo->prepare("SELECT `address` AS `direct_aliases`, `public_comment` FROM `alias`
  635. WHERE `goto` = :username_goto
  636. AND `address` NOT LIKE '@%'
  637. AND `address` != :username_address");
  638. $stmt->execute(
  639. array(
  640. ':username_goto' => $username,
  641. ':username_address' => $username
  642. ));
  643. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  644. while ($row = array_shift($run)) {
  645. $data['direct_aliases'][$row['direct_aliases']]['public_comment'] = htmlspecialchars($row['public_comment']);
  646. }
  647. $stmt = $pdo->prepare("SELECT CONCAT(local_part, '@', alias_domain) AS `ad_alias`, `alias_domain` FROM `mailbox`
  648. LEFT OUTER JOIN `alias_domain` on `target_domain` = `domain`
  649. WHERE `username` = :username ;");
  650. $stmt->execute(array(':username' => $username));
  651. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  652. while ($row = array_shift($run)) {
  653. $data['direct_aliases'][$row['ad_alias']]['public_comment'] = '↪ ' . $row['alias_domain'];
  654. }
  655. $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 '@%';");
  656. $stmt->execute(array(':username' => $username));
  657. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  658. while ($row = array_shift($run)) {
  659. $data['aliases_also_send_as'] = $row['send_as'];
  660. }
  661. $stmt = $pdo->prepare("SELECT IFNULL(CONCAT(GROUP_CONCAT(DISTINCT `send_as` SEPARATOR ', '), ', ', GROUP_CONCAT(DISTINCT CONCAT('@',`alias_domain`) SEPARATOR ', ')), '&#10008;') 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 '@%';");
  662. $stmt->execute(array(':username' => $username));
  663. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  664. while ($row = array_shift($run)) {
  665. $data['aliases_send_as_all'] = $row['send_as'];
  666. }
  667. $stmt = $pdo->prepare("SELECT IFNULL(GROUP_CONCAT(`address` SEPARATOR ', '), '&#10008;') as `address` FROM `alias` WHERE `goto` REGEXP :username AND `address` LIKE '@%';");
  668. $stmt->execute(array(':username' => '(^|,)'.$username.'($|,)'));
  669. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  670. while ($row = array_shift($run)) {
  671. $data['is_catch_all'] = $row['address'];
  672. }
  673. return $data;
  674. }
  675. function is_valid_domain_name($domain_name) {
  676. if (empty($domain_name)) {
  677. return false;
  678. }
  679. $domain_name = idn_to_ascii($domain_name);
  680. return (preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $domain_name)
  681. && preg_match("/^.{1,253}$/", $domain_name)
  682. && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $domain_name));
  683. }
  684. function set_tfa($_data) {
  685. global $lang;
  686. global $pdo;
  687. global $yubi;
  688. global $u2f;
  689. global $tfa;
  690. $_data_log = $_data;
  691. !isset($_data_log['confirm_password']) ?: $_data_log['confirm_password'] = '*';
  692. $username = $_SESSION['mailcow_cc_username'];
  693. if ($_SESSION['mailcow_cc_role'] != "domainadmin" &&
  694. $_SESSION['mailcow_cc_role'] != "admin") {
  695. $_SESSION['return'][] = array(
  696. 'type' => 'danger',
  697. 'log' => array(__FUNCTION__, $_data_log),
  698. 'msg' => 'access_denied'
  699. );
  700. return false;
  701. }
  702. $stmt = $pdo->prepare("SELECT `password` FROM `admin`
  703. WHERE `username` = :user");
  704. $stmt->execute(array(':user' => $username));
  705. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  706. if (!verify_hash($row['password'], $_data["confirm_password"])) {
  707. $_SESSION['return'][] = array(
  708. 'type' => 'danger',
  709. 'log' => array(__FUNCTION__, $_data_log),
  710. 'msg' => 'access_denied'
  711. );
  712. return false;
  713. }
  714. switch ($_data["tfa_method"]) {
  715. case "yubi_otp":
  716. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  717. $yubico_id = $_data['yubico_id'];
  718. $yubico_key = $_data['yubico_key'];
  719. $yubi = new Auth_Yubico($yubico_id, $yubico_key);
  720. if (!$yubi) {
  721. $_SESSION['return'][] = array(
  722. 'type' => 'danger',
  723. 'log' => array(__FUNCTION__, $_data_log),
  724. 'msg' => 'access_denied'
  725. );
  726. return false;
  727. }
  728. if (!ctype_alnum($_data["otp_token"]) || strlen($_data["otp_token"]) != 44) {
  729. $_SESSION['return'][] = array(
  730. 'type' => 'danger',
  731. 'log' => array(__FUNCTION__, $_data_log),
  732. 'msg' => 'tfa_token_invalid'
  733. );
  734. return false;
  735. }
  736. $yauth = $yubi->verify($_data["otp_token"]);
  737. if (PEAR::isError($yauth)) {
  738. $_SESSION['return'][] = array(
  739. 'type' => 'danger',
  740. 'log' => array(__FUNCTION__, $_data_log),
  741. 'msg' => array('yotp_verification_failed', $yauth->getMessage())
  742. );
  743. return false;
  744. }
  745. try {
  746. // We could also do a modhex translation here
  747. $yubico_modhex_id = substr($_data["otp_token"], 0, 12);
  748. $stmt = $pdo->prepare("DELETE FROM `tfa`
  749. WHERE `username` = :username
  750. AND (`authmech` != 'yubi_otp')
  751. OR (`authmech` = 'yubi_otp' AND `secret` LIKE :modhex)");
  752. $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id));
  753. $stmt = $pdo->prepare("INSERT INTO `tfa` (`key_id`, `username`, `authmech`, `active`, `secret`) VALUES
  754. (:key_id, :username, 'yubi_otp', '1', :secret)");
  755. $stmt->execute(array(':key_id' => $key_id, ':username' => $username, ':secret' => $yubico_id . ':' . $yubico_key . ':' . $yubico_modhex_id));
  756. }
  757. catch (PDOException $e) {
  758. $_SESSION['return'][] = array(
  759. 'type' => 'danger',
  760. 'log' => array(__FUNCTION__, $_data_log),
  761. 'msg' => array('mysql_error', $e)
  762. );
  763. return false;
  764. }
  765. $_SESSION['return'][] = array(
  766. 'type' => 'success',
  767. 'log' => array(__FUNCTION__, $_data_log),
  768. 'msg' => array('object_modified', htmlspecialchars($username))
  769. );
  770. break;
  771. case "u2f":
  772. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  773. try {
  774. $reg = $u2f->doRegister(json_decode($_SESSION['regReq']), json_decode($_data['token']));
  775. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username AND `authmech` != 'u2f'");
  776. $stmt->execute(array(':username' => $username));
  777. $stmt = $pdo->prepare("INSERT INTO `tfa` (`username`, `key_id`, `authmech`, `keyHandle`, `publicKey`, `certificate`, `counter`, `active`) VALUES (?, ?, 'u2f', ?, ?, ?, ?, '1')");
  778. $stmt->execute(array($username, $key_id, $reg->keyHandle, $reg->publicKey, $reg->certificate, $reg->counter));
  779. $_SESSION['return'][] = array(
  780. 'type' => 'success',
  781. 'log' => array(__FUNCTION__, $_data_log),
  782. 'msg' => array('object_modified', $username)
  783. );
  784. $_SESSION['regReq'] = null;
  785. }
  786. catch (Exception $e) {
  787. $_SESSION['return'][] = array(
  788. 'type' => 'danger',
  789. 'log' => array(__FUNCTION__, $_data_log),
  790. 'msg' => array('u2f_verification_failed', $e->getMessage())
  791. );
  792. $_SESSION['regReq'] = null;
  793. return false;
  794. }
  795. break;
  796. case "totp":
  797. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  798. if ($tfa->verifyCode($_POST['totp_secret'], $_POST['totp_confirm_token']) === true) {
  799. try {
  800. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
  801. $stmt->execute(array(':username' => $username));
  802. $stmt = $pdo->prepare("INSERT INTO `tfa` (`username`, `key_id`, `authmech`, `secret`, `active`) VALUES (?, ?, 'totp', ?, '1')");
  803. $stmt->execute(array($username, $key_id, $_POST['totp_secret']));
  804. }
  805. catch (PDOException $e) {
  806. $_SESSION['return'][] = array(
  807. 'type' => 'danger',
  808. 'log' => array(__FUNCTION__, $_data_log),
  809. 'msg' => array('mysql_error', $e)
  810. );
  811. return false;
  812. }
  813. $_SESSION['return'][] = array(
  814. 'type' => 'success',
  815. 'log' => array(__FUNCTION__, $_data_log),
  816. 'msg' => array('object_modified', $username)
  817. );
  818. }
  819. else {
  820. $_SESSION['return'][] = array(
  821. 'type' => 'danger',
  822. 'log' => array(__FUNCTION__, $_data_log),
  823. 'msg' => 'totp_verification_failed'
  824. );
  825. }
  826. break;
  827. case "none":
  828. try {
  829. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
  830. $stmt->execute(array(':username' => $username));
  831. }
  832. catch (PDOException $e) {
  833. $_SESSION['return'][] = array(
  834. 'type' => 'danger',
  835. 'log' => array(__FUNCTION__, $_data_log),
  836. 'msg' => array('mysql_error', $e)
  837. );
  838. return false;
  839. }
  840. $_SESSION['return'][] = array(
  841. 'type' => 'success',
  842. 'log' => array(__FUNCTION__, $_data_log),
  843. 'msg' => array('object_modified', htmlspecialchars($username))
  844. );
  845. break;
  846. }
  847. }
  848. function unset_tfa_key($_data) {
  849. // Can only unset own keys
  850. // Needs at least one key left
  851. global $pdo;
  852. global $lang;
  853. $_data_log = $_data;
  854. $id = intval($_data['unset_tfa_key']);
  855. $username = $_SESSION['mailcow_cc_username'];
  856. if ($_SESSION['mailcow_cc_role'] != "domainadmin" &&
  857. $_SESSION['mailcow_cc_role'] != "admin") {
  858. $_SESSION['return'][] = array(
  859. 'type' => 'danger',
  860. 'log' => array(__FUNCTION__, $_data_log),
  861. 'msg' => 'access_denied'
  862. );
  863. return false;
  864. }
  865. try {
  866. if (!is_numeric($id)) {
  867. $_SESSION['return'][] = array(
  868. 'type' => 'danger',
  869. 'log' => array(__FUNCTION__, $_data_log),
  870. 'msg' => 'access_denied'
  871. );
  872. return false;
  873. }
  874. $stmt = $pdo->prepare("SELECT COUNT(*) AS `keys` FROM `tfa`
  875. WHERE `username` = :username AND `active` = '1'");
  876. $stmt->execute(array(':username' => $username));
  877. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  878. if ($row['keys'] == "1") {
  879. $_SESSION['return'][] = array(
  880. 'type' => 'danger',
  881. 'log' => array(__FUNCTION__, $_data_log),
  882. 'msg' => 'last_key'
  883. );
  884. return false;
  885. }
  886. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username AND `id` = :id");
  887. $stmt->execute(array(':username' => $username, ':id' => $id));
  888. $_SESSION['return'][] = array(
  889. 'type' => 'success',
  890. 'log' => array(__FUNCTION__, $_data_log),
  891. 'msg' => array('object_modified', $username)
  892. );
  893. }
  894. catch (PDOException $e) {
  895. $_SESSION['return'][] = array(
  896. 'type' => 'danger',
  897. 'log' => array(__FUNCTION__, $_data_log),
  898. 'msg' => array('mysql_error', $e)
  899. );
  900. return false;
  901. }
  902. }
  903. function get_tfa($username = null) {
  904. global $pdo;
  905. if (isset($_SESSION['mailcow_cc_username'])) {
  906. $username = $_SESSION['mailcow_cc_username'];
  907. }
  908. elseif (empty($username)) {
  909. return false;
  910. }
  911. $stmt = $pdo->prepare("SELECT * FROM `tfa`
  912. WHERE `username` = :username AND `active` = '1'");
  913. $stmt->execute(array(':username' => $username));
  914. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  915. switch ($row["authmech"]) {
  916. case "yubi_otp":
  917. $data['name'] = "yubi_otp";
  918. $data['pretty'] = "Yubico OTP";
  919. $stmt = $pdo->prepare("SELECT `id`, `key_id`, RIGHT(`secret`, 12) AS 'modhex' FROM `tfa` WHERE `authmech` = 'yubi_otp' AND `username` = :username");
  920. $stmt->execute(array(
  921. ':username' => $username,
  922. ));
  923. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  924. while($row = array_shift($rows)) {
  925. $data['additional'][] = $row;
  926. }
  927. return $data;
  928. break;
  929. case "u2f":
  930. $data['name'] = "u2f";
  931. $data['pretty'] = "Fido U2F";
  932. $stmt = $pdo->prepare("SELECT `id`, `key_id` FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username");
  933. $stmt->execute(array(
  934. ':username' => $username,
  935. ));
  936. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  937. while($row = array_shift($rows)) {
  938. $data['additional'][] = $row;
  939. }
  940. return $data;
  941. break;
  942. case "hotp":
  943. $data['name'] = "hotp";
  944. $data['pretty'] = "HMAC-based OTP";
  945. return $data;
  946. break;
  947. case "totp":
  948. $data['name'] = "totp";
  949. $data['pretty'] = "Time-based OTP";
  950. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `secret` FROM `tfa` WHERE `authmech` = 'totp' AND `username` = :username");
  951. $stmt->execute(array(
  952. ':username' => $username,
  953. ));
  954. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  955. while($row = array_shift($rows)) {
  956. $data['additional'][] = $row;
  957. }
  958. return $data;
  959. break;
  960. default:
  961. $data['name'] = 'none';
  962. $data['pretty'] = "-";
  963. return $data;
  964. break;
  965. }
  966. }
  967. function verify_tfa_login($username, $token) {
  968. global $pdo;
  969. global $lang;
  970. global $yubi;
  971. global $u2f;
  972. global $tfa;
  973. $stmt = $pdo->prepare("SELECT `authmech` FROM `tfa`
  974. WHERE `username` = :username AND `active` = '1'");
  975. $stmt->execute(array(':username' => $username));
  976. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  977. switch ($row["authmech"]) {
  978. case "yubi_otp":
  979. if (!ctype_alnum($token) || strlen($token) != 44) {
  980. $_SESSION['return'][] = array(
  981. 'type' => 'danger',
  982. 'log' => array(__FUNCTION__, $username, '*'),
  983. 'msg' => array('yotp_verification_failed', 'token length error')
  984. );
  985. return false;
  986. }
  987. $yubico_modhex_id = substr($token, 0, 12);
  988. $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
  989. WHERE `username` = :username
  990. AND `authmech` = 'yubi_otp'
  991. AND `active`='1'
  992. AND `secret` LIKE :modhex");
  993. $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id));
  994. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  995. $yubico_auth = explode(':', $row['secret']);
  996. $yubi = new Auth_Yubico($yubico_auth[0], $yubico_auth[1]);
  997. $yauth = $yubi->verify($token);
  998. if (PEAR::isError($yauth)) {
  999. $_SESSION['return'][] = array(
  1000. 'type' => 'danger',
  1001. 'log' => array(__FUNCTION__, $username, '*'),
  1002. 'msg' => array('yotp_verification_failed', $yauth->getMessage())
  1003. );
  1004. return false;
  1005. }
  1006. else {
  1007. $_SESSION['tfa_id'] = $row['id'];
  1008. $_SESSION['return'][] = array(
  1009. 'type' => 'success',
  1010. 'log' => array(__FUNCTION__, $username, '*'),
  1011. 'msg' => 'verified_yotp_login'
  1012. );
  1013. return true;
  1014. }
  1015. $_SESSION['return'][] = array(
  1016. 'type' => 'danger',
  1017. 'log' => array(__FUNCTION__, $username, '*'),
  1018. 'msg' => array('yotp_verification_failed', 'unknown')
  1019. );
  1020. return false;
  1021. break;
  1022. case "u2f":
  1023. try {
  1024. $reg = $u2f->doAuthenticate(json_decode($_SESSION['authReq']), get_u2f_registrations($username), json_decode($token));
  1025. $stmt = $pdo->prepare("UPDATE `tfa` SET `counter` = ? WHERE `id` = ?");
  1026. $stmt->execute(array($reg->counter, $reg->id));
  1027. $_SESSION['tfa_id'] = $reg->id;
  1028. $_SESSION['authReq'] = null;
  1029. $_SESSION['return'][] = array(
  1030. 'type' => 'success',
  1031. 'log' => array(__FUNCTION__, $username, '*'),
  1032. 'msg' => 'verified_u2f_login'
  1033. );
  1034. return true;
  1035. }
  1036. catch (Exception $e) {
  1037. $_SESSION['return'][] = array(
  1038. 'type' => 'danger',
  1039. 'log' => array(__FUNCTION__, $username, '*'),
  1040. 'msg' => array('u2f_verification_failed', $e->getMessage())
  1041. );
  1042. $_SESSION['regReq'] = null;
  1043. return false;
  1044. }
  1045. $_SESSION['return'][] = array(
  1046. 'type' => 'danger',
  1047. 'log' => array(__FUNCTION__, $username, '*'),
  1048. 'msg' => array('u2f_verification_failed', 'unknown')
  1049. );
  1050. return false;
  1051. break;
  1052. case "hotp":
  1053. return false;
  1054. break;
  1055. case "totp":
  1056. try {
  1057. $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
  1058. WHERE `username` = :username
  1059. AND `authmech` = 'totp'
  1060. AND `active`='1'");
  1061. $stmt->execute(array(':username' => $username));
  1062. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1063. if ($tfa->verifyCode($row['secret'], $_POST['token']) === true) {
  1064. $_SESSION['tfa_id'] = $row['id'];
  1065. $_SESSION['return'][] = array(
  1066. 'type' => 'success',
  1067. 'log' => array(__FUNCTION__, $username, '*'),
  1068. 'msg' => 'verified_totp_login'
  1069. );
  1070. return true;
  1071. }
  1072. $_SESSION['return'][] = array(
  1073. 'type' => 'danger',
  1074. 'log' => array(__FUNCTION__, $username, '*'),
  1075. 'msg' => 'totp_verification_failed'
  1076. );
  1077. return false;
  1078. }
  1079. catch (PDOException $e) {
  1080. $_SESSION['return'][] = array(
  1081. 'type' => 'danger',
  1082. 'log' => array(__FUNCTION__, $username, '*'),
  1083. 'msg' => array('mysql_error', $e)
  1084. );
  1085. return false;
  1086. }
  1087. break;
  1088. default:
  1089. $_SESSION['return'][] = array(
  1090. 'type' => 'danger',
  1091. 'log' => array(__FUNCTION__, $username, '*'),
  1092. 'msg' => 'unknown_tfa_method'
  1093. );
  1094. return false;
  1095. break;
  1096. }
  1097. return false;
  1098. }
  1099. function admin_api($action, $data = null) {
  1100. global $pdo;
  1101. global $lang;
  1102. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1103. $_SESSION['return'][] = array(
  1104. 'type' => 'danger',
  1105. 'log' => array(__FUNCTION__),
  1106. 'msg' => 'access_denied'
  1107. );
  1108. return false;
  1109. }
  1110. switch ($action) {
  1111. case "edit":
  1112. $regen_key = $data['admin_api_regen_key'];
  1113. $active = (isset($data['active'])) ? 1 : 0;
  1114. $allow_from = array_map('trim', preg_split( "/( |,|;|\n)/", $data['allow_from']));
  1115. foreach ($allow_from as $key => $val) {
  1116. if (!filter_var($val, FILTER_VALIDATE_IP)) {
  1117. $_SESSION['return'][] = array(
  1118. 'type' => 'warning',
  1119. 'log' => array(__FUNCTION__, $data),
  1120. 'msg' => array('ip_invalid', htmlspecialchars($allow_from[$key]))
  1121. );
  1122. unset($allow_from[$key]);
  1123. continue;
  1124. }
  1125. }
  1126. $allow_from = implode(',', array_unique(array_filter($allow_from)));
  1127. if (empty($allow_from)) {
  1128. $_SESSION['return'][] = array(
  1129. 'type' => 'danger',
  1130. 'log' => array(__FUNCTION__, $data),
  1131. 'msg' => 'ip_list_empty'
  1132. );
  1133. return false;
  1134. }
  1135. $api_key = implode('-', array(
  1136. strtoupper(bin2hex(random_bytes(3))),
  1137. strtoupper(bin2hex(random_bytes(3))),
  1138. strtoupper(bin2hex(random_bytes(3))),
  1139. strtoupper(bin2hex(random_bytes(3))),
  1140. strtoupper(bin2hex(random_bytes(3)))
  1141. ));
  1142. $stmt = $pdo->query("SELECT `api_key` FROM `api`");
  1143. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  1144. if (empty($num_results)) {
  1145. $stmt = $pdo->prepare("INSERT INTO `api` (`api_key`, `active`, `allow_from`)
  1146. VALUES (:api_key, :active, :allow_from);");
  1147. $stmt->execute(array(
  1148. ':api_key' => $api_key,
  1149. ':active' => $active,
  1150. ':allow_from' => $allow_from
  1151. ));
  1152. }
  1153. else {
  1154. $stmt = $pdo->prepare("UPDATE `api` SET `active` = :active, `allow_from` = :allow_from ;");
  1155. $stmt->execute(array(
  1156. ':active' => $active,
  1157. ':allow_from' => $allow_from
  1158. ));
  1159. }
  1160. break;
  1161. case "regen_key":
  1162. $api_key = implode('-', array(
  1163. strtoupper(bin2hex(random_bytes(3))),
  1164. strtoupper(bin2hex(random_bytes(3))),
  1165. strtoupper(bin2hex(random_bytes(3))),
  1166. strtoupper(bin2hex(random_bytes(3))),
  1167. strtoupper(bin2hex(random_bytes(3)))
  1168. ));
  1169. $stmt = $pdo->prepare("UPDATE `api` SET `api_key` = :api_key");
  1170. $stmt->execute(array(
  1171. ':api_key' => $api_key
  1172. ));
  1173. break;
  1174. case "get":
  1175. $stmt = $pdo->query("SELECT * FROM `api`");
  1176. $apidata = $stmt->fetch(PDO::FETCH_ASSOC);
  1177. return $apidata;
  1178. break;
  1179. }
  1180. $_SESSION['return'][] = array(
  1181. 'type' => 'success',
  1182. 'log' => array(__FUNCTION__, $data),
  1183. 'msg' => 'admin_api_modified'
  1184. );
  1185. }
  1186. function rspamd_ui($action, $data = null) {
  1187. global $lang;
  1188. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1189. $_SESSION['return'][] = array(
  1190. 'type' => 'danger',
  1191. 'log' => array(__FUNCTION__),
  1192. 'msg' => 'access_denied'
  1193. );
  1194. return false;
  1195. }
  1196. switch ($action) {
  1197. case "edit":
  1198. $rspamd_ui_pass = $data['rspamd_ui_pass'];
  1199. $rspamd_ui_pass2 = $data['rspamd_ui_pass2'];
  1200. if (empty($rspamd_ui_pass) || empty($rspamd_ui_pass2)) {
  1201. $_SESSION['return'][] = array(
  1202. 'type' => 'danger',
  1203. 'log' => array(__FUNCTION__, '*', '*'),
  1204. 'msg' => 'password_empty'
  1205. );
  1206. return false;
  1207. }
  1208. if ($rspamd_ui_pass != $rspamd_ui_pass2) {
  1209. $_SESSION['return'][] = array(
  1210. 'type' => 'danger',
  1211. 'log' => array(__FUNCTION__, '*', '*'),
  1212. 'msg' => 'password_mismatch'
  1213. );
  1214. return false;
  1215. }
  1216. if (strlen($rspamd_ui_pass) < 6) {
  1217. $_SESSION['return'][] = array(
  1218. 'type' => 'danger',
  1219. 'log' => array(__FUNCTION__, '*', '*'),
  1220. 'msg' => 'rspamd_ui_pw_length'
  1221. );
  1222. return false;
  1223. }
  1224. $docker_return = docker('post', 'rspamd-mailcow', 'exec', array('cmd' => 'rspamd', 'task' => 'worker_password', 'raw' => $rspamd_ui_pass), array('Content-Type: application/json'));
  1225. if ($docker_return_array = json_decode($docker_return, true)) {
  1226. if ($docker_return_array['type'] == 'success') {
  1227. $_SESSION['return'][] = array(
  1228. 'type' => 'success',
  1229. 'log' => array(__FUNCTION__, '*', '*'),
  1230. 'msg' => 'rspamd_ui_pw_set'
  1231. );
  1232. return true;
  1233. }
  1234. else {
  1235. $_SESSION['return'][] = array(
  1236. 'type' => $docker_return_array['type'],
  1237. 'log' => array(__FUNCTION__, '*', '*'),
  1238. 'msg' => $docker_return_array['msg']
  1239. );
  1240. return false;
  1241. }
  1242. }
  1243. else {
  1244. $_SESSION['return'][] = array(
  1245. 'type' => 'danger',
  1246. 'log' => array(__FUNCTION__, '*', '*'),
  1247. 'msg' => 'unknown'
  1248. );
  1249. return false;
  1250. }
  1251. break;
  1252. }
  1253. }
  1254. function get_u2f_registrations($username) {
  1255. global $pdo;
  1256. $sel = $pdo->prepare("SELECT * FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = ? AND `active` = '1'");
  1257. $sel->execute(array($username));
  1258. return $sel->fetchAll(PDO::FETCH_OBJ);
  1259. }
  1260. function get_logs($application, $lines = false) {
  1261. if ($lines === false) {
  1262. $lines = $GLOBALS['LOG_LINES'] - 1;
  1263. }
  1264. elseif(is_numeric($lines) && $lines >= 1) {
  1265. $lines = abs(intval($lines) - 1);
  1266. }
  1267. else {
  1268. list ($from, $to) = explode('-', $lines);
  1269. $from = intval($from);
  1270. $to = intval($to);
  1271. if ($from < 1 || $to < $from) { return false; }
  1272. }
  1273. global $lang;
  1274. global $redis;
  1275. global $pdo;
  1276. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1277. return false;
  1278. }
  1279. // SQL
  1280. if ($application == "mailcow-ui") {
  1281. if (isset($from) && isset($to)) {
  1282. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :from, :to");
  1283. $stmt->execute(array(
  1284. ':from' => $from - 1,
  1285. ':to' => $to
  1286. ));
  1287. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1288. }
  1289. else {
  1290. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :lines");
  1291. $stmt->execute(array(
  1292. ':lines' => $lines + 1,
  1293. ));
  1294. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1295. }
  1296. if (is_array($data)) {
  1297. return $data;
  1298. }
  1299. }
  1300. // Redis
  1301. if ($application == "dovecot-mailcow") {
  1302. if (isset($from) && isset($to)) {
  1303. $data = $redis->lRange('DOVECOT_MAILLOG', $from - 1, $to - 1);
  1304. }
  1305. else {
  1306. $data = $redis->lRange('DOVECOT_MAILLOG', 0, $lines);
  1307. }
  1308. if ($data) {
  1309. foreach ($data as $json_line) {
  1310. $data_array[] = json_decode($json_line, true);
  1311. }
  1312. return $data_array;
  1313. }
  1314. }
  1315. if ($application == "postfix-mailcow") {
  1316. if (isset($from) && isset($to)) {
  1317. $data = $redis->lRange('POSTFIX_MAILLOG', $from - 1, $to - 1);
  1318. }
  1319. else {
  1320. $data = $redis->lRange('POSTFIX_MAILLOG', 0, $lines);
  1321. }
  1322. if ($data) {
  1323. foreach ($data as $json_line) {
  1324. $data_array[] = json_decode($json_line, true);
  1325. }
  1326. return $data_array;
  1327. }
  1328. }
  1329. if ($application == "sogo-mailcow") {
  1330. if (isset($from) && isset($to)) {
  1331. $data = $redis->lRange('SOGO_LOG', $from - 1, $to - 1);
  1332. }
  1333. else {
  1334. $data = $redis->lRange('SOGO_LOG', 0, $lines);
  1335. }
  1336. if ($data) {
  1337. foreach ($data as $json_line) {
  1338. $data_array[] = json_decode($json_line, true);
  1339. }
  1340. return $data_array;
  1341. }
  1342. }
  1343. if ($application == "watchdog-mailcow") {
  1344. if (isset($from) && isset($to)) {
  1345. $data = $redis->lRange('WATCHDOG_LOG', $from - 1, $to - 1);
  1346. }
  1347. else {
  1348. $data = $redis->lRange('WATCHDOG_LOG', 0, $lines);
  1349. }
  1350. if ($data) {
  1351. foreach ($data as $json_line) {
  1352. $data_array[] = json_decode($json_line, true);
  1353. }
  1354. return $data_array;
  1355. }
  1356. }
  1357. if ($application == "acme-mailcow") {
  1358. if (isset($from) && isset($to)) {
  1359. $data = $redis->lRange('ACME_LOG', $from - 1, $to - 1);
  1360. }
  1361. else {
  1362. $data = $redis->lRange('ACME_LOG', 0, $lines);
  1363. }
  1364. if ($data) {
  1365. foreach ($data as $json_line) {
  1366. $data_array[] = json_decode($json_line, true);
  1367. }
  1368. return $data_array;
  1369. }
  1370. }
  1371. if ($application == "ratelimited") {
  1372. if (isset($from) && isset($to)) {
  1373. $data = $redis->lRange('RL_LOG', $from - 1, $to - 1);
  1374. }
  1375. else {
  1376. $data = $redis->lRange('RL_LOG', 0, $lines);
  1377. }
  1378. if ($data) {
  1379. foreach ($data as $json_line) {
  1380. $data_array[] = json_decode($json_line, true);
  1381. }
  1382. return $data_array;
  1383. }
  1384. }
  1385. if ($application == "api-mailcow") {
  1386. if (isset($from) && isset($to)) {
  1387. $data = $redis->lRange('API_LOG', $from - 1, $to - 1);
  1388. }
  1389. else {
  1390. $data = $redis->lRange('API_LOG', 0, $lines);
  1391. }
  1392. if ($data) {
  1393. foreach ($data as $json_line) {
  1394. $data_array[] = json_decode($json_line, true);
  1395. }
  1396. return $data_array;
  1397. }
  1398. }
  1399. if ($application == "netfilter-mailcow") {
  1400. if (isset($from) && isset($to)) {
  1401. $data = $redis->lRange('NETFILTER_LOG', $from - 1, $to - 1);
  1402. }
  1403. else {
  1404. $data = $redis->lRange('NETFILTER_LOG', 0, $lines);
  1405. }
  1406. if ($data) {
  1407. foreach ($data as $json_line) {
  1408. $data_array[] = json_decode($json_line, true);
  1409. }
  1410. return $data_array;
  1411. }
  1412. }
  1413. if ($application == "autodiscover-mailcow") {
  1414. if (isset($from) && isset($to)) {
  1415. $data = $redis->lRange('AUTODISCOVER_LOG', $from - 1, $to - 1);
  1416. }
  1417. else {
  1418. $data = $redis->lRange('AUTODISCOVER_LOG', 0, $lines);
  1419. }
  1420. if ($data) {
  1421. foreach ($data as $json_line) {
  1422. $data_array[] = json_decode($json_line, true);
  1423. }
  1424. return $data_array;
  1425. }
  1426. }
  1427. if ($application == "rspamd-history") {
  1428. $curl = curl_init();
  1429. curl_setopt($curl, CURLOPT_UNIX_SOCKET_PATH, '/var/lib/rspamd/rspamd.sock');
  1430. if (!is_numeric($lines)) {
  1431. list ($from, $to) = explode('-', $lines);
  1432. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?from=" . intval($from) . "&to=" . intval($to));
  1433. }
  1434. else {
  1435. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?to=" . intval($lines));
  1436. }
  1437. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  1438. $history = curl_exec($curl);
  1439. if (!curl_errno($curl)) {
  1440. $data_array = json_decode($history, true);
  1441. curl_close($curl);
  1442. return $data_array['rows'];
  1443. }
  1444. curl_close($curl);
  1445. return false;
  1446. }
  1447. return false;
  1448. }
  1449. function getGUID() {
  1450. if (function_exists('com_create_guid')) {
  1451. return com_create_guid();
  1452. }
  1453. mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
  1454. $charid = strtoupper(md5(uniqid(rand(), true)));
  1455. $hyphen = chr(45);// "-"
  1456. return substr($charid, 0, 8).$hyphen
  1457. .substr($charid, 8, 4).$hyphen
  1458. .substr($charid,12, 4).$hyphen
  1459. .substr($charid,16, 4).$hyphen
  1460. .substr($charid,20,12);
  1461. }
  1462. function solr_status() {
  1463. $curl = curl_init();
  1464. $endpoint = 'http://solr:8983/solr/admin/cores';
  1465. $params = array(
  1466. 'action' => 'STATUS',
  1467. 'core' => 'dovecot',
  1468. 'indexInfo' => 'true'
  1469. );
  1470. $url = $endpoint . '?' . http_build_query($params);
  1471. curl_setopt($curl, CURLOPT_URL, $url);
  1472. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  1473. curl_setopt($curl, CURLOPT_POST, 0);
  1474. curl_setopt($curl, CURLOPT_TIMEOUT, 20);
  1475. $response = curl_exec($curl);
  1476. if ($response === false) {
  1477. $err = curl_error($curl);
  1478. curl_close($curl);
  1479. // logger(array('return' => array(
  1480. // 'type' => 'danger',
  1481. // 'log' => array(__FUNCTION__, $action, $service_name, $attr1, $attr2, $extra_headers),
  1482. // 'msg' => $err,
  1483. // )));
  1484. return false;
  1485. }
  1486. else {
  1487. curl_close($curl);
  1488. // logger(array('return' => array(
  1489. // 'type' => 'success',
  1490. // 'log' => array(__FUNCTION__, $action, $service_name, $attr1, $attr2, $extra_headers),
  1491. // )));
  1492. $status = json_decode($response, true);
  1493. return (!empty($status['status']['dovecot'])) ? $status['status']['dovecot'] : false;
  1494. }
  1495. return false;
  1496. }
  1497. ?>