functions.inc.php 54 KB

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