functions.inc.php 59 KB

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