functions.inc.php 67 KB

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