functions.inc.php 51 KB

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