functions.inc.php 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501
  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 `active` = '1'
  407. AND `username` = :user");
  408. $stmt->execute(array(':user' => $user));
  409. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  410. foreach ($rows as $row) {
  411. if (verify_hash($row['password'], $pass)) {
  412. if (get_tfa($user)['name'] != "none") {
  413. $_SESSION['pending_mailcow_cc_username'] = $user;
  414. $_SESSION['pending_mailcow_cc_role'] = "admin";
  415. $_SESSION['pending_tfa_method'] = get_tfa($user)['name'];
  416. unset($_SESSION['ldelay']);
  417. $_SESSION['return'][] = array(
  418. 'type' => 'info',
  419. 'log' => array(__FUNCTION__, $user, '*'),
  420. 'msg' => 'awaiting_tfa_confirmation'
  421. );
  422. return "pending";
  423. }
  424. else {
  425. unset($_SESSION['ldelay']);
  426. // Reactivate TFA if it was set to "deactivate TFA for next login"
  427. $stmt = $pdo->prepare("UPDATE `tfa` SET `active`='1' WHERE `username` = :user");
  428. $stmt->execute(array(':user' => $user));
  429. $_SESSION['return'][] = array(
  430. 'type' => 'success',
  431. 'log' => array(__FUNCTION__, $user, '*'),
  432. 'msg' => array('logged_in_as', $user)
  433. );
  434. return "admin";
  435. }
  436. }
  437. }
  438. $stmt = $pdo->prepare("SELECT `password` FROM `admin`
  439. WHERE `superadmin` = '0'
  440. AND `active`='1'
  441. AND `username` = :user");
  442. $stmt->execute(array(':user' => $user));
  443. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  444. foreach ($rows as $row) {
  445. if (verify_hash($row['password'], $pass) !== false) {
  446. if (get_tfa($user)['name'] != "none") {
  447. $_SESSION['pending_mailcow_cc_username'] = $user;
  448. $_SESSION['pending_mailcow_cc_role'] = "domainadmin";
  449. $_SESSION['pending_tfa_method'] = get_tfa($user)['name'];
  450. unset($_SESSION['ldelay']);
  451. $_SESSION['return'][] = array(
  452. 'type' => 'info',
  453. 'log' => array(__FUNCTION__, $user, '*'),
  454. 'msg' => 'awaiting_tfa_confirmation'
  455. );
  456. return "pending";
  457. }
  458. else {
  459. unset($_SESSION['ldelay']);
  460. // Reactivate TFA if it was set to "deactivate TFA for next login"
  461. $stmt = $pdo->prepare("UPDATE `tfa` SET `active`='1' WHERE `username` = :user");
  462. $stmt->execute(array(':user' => $user));
  463. $_SESSION['return'][] = array(
  464. 'type' => 'success',
  465. 'log' => array(__FUNCTION__, $user, '*'),
  466. 'msg' => array('logged_in_as', $user)
  467. );
  468. return "domainadmin";
  469. }
  470. }
  471. }
  472. $stmt = $pdo->prepare("SELECT `password` FROM `mailbox`
  473. WHERE `kind` NOT REGEXP 'location|thing|group'
  474. AND `active`='1'
  475. AND `username` = :user");
  476. $stmt->execute(array(':user' => $user));
  477. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  478. foreach ($rows as $row) {
  479. if (verify_hash($row['password'], $pass) !== false) {
  480. unset($_SESSION['ldelay']);
  481. $_SESSION['return'][] = array(
  482. 'type' => 'success',
  483. 'log' => array(__FUNCTION__, $user, '*'),
  484. 'msg' => array('logged_in_as', $user)
  485. );
  486. return "user";
  487. }
  488. }
  489. if (!isset($_SESSION['ldelay'])) {
  490. $_SESSION['ldelay'] = "0";
  491. $redis->publish("F2B_CHANNEL", "mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  492. error_log("mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  493. }
  494. elseif (!isset($_SESSION['mailcow_cc_username'])) {
  495. $_SESSION['ldelay'] = $_SESSION['ldelay']+0.5;
  496. $redis->publish("F2B_CHANNEL", "mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  497. error_log("mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  498. }
  499. $_SESSION['return'][] = array(
  500. 'type' => 'danger',
  501. 'log' => array(__FUNCTION__, $user, '*'),
  502. 'msg' => 'login_failed'
  503. );
  504. sleep($_SESSION['ldelay']);
  505. return false;
  506. }
  507. function formatBytes($size, $precision = 2) {
  508. if(!is_numeric($size)) {
  509. return "0";
  510. }
  511. $base = log($size, 1024);
  512. $suffixes = array(' Byte', ' KiB', ' MiB', ' GiB', ' TiB');
  513. if ($size == "0") {
  514. return "0";
  515. }
  516. return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
  517. }
  518. function update_sogo_static_view() {
  519. global $pdo;
  520. global $lang;
  521. $stmt = $pdo->query("SELECT 'OK' FROM INFORMATION_SCHEMA.TABLES
  522. WHERE TABLE_NAME = 'sogo_view'");
  523. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  524. if ($num_results != 0) {
  525. $stmt = $pdo->query("REPLACE INTO _sogo_static_view (`c_uid`, `domain`, `c_name`, `c_password`, `c_cn`, `mail`, `aliases`, `ad_aliases`, `kind`, `multiple_bookings`)
  526. SELECT `c_uid`, `domain`, `c_name`, `c_password`, `c_cn`, `mail`, `aliases`, `ad_aliases`, `kind`, `multiple_bookings` from sogo_view");
  527. $stmt = $pdo->query("DELETE FROM _sogo_static_view WHERE `c_uid` NOT IN (SELECT `username` FROM `mailbox` WHERE `active` = '1');");
  528. }
  529. flush_memcached();
  530. }
  531. function edit_user_account($_data) {
  532. global $lang;
  533. global $pdo;
  534. $_data_log = $_data;
  535. !isset($_data_log['user_new_pass']) ?: $_data_log['user_new_pass'] = '*';
  536. !isset($_data_log['user_new_pass2']) ?: $_data_log['user_new_pass2'] = '*';
  537. !isset($_data_log['user_old_pass']) ?: $_data_log['user_old_pass'] = '*';
  538. $username = $_SESSION['mailcow_cc_username'];
  539. $role = $_SESSION['mailcow_cc_role'];
  540. $password_old = $_data['user_old_pass'];
  541. if (filter_var($username, FILTER_VALIDATE_EMAIL === false) || $role != 'user') {
  542. $_SESSION['return'][] = array(
  543. 'type' => 'danger',
  544. 'log' => array(__FUNCTION__, $_data_log),
  545. 'msg' => 'access_denied'
  546. );
  547. return false;
  548. }
  549. if (isset($_data['user_new_pass']) && isset($_data['user_new_pass2'])) {
  550. $password_new = $_data['user_new_pass'];
  551. $password_new2 = $_data['user_new_pass2'];
  552. }
  553. $stmt = $pdo->prepare("SELECT `password` FROM `mailbox`
  554. WHERE `kind` NOT REGEXP 'location|thing|group'
  555. AND `username` = :user");
  556. $stmt->execute(array(':user' => $username));
  557. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  558. if (!verify_hash($row['password'], $password_old)) {
  559. $_SESSION['return'][] = array(
  560. 'type' => 'danger',
  561. 'log' => array(__FUNCTION__, $_data_log),
  562. 'msg' => 'access_denied'
  563. );
  564. return false;
  565. }
  566. if (isset($password_new) && isset($password_new2)) {
  567. if (!empty($password_new2) && !empty($password_new)) {
  568. if ($password_new2 != $password_new) {
  569. $_SESSION['return'][] = array(
  570. 'type' => 'danger',
  571. 'log' => array(__FUNCTION__, $_data_log),
  572. 'msg' => 'password_mismatch'
  573. );
  574. return false;
  575. }
  576. if (!preg_match('/' . $GLOBALS['PASSWD_REGEP'] . '/', $password_new)) {
  577. $_SESSION['return'][] = array(
  578. 'type' => 'danger',
  579. 'log' => array(__FUNCTION__, $_data_log),
  580. 'msg' => 'password_complexity'
  581. );
  582. return false;
  583. }
  584. $password_hashed = hash_password($password_new);
  585. try {
  586. $stmt = $pdo->prepare("UPDATE `mailbox` SET `password` = :password_hashed, `attributes` = JSON_SET(`attributes`, '$.force_pw_update', '0') WHERE `username` = :username");
  587. $stmt->execute(array(
  588. ':password_hashed' => $password_hashed,
  589. ':username' => $username
  590. ));
  591. }
  592. catch (PDOException $e) {
  593. $_SESSION['return'][] = array(
  594. 'type' => 'danger',
  595. 'log' => array(__FUNCTION__, $_data_log),
  596. 'msg' => array('mysql_error', $e)
  597. );
  598. return false;
  599. }
  600. }
  601. }
  602. update_sogo_static_view();
  603. $_SESSION['return'][] = array(
  604. 'type' => 'success',
  605. 'log' => array(__FUNCTION__, $_data_log),
  606. 'msg' => array('mailbox_modified', htmlspecialchars($username))
  607. );
  608. }
  609. function user_get_alias_details($username) {
  610. global $lang;
  611. global $pdo;
  612. $data['direct_aliases'] = false;
  613. $data['shared_aliases'] = false;
  614. if ($_SESSION['mailcow_cc_role'] == "user") {
  615. $username = $_SESSION['mailcow_cc_username'];
  616. }
  617. if (!filter_var($username, FILTER_VALIDATE_EMAIL)) {
  618. return false;
  619. }
  620. $data['address'] = $username;
  621. $stmt = $pdo->prepare("SELECT `address` AS `shared_aliases`, `public_comment` FROM `alias`
  622. WHERE `goto` REGEXP :username_goto
  623. AND `address` NOT LIKE '@%'
  624. AND `goto` != :username_goto2
  625. AND `address` != :username_address");
  626. $stmt->execute(array(
  627. ':username_goto' => '(^|,)'.$username.'($|,)',
  628. ':username_goto2' => $username,
  629. ':username_address' => $username
  630. ));
  631. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  632. while ($row = array_shift($run)) {
  633. $data['shared_aliases'][$row['shared_aliases']]['public_comment'] = htmlspecialchars($row['public_comment']);
  634. //$data['shared_aliases'][] = $row['shared_aliases'];
  635. }
  636. $stmt = $pdo->prepare("SELECT `address` AS `direct_aliases`, `public_comment` FROM `alias`
  637. WHERE `goto` = :username_goto
  638. AND `address` NOT LIKE '@%'
  639. AND `address` != :username_address");
  640. $stmt->execute(
  641. array(
  642. ':username_goto' => $username,
  643. ':username_address' => $username
  644. ));
  645. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  646. while ($row = array_shift($run)) {
  647. $data['direct_aliases'][$row['direct_aliases']]['public_comment'] = htmlspecialchars($row['public_comment']);
  648. }
  649. $stmt = $pdo->prepare("SELECT CONCAT(local_part, '@', alias_domain) AS `ad_alias`, `alias_domain` FROM `mailbox`
  650. LEFT OUTER JOIN `alias_domain` on `target_domain` = `domain`
  651. WHERE `username` = :username ;");
  652. $stmt->execute(array(':username' => $username));
  653. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  654. while ($row = array_shift($run)) {
  655. if (empty($row['ad_alias'])) {
  656. continue;
  657. }
  658. $data['direct_aliases'][$row['ad_alias']]['public_comment'] = '↪ ' . $row['alias_domain'];
  659. }
  660. $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 '@%';");
  661. $stmt->execute(array(':username' => $username));
  662. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  663. while ($row = array_shift($run)) {
  664. $data['aliases_also_send_as'] = $row['send_as'];
  665. }
  666. $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 '@%';");
  667. $stmt->execute(array(':username' => $username));
  668. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  669. while ($row = array_shift($run)) {
  670. $data['aliases_send_as_all'] = $row['send_as'];
  671. }
  672. $stmt = $pdo->prepare("SELECT IFNULL(GROUP_CONCAT(`address` SEPARATOR ', '), '&#10008;') as `address` FROM `alias` WHERE `goto` REGEXP :username AND `address` LIKE '@%';");
  673. $stmt->execute(array(':username' => '(^|,)'.$username.'($|,)'));
  674. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  675. while ($row = array_shift($run)) {
  676. $data['is_catch_all'] = $row['address'];
  677. }
  678. return $data;
  679. }
  680. function is_valid_domain_name($domain_name) {
  681. if (empty($domain_name)) {
  682. return false;
  683. }
  684. $domain_name = idn_to_ascii($domain_name, 0, INTL_IDNA_VARIANT_UTS46);
  685. return (preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $domain_name)
  686. && preg_match("/^.{1,253}$/", $domain_name)
  687. && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $domain_name));
  688. }
  689. function set_tfa($_data) {
  690. global $lang;
  691. global $pdo;
  692. global $yubi;
  693. global $u2f;
  694. global $tfa;
  695. $_data_log = $_data;
  696. !isset($_data_log['confirm_password']) ?: $_data_log['confirm_password'] = '*';
  697. $username = $_SESSION['mailcow_cc_username'];
  698. if ($_SESSION['mailcow_cc_role'] != "domainadmin" &&
  699. $_SESSION['mailcow_cc_role'] != "admin") {
  700. $_SESSION['return'][] = array(
  701. 'type' => 'danger',
  702. 'log' => array(__FUNCTION__, $_data_log),
  703. 'msg' => 'access_denied'
  704. );
  705. return false;
  706. }
  707. $stmt = $pdo->prepare("SELECT `password` FROM `admin`
  708. WHERE `username` = :user");
  709. $stmt->execute(array(':user' => $username));
  710. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  711. if (!verify_hash($row['password'], $_data["confirm_password"])) {
  712. $_SESSION['return'][] = array(
  713. 'type' => 'danger',
  714. 'log' => array(__FUNCTION__, $_data_log),
  715. 'msg' => 'access_denied'
  716. );
  717. return false;
  718. }
  719. switch ($_data["tfa_method"]) {
  720. case "yubi_otp":
  721. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  722. $yubico_id = $_data['yubico_id'];
  723. $yubico_key = $_data['yubico_key'];
  724. $yubi = new Auth_Yubico($yubico_id, $yubico_key);
  725. if (!$yubi) {
  726. $_SESSION['return'][] = array(
  727. 'type' => 'danger',
  728. 'log' => array(__FUNCTION__, $_data_log),
  729. 'msg' => 'access_denied'
  730. );
  731. return false;
  732. }
  733. if (!ctype_alnum($_data["otp_token"]) || strlen($_data["otp_token"]) != 44) {
  734. $_SESSION['return'][] = array(
  735. 'type' => 'danger',
  736. 'log' => array(__FUNCTION__, $_data_log),
  737. 'msg' => 'tfa_token_invalid'
  738. );
  739. return false;
  740. }
  741. $yauth = $yubi->verify($_data["otp_token"]);
  742. if (PEAR::isError($yauth)) {
  743. $_SESSION['return'][] = array(
  744. 'type' => 'danger',
  745. 'log' => array(__FUNCTION__, $_data_log),
  746. 'msg' => array('yotp_verification_failed', $yauth->getMessage())
  747. );
  748. return false;
  749. }
  750. try {
  751. // We could also do a modhex translation here
  752. $yubico_modhex_id = substr($_data["otp_token"], 0, 12);
  753. $stmt = $pdo->prepare("DELETE FROM `tfa`
  754. WHERE `username` = :username
  755. AND (`authmech` != 'yubi_otp')
  756. OR (`authmech` = 'yubi_otp' AND `secret` LIKE :modhex)");
  757. $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id));
  758. $stmt = $pdo->prepare("INSERT INTO `tfa` (`key_id`, `username`, `authmech`, `active`, `secret`) VALUES
  759. (:key_id, :username, 'yubi_otp', '1', :secret)");
  760. $stmt->execute(array(':key_id' => $key_id, ':username' => $username, ':secret' => $yubico_id . ':' . $yubico_key . ':' . $yubico_modhex_id));
  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. $_SESSION['return'][] = array(
  771. 'type' => 'success',
  772. 'log' => array(__FUNCTION__, $_data_log),
  773. 'msg' => array('object_modified', htmlspecialchars($username))
  774. );
  775. break;
  776. case "u2f":
  777. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  778. try {
  779. $reg = $u2f->doRegister(json_decode($_SESSION['regReq']), json_decode($_data['token']));
  780. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username AND `authmech` != 'u2f'");
  781. $stmt->execute(array(':username' => $username));
  782. $stmt = $pdo->prepare("INSERT INTO `tfa` (`username`, `key_id`, `authmech`, `keyHandle`, `publicKey`, `certificate`, `counter`, `active`) VALUES (?, ?, 'u2f', ?, ?, ?, ?, '1')");
  783. $stmt->execute(array($username, $key_id, $reg->keyHandle, $reg->publicKey, $reg->certificate, $reg->counter));
  784. $_SESSION['return'][] = array(
  785. 'type' => 'success',
  786. 'log' => array(__FUNCTION__, $_data_log),
  787. 'msg' => array('object_modified', $username)
  788. );
  789. $_SESSION['regReq'] = null;
  790. }
  791. catch (Exception $e) {
  792. $_SESSION['return'][] = array(
  793. 'type' => 'danger',
  794. 'log' => array(__FUNCTION__, $_data_log),
  795. 'msg' => array('u2f_verification_failed', $e->getMessage())
  796. );
  797. $_SESSION['regReq'] = null;
  798. return false;
  799. }
  800. break;
  801. case "totp":
  802. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  803. if ($tfa->verifyCode($_POST['totp_secret'], $_POST['totp_confirm_token']) === true) {
  804. try {
  805. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
  806. $stmt->execute(array(':username' => $username));
  807. $stmt = $pdo->prepare("INSERT INTO `tfa` (`username`, `key_id`, `authmech`, `secret`, `active`) VALUES (?, ?, 'totp', ?, '1')");
  808. $stmt->execute(array($username, $key_id, $_POST['totp_secret']));
  809. }
  810. catch (PDOException $e) {
  811. $_SESSION['return'][] = array(
  812. 'type' => 'danger',
  813. 'log' => array(__FUNCTION__, $_data_log),
  814. 'msg' => array('mysql_error', $e)
  815. );
  816. return false;
  817. }
  818. $_SESSION['return'][] = array(
  819. 'type' => 'success',
  820. 'log' => array(__FUNCTION__, $_data_log),
  821. 'msg' => array('object_modified', $username)
  822. );
  823. }
  824. else {
  825. $_SESSION['return'][] = array(
  826. 'type' => 'danger',
  827. 'log' => array(__FUNCTION__, $_data_log),
  828. 'msg' => 'totp_verification_failed'
  829. );
  830. }
  831. break;
  832. case "none":
  833. try {
  834. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
  835. $stmt->execute(array(':username' => $username));
  836. }
  837. catch (PDOException $e) {
  838. $_SESSION['return'][] = array(
  839. 'type' => 'danger',
  840. 'log' => array(__FUNCTION__, $_data_log),
  841. 'msg' => array('mysql_error', $e)
  842. );
  843. return false;
  844. }
  845. $_SESSION['return'][] = array(
  846. 'type' => 'success',
  847. 'log' => array(__FUNCTION__, $_data_log),
  848. 'msg' => array('object_modified', htmlspecialchars($username))
  849. );
  850. break;
  851. }
  852. }
  853. function unset_tfa_key($_data) {
  854. // Can only unset own keys
  855. // Needs at least one key left
  856. global $pdo;
  857. global $lang;
  858. $_data_log = $_data;
  859. $id = intval($_data['unset_tfa_key']);
  860. $username = $_SESSION['mailcow_cc_username'];
  861. if ($_SESSION['mailcow_cc_role'] != "domainadmin" &&
  862. $_SESSION['mailcow_cc_role'] != "admin") {
  863. $_SESSION['return'][] = array(
  864. 'type' => 'danger',
  865. 'log' => array(__FUNCTION__, $_data_log),
  866. 'msg' => 'access_denied'
  867. );
  868. return false;
  869. }
  870. try {
  871. if (!is_numeric($id)) {
  872. $_SESSION['return'][] = array(
  873. 'type' => 'danger',
  874. 'log' => array(__FUNCTION__, $_data_log),
  875. 'msg' => 'access_denied'
  876. );
  877. return false;
  878. }
  879. $stmt = $pdo->prepare("SELECT COUNT(*) AS `keys` FROM `tfa`
  880. WHERE `username` = :username AND `active` = '1'");
  881. $stmt->execute(array(':username' => $username));
  882. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  883. if ($row['keys'] == "1") {
  884. $_SESSION['return'][] = array(
  885. 'type' => 'danger',
  886. 'log' => array(__FUNCTION__, $_data_log),
  887. 'msg' => 'last_key'
  888. );
  889. return false;
  890. }
  891. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username AND `id` = :id");
  892. $stmt->execute(array(':username' => $username, ':id' => $id));
  893. $_SESSION['return'][] = array(
  894. 'type' => 'success',
  895. 'log' => array(__FUNCTION__, $_data_log),
  896. 'msg' => array('object_modified', $username)
  897. );
  898. }
  899. catch (PDOException $e) {
  900. $_SESSION['return'][] = array(
  901. 'type' => 'danger',
  902. 'log' => array(__FUNCTION__, $_data_log),
  903. 'msg' => array('mysql_error', $e)
  904. );
  905. return false;
  906. }
  907. }
  908. function get_tfa($username = null) {
  909. global $pdo;
  910. if (isset($_SESSION['mailcow_cc_username'])) {
  911. $username = $_SESSION['mailcow_cc_username'];
  912. }
  913. elseif (empty($username)) {
  914. return false;
  915. }
  916. $stmt = $pdo->prepare("SELECT * FROM `tfa`
  917. WHERE `username` = :username AND `active` = '1'");
  918. $stmt->execute(array(':username' => $username));
  919. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  920. switch ($row["authmech"]) {
  921. case "yubi_otp":
  922. $data['name'] = "yubi_otp";
  923. $data['pretty'] = "Yubico OTP";
  924. $stmt = $pdo->prepare("SELECT `id`, `key_id`, RIGHT(`secret`, 12) AS 'modhex' FROM `tfa` WHERE `authmech` = 'yubi_otp' AND `username` = :username");
  925. $stmt->execute(array(
  926. ':username' => $username,
  927. ));
  928. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  929. while($row = array_shift($rows)) {
  930. $data['additional'][] = $row;
  931. }
  932. return $data;
  933. break;
  934. case "u2f":
  935. $data['name'] = "u2f";
  936. $data['pretty'] = "Fido U2F";
  937. $stmt = $pdo->prepare("SELECT `id`, `key_id` FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username");
  938. $stmt->execute(array(
  939. ':username' => $username,
  940. ));
  941. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  942. while($row = array_shift($rows)) {
  943. $data['additional'][] = $row;
  944. }
  945. return $data;
  946. break;
  947. case "hotp":
  948. $data['name'] = "hotp";
  949. $data['pretty'] = "HMAC-based OTP";
  950. return $data;
  951. break;
  952. case "totp":
  953. $data['name'] = "totp";
  954. $data['pretty'] = "Time-based OTP";
  955. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `secret` FROM `tfa` WHERE `authmech` = 'totp' AND `username` = :username");
  956. $stmt->execute(array(
  957. ':username' => $username,
  958. ));
  959. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  960. while($row = array_shift($rows)) {
  961. $data['additional'][] = $row;
  962. }
  963. return $data;
  964. break;
  965. default:
  966. $data['name'] = 'none';
  967. $data['pretty'] = "-";
  968. return $data;
  969. break;
  970. }
  971. }
  972. function verify_tfa_login($username, $token) {
  973. global $pdo;
  974. global $lang;
  975. global $yubi;
  976. global $u2f;
  977. global $tfa;
  978. $stmt = $pdo->prepare("SELECT `authmech` FROM `tfa`
  979. WHERE `username` = :username AND `active` = '1'");
  980. $stmt->execute(array(':username' => $username));
  981. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  982. switch ($row["authmech"]) {
  983. case "yubi_otp":
  984. if (!ctype_alnum($token) || strlen($token) != 44) {
  985. $_SESSION['return'][] = array(
  986. 'type' => 'danger',
  987. 'log' => array(__FUNCTION__, $username, '*'),
  988. 'msg' => array('yotp_verification_failed', 'token length error')
  989. );
  990. return false;
  991. }
  992. $yubico_modhex_id = substr($token, 0, 12);
  993. $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
  994. WHERE `username` = :username
  995. AND `authmech` = 'yubi_otp'
  996. AND `active`='1'
  997. AND `secret` LIKE :modhex");
  998. $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id));
  999. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1000. $yubico_auth = explode(':', $row['secret']);
  1001. $yubi = new Auth_Yubico($yubico_auth[0], $yubico_auth[1]);
  1002. $yauth = $yubi->verify($token);
  1003. if (PEAR::isError($yauth)) {
  1004. $_SESSION['return'][] = array(
  1005. 'type' => 'danger',
  1006. 'log' => array(__FUNCTION__, $username, '*'),
  1007. 'msg' => array('yotp_verification_failed', $yauth->getMessage())
  1008. );
  1009. return false;
  1010. }
  1011. else {
  1012. $_SESSION['tfa_id'] = $row['id'];
  1013. $_SESSION['return'][] = array(
  1014. 'type' => 'success',
  1015. 'log' => array(__FUNCTION__, $username, '*'),
  1016. 'msg' => 'verified_yotp_login'
  1017. );
  1018. return true;
  1019. }
  1020. $_SESSION['return'][] = array(
  1021. 'type' => 'danger',
  1022. 'log' => array(__FUNCTION__, $username, '*'),
  1023. 'msg' => array('yotp_verification_failed', 'unknown')
  1024. );
  1025. return false;
  1026. break;
  1027. case "u2f":
  1028. try {
  1029. $reg = $u2f->doAuthenticate(json_decode($_SESSION['authReq']), get_u2f_registrations($username), json_decode($token));
  1030. $stmt = $pdo->prepare("UPDATE `tfa` SET `counter` = ? WHERE `id` = ?");
  1031. $stmt->execute(array($reg->counter, $reg->id));
  1032. $_SESSION['tfa_id'] = $reg->id;
  1033. $_SESSION['authReq'] = null;
  1034. $_SESSION['return'][] = array(
  1035. 'type' => 'success',
  1036. 'log' => array(__FUNCTION__, $username, '*'),
  1037. 'msg' => 'verified_u2f_login'
  1038. );
  1039. return true;
  1040. }
  1041. catch (Exception $e) {
  1042. $_SESSION['return'][] = array(
  1043. 'type' => 'danger',
  1044. 'log' => array(__FUNCTION__, $username, '*'),
  1045. 'msg' => array('u2f_verification_failed', $e->getMessage())
  1046. );
  1047. $_SESSION['regReq'] = null;
  1048. return false;
  1049. }
  1050. $_SESSION['return'][] = array(
  1051. 'type' => 'danger',
  1052. 'log' => array(__FUNCTION__, $username, '*'),
  1053. 'msg' => array('u2f_verification_failed', 'unknown')
  1054. );
  1055. return false;
  1056. break;
  1057. case "hotp":
  1058. return false;
  1059. break;
  1060. case "totp":
  1061. try {
  1062. $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
  1063. WHERE `username` = :username
  1064. AND `authmech` = 'totp'
  1065. AND `active`='1'");
  1066. $stmt->execute(array(':username' => $username));
  1067. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1068. if ($tfa->verifyCode($row['secret'], $_POST['token']) === true) {
  1069. $_SESSION['tfa_id'] = $row['id'];
  1070. $_SESSION['return'][] = array(
  1071. 'type' => 'success',
  1072. 'log' => array(__FUNCTION__, $username, '*'),
  1073. 'msg' => 'verified_totp_login'
  1074. );
  1075. return true;
  1076. }
  1077. $_SESSION['return'][] = array(
  1078. 'type' => 'danger',
  1079. 'log' => array(__FUNCTION__, $username, '*'),
  1080. 'msg' => 'totp_verification_failed'
  1081. );
  1082. return false;
  1083. }
  1084. catch (PDOException $e) {
  1085. $_SESSION['return'][] = array(
  1086. 'type' => 'danger',
  1087. 'log' => array(__FUNCTION__, $username, '*'),
  1088. 'msg' => array('mysql_error', $e)
  1089. );
  1090. return false;
  1091. }
  1092. break;
  1093. default:
  1094. $_SESSION['return'][] = array(
  1095. 'type' => 'danger',
  1096. 'log' => array(__FUNCTION__, $username, '*'),
  1097. 'msg' => 'unknown_tfa_method'
  1098. );
  1099. return false;
  1100. break;
  1101. }
  1102. return false;
  1103. }
  1104. function admin_api($action, $data = null) {
  1105. global $pdo;
  1106. global $lang;
  1107. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1108. $_SESSION['return'][] = array(
  1109. 'type' => 'danger',
  1110. 'log' => array(__FUNCTION__),
  1111. 'msg' => 'access_denied'
  1112. );
  1113. return false;
  1114. }
  1115. switch ($action) {
  1116. case "edit":
  1117. $regen_key = $data['admin_api_regen_key'];
  1118. $active = (isset($data['active'])) ? 1 : 0;
  1119. $allow_from = array_map('trim', preg_split( "/( |,|;|\n)/", $data['allow_from']));
  1120. foreach ($allow_from as $key => $val) {
  1121. if (!filter_var($val, FILTER_VALIDATE_IP)) {
  1122. $_SESSION['return'][] = array(
  1123. 'type' => 'warning',
  1124. 'log' => array(__FUNCTION__, $data),
  1125. 'msg' => array('ip_invalid', htmlspecialchars($allow_from[$key]))
  1126. );
  1127. unset($allow_from[$key]);
  1128. continue;
  1129. }
  1130. }
  1131. $allow_from = implode(',', array_unique(array_filter($allow_from)));
  1132. if (empty($allow_from)) {
  1133. $_SESSION['return'][] = array(
  1134. 'type' => 'danger',
  1135. 'log' => array(__FUNCTION__, $data),
  1136. 'msg' => 'ip_list_empty'
  1137. );
  1138. return false;
  1139. }
  1140. $api_key = implode('-', array(
  1141. strtoupper(bin2hex(random_bytes(3))),
  1142. strtoupper(bin2hex(random_bytes(3))),
  1143. strtoupper(bin2hex(random_bytes(3))),
  1144. strtoupper(bin2hex(random_bytes(3))),
  1145. strtoupper(bin2hex(random_bytes(3)))
  1146. ));
  1147. $stmt = $pdo->query("SELECT `api_key` FROM `api`");
  1148. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  1149. if (empty($num_results)) {
  1150. $stmt = $pdo->prepare("INSERT INTO `api` (`api_key`, `active`, `allow_from`)
  1151. VALUES (:api_key, :active, :allow_from);");
  1152. $stmt->execute(array(
  1153. ':api_key' => $api_key,
  1154. ':active' => $active,
  1155. ':allow_from' => $allow_from
  1156. ));
  1157. }
  1158. else {
  1159. $stmt = $pdo->prepare("UPDATE `api` SET `active` = :active, `allow_from` = :allow_from ;");
  1160. $stmt->execute(array(
  1161. ':active' => $active,
  1162. ':allow_from' => $allow_from
  1163. ));
  1164. }
  1165. break;
  1166. case "regen_key":
  1167. $api_key = implode('-', array(
  1168. strtoupper(bin2hex(random_bytes(3))),
  1169. strtoupper(bin2hex(random_bytes(3))),
  1170. strtoupper(bin2hex(random_bytes(3))),
  1171. strtoupper(bin2hex(random_bytes(3))),
  1172. strtoupper(bin2hex(random_bytes(3)))
  1173. ));
  1174. $stmt = $pdo->prepare("UPDATE `api` SET `api_key` = :api_key");
  1175. $stmt->execute(array(
  1176. ':api_key' => $api_key
  1177. ));
  1178. break;
  1179. case "get":
  1180. $stmt = $pdo->query("SELECT * FROM `api`");
  1181. $apidata = $stmt->fetch(PDO::FETCH_ASSOC);
  1182. return $apidata;
  1183. break;
  1184. }
  1185. $_SESSION['return'][] = array(
  1186. 'type' => 'success',
  1187. 'log' => array(__FUNCTION__, $data),
  1188. 'msg' => 'admin_api_modified'
  1189. );
  1190. }
  1191. function rspamd_ui($action, $data = null) {
  1192. global $lang;
  1193. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1194. $_SESSION['return'][] = array(
  1195. 'type' => 'danger',
  1196. 'log' => array(__FUNCTION__),
  1197. 'msg' => 'access_denied'
  1198. );
  1199. return false;
  1200. }
  1201. switch ($action) {
  1202. case "edit":
  1203. $rspamd_ui_pass = $data['rspamd_ui_pass'];
  1204. $rspamd_ui_pass2 = $data['rspamd_ui_pass2'];
  1205. if (empty($rspamd_ui_pass) || empty($rspamd_ui_pass2)) {
  1206. $_SESSION['return'][] = array(
  1207. 'type' => 'danger',
  1208. 'log' => array(__FUNCTION__, '*', '*'),
  1209. 'msg' => 'password_empty'
  1210. );
  1211. return false;
  1212. }
  1213. if ($rspamd_ui_pass != $rspamd_ui_pass2) {
  1214. $_SESSION['return'][] = array(
  1215. 'type' => 'danger',
  1216. 'log' => array(__FUNCTION__, '*', '*'),
  1217. 'msg' => 'password_mismatch'
  1218. );
  1219. return false;
  1220. }
  1221. if (strlen($rspamd_ui_pass) < 6) {
  1222. $_SESSION['return'][] = array(
  1223. 'type' => 'danger',
  1224. 'log' => array(__FUNCTION__, '*', '*'),
  1225. 'msg' => 'rspamd_ui_pw_length'
  1226. );
  1227. return false;
  1228. }
  1229. $docker_return = docker('post', 'rspamd-mailcow', 'exec', array('cmd' => 'rspamd', 'task' => 'worker_password', 'raw' => $rspamd_ui_pass), array('Content-Type: application/json'));
  1230. if ($docker_return_array = json_decode($docker_return, true)) {
  1231. if ($docker_return_array['type'] == 'success') {
  1232. $_SESSION['return'][] = array(
  1233. 'type' => 'success',
  1234. 'log' => array(__FUNCTION__, '*', '*'),
  1235. 'msg' => 'rspamd_ui_pw_set'
  1236. );
  1237. return true;
  1238. }
  1239. else {
  1240. $_SESSION['return'][] = array(
  1241. 'type' => $docker_return_array['type'],
  1242. 'log' => array(__FUNCTION__, '*', '*'),
  1243. 'msg' => $docker_return_array['msg']
  1244. );
  1245. return false;
  1246. }
  1247. }
  1248. else {
  1249. $_SESSION['return'][] = array(
  1250. 'type' => 'danger',
  1251. 'log' => array(__FUNCTION__, '*', '*'),
  1252. 'msg' => 'unknown'
  1253. );
  1254. return false;
  1255. }
  1256. break;
  1257. }
  1258. }
  1259. function get_u2f_registrations($username) {
  1260. global $pdo;
  1261. $sel = $pdo->prepare("SELECT * FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = ? AND `active` = '1'");
  1262. $sel->execute(array($username));
  1263. return $sel->fetchAll(PDO::FETCH_OBJ);
  1264. }
  1265. function get_logs($application, $lines = false) {
  1266. if ($lines === false) {
  1267. $lines = $GLOBALS['LOG_LINES'] - 1;
  1268. }
  1269. elseif(is_numeric($lines) && $lines >= 1) {
  1270. $lines = abs(intval($lines) - 1);
  1271. }
  1272. else {
  1273. list ($from, $to) = explode('-', $lines);
  1274. $from = intval($from);
  1275. $to = intval($to);
  1276. if ($from < 1 || $to < $from) { return false; }
  1277. }
  1278. global $lang;
  1279. global $redis;
  1280. global $pdo;
  1281. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1282. return false;
  1283. }
  1284. // SQL
  1285. if ($application == "mailcow-ui") {
  1286. if (isset($from) && isset($to)) {
  1287. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :from, :to");
  1288. $stmt->execute(array(
  1289. ':from' => $from - 1,
  1290. ':to' => $to
  1291. ));
  1292. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1293. }
  1294. else {
  1295. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :lines");
  1296. $stmt->execute(array(
  1297. ':lines' => $lines + 1,
  1298. ));
  1299. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1300. }
  1301. if (is_array($data)) {
  1302. return $data;
  1303. }
  1304. }
  1305. // Redis
  1306. if ($application == "dovecot-mailcow") {
  1307. if (isset($from) && isset($to)) {
  1308. $data = $redis->lRange('DOVECOT_MAILLOG', $from - 1, $to - 1);
  1309. }
  1310. else {
  1311. $data = $redis->lRange('DOVECOT_MAILLOG', 0, $lines);
  1312. }
  1313. if ($data) {
  1314. foreach ($data as $json_line) {
  1315. $data_array[] = json_decode($json_line, true);
  1316. }
  1317. return $data_array;
  1318. }
  1319. }
  1320. if ($application == "postfix-mailcow") {
  1321. if (isset($from) && isset($to)) {
  1322. $data = $redis->lRange('POSTFIX_MAILLOG', $from - 1, $to - 1);
  1323. }
  1324. else {
  1325. $data = $redis->lRange('POSTFIX_MAILLOG', 0, $lines);
  1326. }
  1327. if ($data) {
  1328. foreach ($data as $json_line) {
  1329. $data_array[] = json_decode($json_line, true);
  1330. }
  1331. return $data_array;
  1332. }
  1333. }
  1334. if ($application == "sogo-mailcow") {
  1335. if (isset($from) && isset($to)) {
  1336. $data = $redis->lRange('SOGO_LOG', $from - 1, $to - 1);
  1337. }
  1338. else {
  1339. $data = $redis->lRange('SOGO_LOG', 0, $lines);
  1340. }
  1341. if ($data) {
  1342. foreach ($data as $json_line) {
  1343. $data_array[] = json_decode($json_line, true);
  1344. }
  1345. return $data_array;
  1346. }
  1347. }
  1348. if ($application == "watchdog-mailcow") {
  1349. if (isset($from) && isset($to)) {
  1350. $data = $redis->lRange('WATCHDOG_LOG', $from - 1, $to - 1);
  1351. }
  1352. else {
  1353. $data = $redis->lRange('WATCHDOG_LOG', 0, $lines);
  1354. }
  1355. if ($data) {
  1356. foreach ($data as $json_line) {
  1357. $data_array[] = json_decode($json_line, true);
  1358. }
  1359. return $data_array;
  1360. }
  1361. }
  1362. if ($application == "acme-mailcow") {
  1363. if (isset($from) && isset($to)) {
  1364. $data = $redis->lRange('ACME_LOG', $from - 1, $to - 1);
  1365. }
  1366. else {
  1367. $data = $redis->lRange('ACME_LOG', 0, $lines);
  1368. }
  1369. if ($data) {
  1370. foreach ($data as $json_line) {
  1371. $data_array[] = json_decode($json_line, true);
  1372. }
  1373. return $data_array;
  1374. }
  1375. }
  1376. if ($application == "ratelimited") {
  1377. if (isset($from) && isset($to)) {
  1378. $data = $redis->lRange('RL_LOG', $from - 1, $to - 1);
  1379. }
  1380. else {
  1381. $data = $redis->lRange('RL_LOG', 0, $lines);
  1382. }
  1383. if ($data) {
  1384. foreach ($data as $json_line) {
  1385. $data_array[] = json_decode($json_line, true);
  1386. }
  1387. return $data_array;
  1388. }
  1389. }
  1390. if ($application == "api-mailcow") {
  1391. if (isset($from) && isset($to)) {
  1392. $data = $redis->lRange('API_LOG', $from - 1, $to - 1);
  1393. }
  1394. else {
  1395. $data = $redis->lRange('API_LOG', 0, $lines);
  1396. }
  1397. if ($data) {
  1398. foreach ($data as $json_line) {
  1399. $data_array[] = json_decode($json_line, true);
  1400. }
  1401. return $data_array;
  1402. }
  1403. }
  1404. if ($application == "netfilter-mailcow") {
  1405. if (isset($from) && isset($to)) {
  1406. $data = $redis->lRange('NETFILTER_LOG', $from - 1, $to - 1);
  1407. }
  1408. else {
  1409. $data = $redis->lRange('NETFILTER_LOG', 0, $lines);
  1410. }
  1411. if ($data) {
  1412. foreach ($data as $json_line) {
  1413. $data_array[] = json_decode($json_line, true);
  1414. }
  1415. return $data_array;
  1416. }
  1417. }
  1418. if ($application == "autodiscover-mailcow") {
  1419. if (isset($from) && isset($to)) {
  1420. $data = $redis->lRange('AUTODISCOVER_LOG', $from - 1, $to - 1);
  1421. }
  1422. else {
  1423. $data = $redis->lRange('AUTODISCOVER_LOG', 0, $lines);
  1424. }
  1425. if ($data) {
  1426. foreach ($data as $json_line) {
  1427. $data_array[] = json_decode($json_line, true);
  1428. }
  1429. return $data_array;
  1430. }
  1431. }
  1432. if ($application == "rspamd-history") {
  1433. $curl = curl_init();
  1434. curl_setopt($curl, CURLOPT_UNIX_SOCKET_PATH, '/var/lib/rspamd/rspamd.sock');
  1435. if (!is_numeric($lines)) {
  1436. list ($from, $to) = explode('-', $lines);
  1437. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?from=" . intval($from) . "&to=" . intval($to));
  1438. }
  1439. else {
  1440. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?to=" . intval($lines));
  1441. }
  1442. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  1443. $history = curl_exec($curl);
  1444. if (!curl_errno($curl)) {
  1445. $data_array = json_decode($history, true);
  1446. curl_close($curl);
  1447. return $data_array['rows'];
  1448. }
  1449. curl_close($curl);
  1450. return false;
  1451. }
  1452. return false;
  1453. }
  1454. function getGUID() {
  1455. if (function_exists('com_create_guid')) {
  1456. return com_create_guid();
  1457. }
  1458. mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
  1459. $charid = strtoupper(md5(uniqid(rand(), true)));
  1460. $hyphen = chr(45);// "-"
  1461. return substr($charid, 0, 8).$hyphen
  1462. .substr($charid, 8, 4).$hyphen
  1463. .substr($charid,12, 4).$hyphen
  1464. .substr($charid,16, 4).$hyphen
  1465. .substr($charid,20,12);
  1466. }
  1467. function solr_status() {
  1468. $curl = curl_init();
  1469. $endpoint = 'http://solr:8983/solr/admin/cores';
  1470. $params = array(
  1471. 'action' => 'STATUS',
  1472. 'core' => 'dovecot',
  1473. 'indexInfo' => 'true'
  1474. );
  1475. $url = $endpoint . '?' . http_build_query($params);
  1476. curl_setopt($curl, CURLOPT_URL, $url);
  1477. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  1478. curl_setopt($curl, CURLOPT_POST, 0);
  1479. curl_setopt($curl, CURLOPT_TIMEOUT, 20);
  1480. $response = curl_exec($curl);
  1481. if ($response === false) {
  1482. $err = curl_error($curl);
  1483. curl_close($curl);
  1484. return false;
  1485. }
  1486. else {
  1487. curl_close($curl);
  1488. $status = json_decode($response, true);
  1489. return (!empty($status['status']['dovecot'])) ? $status['status']['dovecot'] : false;
  1490. }
  1491. return false;
  1492. }
  1493. ?>