functions.inc.php 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778
  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. if ($application == "rspamd-stats") {
  1669. $curl = curl_init();
  1670. curl_setopt($curl, CURLOPT_UNIX_SOCKET_PATH, '/var/lib/rspamd/rspamd.sock');
  1671. curl_setopt($curl, CURLOPT_URL,"http://rspamd/stat");
  1672. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  1673. $stats = curl_exec($curl);
  1674. if (!curl_errno($curl)) {
  1675. $data_array = json_decode($stats, true);
  1676. curl_close($curl);
  1677. return $data_array;
  1678. }
  1679. curl_close($curl);
  1680. return false;
  1681. }
  1682. return false;
  1683. }
  1684. function getGUID() {
  1685. if (function_exists('com_create_guid')) {
  1686. return com_create_guid();
  1687. }
  1688. mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
  1689. $charid = strtoupper(md5(uniqid(rand(), true)));
  1690. $hyphen = chr(45);// "-"
  1691. return substr($charid, 0, 8).$hyphen
  1692. .substr($charid, 8, 4).$hyphen
  1693. .substr($charid,12, 4).$hyphen
  1694. .substr($charid,16, 4).$hyphen
  1695. .substr($charid,20,12);
  1696. }
  1697. function solr_status() {
  1698. $curl = curl_init();
  1699. $endpoint = 'http://solr:8983/solr/admin/cores';
  1700. $params = array(
  1701. 'action' => 'STATUS',
  1702. 'core' => 'dovecot-fts',
  1703. 'indexInfo' => 'true'
  1704. );
  1705. $url = $endpoint . '?' . http_build_query($params);
  1706. curl_setopt($curl, CURLOPT_URL, $url);
  1707. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  1708. curl_setopt($curl, CURLOPT_POST, 0);
  1709. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  1710. $response_core = curl_exec($curl);
  1711. if ($response_core === false) {
  1712. $err = curl_error($curl);
  1713. curl_close($curl);
  1714. return false;
  1715. }
  1716. else {
  1717. curl_close($curl);
  1718. $curl = curl_init();
  1719. $status_core = json_decode($response_core, true);
  1720. $url = 'http://solr:8983/solr/admin/info/system';
  1721. curl_setopt($curl, CURLOPT_URL, $url);
  1722. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  1723. curl_setopt($curl, CURLOPT_POST, 0);
  1724. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  1725. $response_sysinfo = curl_exec($curl);
  1726. if ($response_sysinfo === false) {
  1727. $err = curl_error($curl);
  1728. curl_close($curl);
  1729. return false;
  1730. }
  1731. else {
  1732. curl_close($curl);
  1733. $status_sysinfo = json_decode($response_sysinfo, true);
  1734. $status = array_merge($status_core, $status_sysinfo);
  1735. return (!empty($status['status']['dovecot-fts']) && !empty($status['jvm']['memory'])) ? $status : false;
  1736. }
  1737. return (!empty($status['status']['dovecot-fts'])) ? $status['status']['dovecot-fts'] : false;
  1738. }
  1739. return false;
  1740. }
  1741. function cleanupJS($ignore = '', $folder = '/tmp/*.js') {
  1742. $now = time();
  1743. foreach (glob($folder) as $filename) {
  1744. if(strpos($filename, $ignore) !== false) {
  1745. continue;
  1746. }
  1747. if (is_file($filename)) {
  1748. if ($now - filemtime($filename) >= 60 * 60) {
  1749. unlink($filename);
  1750. }
  1751. }
  1752. }
  1753. }
  1754. function cleanupCSS($ignore = '', $folder = '/tmp/*.css') {
  1755. $now = time();
  1756. foreach (glob($folder) as $filename) {
  1757. if(strpos($filename, $ignore) !== false) {
  1758. continue;
  1759. }
  1760. if (is_file($filename)) {
  1761. if ($now - filemtime($filename) >= 60 * 60) {
  1762. unlink($filename);
  1763. }
  1764. }
  1765. }
  1766. }
  1767. ?>