functions.inc.php 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970
  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. {
  485. // Decode hash
  486. $dhash = base64_decode($hash);
  487. // Get first 20 bytes of binary which equals a SSHA hash
  488. $ohash = substr($dhash, 0, $salt_length);
  489. // Remove SSHA hash from decoded hash to get original salt string
  490. $osalt = str_replace($ohash, '', $dhash);
  491. // Check single salted SSHA hash against extracted hash
  492. if (hash_equals(hash($algo, $password . $osalt, true), $ohash)) {
  493. return true;
  494. }
  495. return false;
  496. }
  497. function verify_hash($hash, $password)
  498. {
  499. if (preg_match('/^{(.+)}(.+)/i', $hash, $hash_array)) {
  500. $scheme = strtoupper($hash_array[1]);
  501. $hash = $hash_array[2];
  502. switch ($scheme) {
  503. case "ARGON2I":
  504. case "ARGON2ID":
  505. case "BLF-CRYPT":
  506. case "CRYPT":
  507. case "DES-CRYPT":
  508. case "MD5-CRYPT":
  509. case "MD5":
  510. case "SHA256-CRYPT":
  511. case "SHA512-CRYPT":
  512. return password_verify($password, $hash);
  513. case "CLEAR":
  514. case "CLEARTEXT":
  515. case "PLAIN":
  516. return $password == $hash;
  517. case "LDAP-MD5":
  518. $hash = base64_decode($hash);
  519. return hash_equals(hash('md5', $password, true), $hash);
  520. case "PBKDF2":
  521. $components = explode('$', $hash);
  522. $salt = $components[2];
  523. $rounds = $components[3];
  524. $hash = $components[4];
  525. return hash_equals(hash_pbkdf2('sha1', $password, $salt, $rounds), $hash);
  526. case "PLAIN-MD4":
  527. return hash_equals(hash('md4', $password), $hash);
  528. case "PLAIN-MD5":
  529. return md5($password) == $hash;
  530. case "PLAIN-TRUNC":
  531. $components = explode('-', $hash);
  532. if (count($components) > 1) {
  533. $trunc_len = $components[0];
  534. $trunc_password = $components[1];
  535. return substr($password, 0, $trunc_len) == $trunc_password;
  536. } else {
  537. return $password == $hash;
  538. }
  539. case "SHA":
  540. case "SHA1":
  541. case "SHA256":
  542. case "SHA512":
  543. // SHA is an alias for SHA1
  544. $scheme = $scheme == "SHA" ? "sha1" : strtolower($scheme);
  545. $hash = base64_decode($hash);
  546. return hash_equals(hash($scheme, $password, true), $hash);
  547. case "SMD5":
  548. return verify_salted_hash($hash, $password, 'md5', 16);
  549. case "SSHA":
  550. return verify_salted_hash($hash, $password, 'sha1', 20);
  551. case "SSHA256":
  552. return verify_salted_hash($hash, $password, 'sha256', 32);
  553. case "SSHA512":
  554. return verify_salted_hash($hash, $password, 'sha512', 64);
  555. default:
  556. return false;
  557. }
  558. }
  559. return false;
  560. }
  561. function check_login($user, $pass) {
  562. global $pdo;
  563. global $redis;
  564. global $imap_server;
  565. if (!filter_var($user, FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $user))) {
  566. $_SESSION['return'][] = array(
  567. 'type' => 'danger',
  568. 'log' => array(__FUNCTION__, $user, '*'),
  569. 'msg' => 'malformed_username'
  570. );
  571. return false;
  572. }
  573. $user = strtolower(trim($user));
  574. $stmt = $pdo->prepare("SELECT `password` FROM `admin`
  575. WHERE `superadmin` = '1'
  576. AND `active` = '1'
  577. AND `username` = :user");
  578. $stmt->execute(array(':user' => $user));
  579. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  580. foreach ($rows as $row) {
  581. if (verify_hash($row['password'], $pass)) {
  582. if (get_tfa($user)['name'] != "none") {
  583. $_SESSION['pending_mailcow_cc_username'] = $user;
  584. $_SESSION['pending_mailcow_cc_role'] = "admin";
  585. $_SESSION['pending_tfa_method'] = get_tfa($user)['name'];
  586. unset($_SESSION['ldelay']);
  587. $_SESSION['return'][] = array(
  588. 'type' => 'info',
  589. 'log' => array(__FUNCTION__, $user, '*'),
  590. 'msg' => 'awaiting_tfa_confirmation'
  591. );
  592. return "pending";
  593. }
  594. else {
  595. unset($_SESSION['ldelay']);
  596. // Reactivate TFA if it was set to "deactivate TFA for next login"
  597. $stmt = $pdo->prepare("UPDATE `tfa` SET `active`='1' WHERE `username` = :user");
  598. $stmt->execute(array(':user' => $user));
  599. $_SESSION['return'][] = array(
  600. 'type' => 'success',
  601. 'log' => array(__FUNCTION__, $user, '*'),
  602. 'msg' => array('logged_in_as', $user)
  603. );
  604. return "admin";
  605. }
  606. }
  607. }
  608. $stmt = $pdo->prepare("SELECT `password` FROM `admin`
  609. WHERE `superadmin` = '0'
  610. AND `active`='1'
  611. AND `username` = :user");
  612. $stmt->execute(array(':user' => $user));
  613. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  614. foreach ($rows as $row) {
  615. if (verify_hash($row['password'], $pass) !== false) {
  616. if (get_tfa($user)['name'] != "none") {
  617. $_SESSION['pending_mailcow_cc_username'] = $user;
  618. $_SESSION['pending_mailcow_cc_role'] = "domainadmin";
  619. $_SESSION['pending_tfa_method'] = get_tfa($user)['name'];
  620. unset($_SESSION['ldelay']);
  621. $_SESSION['return'][] = array(
  622. 'type' => 'info',
  623. 'log' => array(__FUNCTION__, $user, '*'),
  624. 'msg' => 'awaiting_tfa_confirmation'
  625. );
  626. return "pending";
  627. }
  628. else {
  629. unset($_SESSION['ldelay']);
  630. // Reactivate TFA if it was set to "deactivate TFA for next login"
  631. $stmt = $pdo->prepare("UPDATE `tfa` SET `active`='1' WHERE `username` = :user");
  632. $stmt->execute(array(':user' => $user));
  633. $_SESSION['return'][] = array(
  634. 'type' => 'success',
  635. 'log' => array(__FUNCTION__, $user, '*'),
  636. 'msg' => array('logged_in_as', $user)
  637. );
  638. return "domainadmin";
  639. }
  640. }
  641. }
  642. $stmt = $pdo->prepare("SELECT `password` FROM `mailbox`
  643. INNER JOIN domain on mailbox.domain = domain.domain
  644. WHERE `kind` NOT REGEXP 'location|thing|group'
  645. AND `mailbox`.`active`='1'
  646. AND `domain`.`active`='1'
  647. AND `username` = :user");
  648. $stmt->execute(array(':user' => $user));
  649. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  650. foreach ($rows as $row) {
  651. if (verify_hash($row['password'], $pass) !== false) {
  652. unset($_SESSION['ldelay']);
  653. $_SESSION['return'][] = array(
  654. 'type' => 'success',
  655. 'log' => array(__FUNCTION__, $user, '*'),
  656. 'msg' => array('logged_in_as', $user)
  657. );
  658. return "user";
  659. }
  660. }
  661. if (!isset($_SESSION['ldelay'])) {
  662. $_SESSION['ldelay'] = "0";
  663. $redis->publish("F2B_CHANNEL", "mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  664. error_log("mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  665. }
  666. elseif (!isset($_SESSION['mailcow_cc_username'])) {
  667. $_SESSION['ldelay'] = $_SESSION['ldelay']+0.5;
  668. $redis->publish("F2B_CHANNEL", "mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  669. error_log("mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  670. }
  671. $_SESSION['return'][] = array(
  672. 'type' => 'danger',
  673. 'log' => array(__FUNCTION__, $user, '*'),
  674. 'msg' => 'login_failed'
  675. );
  676. sleep($_SESSION['ldelay']);
  677. return false;
  678. }
  679. function formatBytes($size, $precision = 2) {
  680. if(!is_numeric($size)) {
  681. return "0";
  682. }
  683. $base = log($size, 1024);
  684. $suffixes = array(' Byte', ' KiB', ' MiB', ' GiB', ' TiB');
  685. if ($size == "0") {
  686. return "0";
  687. }
  688. return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
  689. }
  690. function update_sogo_static_view() {
  691. if (getenv('SKIP_SOGO') == "y") {
  692. return true;
  693. }
  694. global $pdo;
  695. global $lang;
  696. $stmt = $pdo->query("SELECT 'OK' FROM INFORMATION_SCHEMA.TABLES
  697. WHERE TABLE_NAME = 'sogo_view'");
  698. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  699. if ($num_results != 0) {
  700. $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`)
  701. SELECT `c_uid`, `domain`, `c_name`, `c_password`, `c_cn`, `mail`, `aliases`, `ad_aliases`, `ext_acl`, `kind`, `multiple_bookings` from sogo_view");
  702. $stmt = $pdo->query("DELETE FROM _sogo_static_view WHERE `c_uid` NOT IN (SELECT `username` FROM `mailbox` WHERE `active` = '1');");
  703. }
  704. flush_memcached();
  705. }
  706. function edit_user_account($_data) {
  707. global $lang;
  708. global $pdo;
  709. $_data_log = $_data;
  710. !isset($_data_log['user_new_pass']) ?: $_data_log['user_new_pass'] = '*';
  711. !isset($_data_log['user_new_pass2']) ?: $_data_log['user_new_pass2'] = '*';
  712. !isset($_data_log['user_old_pass']) ?: $_data_log['user_old_pass'] = '*';
  713. $username = $_SESSION['mailcow_cc_username'];
  714. $role = $_SESSION['mailcow_cc_role'];
  715. $password_old = $_data['user_old_pass'];
  716. if (filter_var($username, FILTER_VALIDATE_EMAIL === false) || $role != 'user') {
  717. $_SESSION['return'][] = array(
  718. 'type' => 'danger',
  719. 'log' => array(__FUNCTION__, $_data_log),
  720. 'msg' => 'access_denied'
  721. );
  722. return false;
  723. }
  724. if (isset($_data['user_new_pass']) && isset($_data['user_new_pass2'])) {
  725. $password_new = $_data['user_new_pass'];
  726. $password_new2 = $_data['user_new_pass2'];
  727. }
  728. $stmt = $pdo->prepare("SELECT `password` FROM `mailbox`
  729. WHERE `kind` NOT REGEXP 'location|thing|group'
  730. AND `username` = :user");
  731. $stmt->execute(array(':user' => $username));
  732. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  733. if (!verify_hash($row['password'], $password_old)) {
  734. $_SESSION['return'][] = array(
  735. 'type' => 'danger',
  736. 'log' => array(__FUNCTION__, $_data_log),
  737. 'msg' => 'access_denied'
  738. );
  739. return false;
  740. }
  741. if (isset($password_new) && isset($password_new2)) {
  742. if (!empty($password_new2) && !empty($password_new)) {
  743. if ($password_new2 != $password_new) {
  744. $_SESSION['return'][] = array(
  745. 'type' => 'danger',
  746. 'log' => array(__FUNCTION__, $_data_log),
  747. 'msg' => 'password_mismatch'
  748. );
  749. return false;
  750. }
  751. if (!preg_match('/' . $GLOBALS['PASSWD_REGEP'] . '/', $password_new)) {
  752. $_SESSION['return'][] = array(
  753. 'type' => 'danger',
  754. 'log' => array(__FUNCTION__, $_data_log),
  755. 'msg' => 'password_complexity'
  756. );
  757. return false;
  758. }
  759. $password_hashed = hash_password($password_new);
  760. try {
  761. $stmt = $pdo->prepare("UPDATE `mailbox` SET `password` = :password_hashed, `attributes` = JSON_SET(`attributes`, '$.force_pw_update', '0') WHERE `username` = :username");
  762. $stmt->execute(array(
  763. ':password_hashed' => $password_hashed,
  764. ':username' => $username
  765. ));
  766. }
  767. catch (PDOException $e) {
  768. $_SESSION['return'][] = array(
  769. 'type' => 'danger',
  770. 'log' => array(__FUNCTION__, $_data_log),
  771. 'msg' => array('mysql_error', $e)
  772. );
  773. return false;
  774. }
  775. }
  776. }
  777. update_sogo_static_view();
  778. $_SESSION['return'][] = array(
  779. 'type' => 'success',
  780. 'log' => array(__FUNCTION__, $_data_log),
  781. 'msg' => array('mailbox_modified', htmlspecialchars($username))
  782. );
  783. }
  784. function user_get_alias_details($username) {
  785. global $pdo;
  786. $data['direct_aliases'] = false;
  787. $data['shared_aliases'] = false;
  788. if ($_SESSION['mailcow_cc_role'] == "user") {
  789. $username = $_SESSION['mailcow_cc_username'];
  790. }
  791. if (!filter_var($username, FILTER_VALIDATE_EMAIL)) {
  792. return false;
  793. }
  794. $data['address'] = $username;
  795. $stmt = $pdo->prepare("SELECT `address` AS `shared_aliases`, `public_comment` FROM `alias`
  796. WHERE `goto` REGEXP :username_goto
  797. AND `address` NOT LIKE '@%'
  798. AND `goto` != :username_goto2
  799. AND `address` != :username_address");
  800. $stmt->execute(array(
  801. ':username_goto' => '(^|,)'.$username.'($|,)',
  802. ':username_goto2' => $username,
  803. ':username_address' => $username
  804. ));
  805. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  806. while ($row = array_shift($run)) {
  807. $data['shared_aliases'][$row['shared_aliases']]['public_comment'] = htmlspecialchars($row['public_comment']);
  808. //$data['shared_aliases'][] = $row['shared_aliases'];
  809. }
  810. $stmt = $pdo->prepare("SELECT `address` AS `direct_aliases`, `public_comment` FROM `alias`
  811. WHERE `goto` = :username_goto
  812. AND `address` NOT LIKE '@%'
  813. AND `address` != :username_address");
  814. $stmt->execute(
  815. array(
  816. ':username_goto' => $username,
  817. ':username_address' => $username
  818. ));
  819. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  820. while ($row = array_shift($run)) {
  821. $data['direct_aliases'][$row['direct_aliases']]['public_comment'] = htmlspecialchars($row['public_comment']);
  822. }
  823. $stmt = $pdo->prepare("SELECT CONCAT(local_part, '@', alias_domain) AS `ad_alias`, `alias_domain` FROM `mailbox`
  824. LEFT OUTER JOIN `alias_domain` on `target_domain` = `domain`
  825. WHERE `username` = :username ;");
  826. $stmt->execute(array(':username' => $username));
  827. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  828. while ($row = array_shift($run)) {
  829. if (empty($row['ad_alias'])) {
  830. continue;
  831. }
  832. $data['direct_aliases'][$row['ad_alias']]['public_comment'] = '↪ ' . $row['alias_domain'];
  833. }
  834. $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 '@%';");
  835. $stmt->execute(array(':username' => $username));
  836. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  837. while ($row = array_shift($run)) {
  838. $data['aliases_also_send_as'] = $row['send_as'];
  839. }
  840. $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 '@%';");
  841. $stmt->execute(array(':username' => $username));
  842. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  843. while ($row = array_shift($run)) {
  844. $data['aliases_send_as_all'] = $row['send_as'];
  845. }
  846. $stmt = $pdo->prepare("SELECT IFNULL(GROUP_CONCAT(`address` SEPARATOR ', '), '&#10008;') as `address` FROM `alias` WHERE `goto` REGEXP :username AND `address` LIKE '@%';");
  847. $stmt->execute(array(':username' => '(^|,)'.$username.'($|,)'));
  848. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  849. while ($row = array_shift($run)) {
  850. $data['is_catch_all'] = $row['address'];
  851. }
  852. return $data;
  853. }
  854. function is_valid_domain_name($domain_name) {
  855. if (empty($domain_name)) {
  856. return false;
  857. }
  858. $domain_name = idn_to_ascii($domain_name, 0, INTL_IDNA_VARIANT_UTS46);
  859. return (preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $domain_name)
  860. && preg_match("/^.{1,253}$/", $domain_name)
  861. && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $domain_name));
  862. }
  863. function set_tfa($_data) {
  864. global $pdo;
  865. global $yubi;
  866. global $u2f;
  867. global $tfa;
  868. $_data_log = $_data;
  869. !isset($_data_log['confirm_password']) ?: $_data_log['confirm_password'] = '*';
  870. $username = $_SESSION['mailcow_cc_username'];
  871. if ($_SESSION['mailcow_cc_role'] != "domainadmin" &&
  872. $_SESSION['mailcow_cc_role'] != "admin") {
  873. $_SESSION['return'][] = array(
  874. 'type' => 'danger',
  875. 'log' => array(__FUNCTION__, $_data_log),
  876. 'msg' => 'access_denied'
  877. );
  878. return false;
  879. }
  880. $stmt = $pdo->prepare("SELECT `password` FROM `admin`
  881. WHERE `username` = :user");
  882. $stmt->execute(array(':user' => $username));
  883. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  884. if (!verify_hash($row['password'], $_data["confirm_password"])) {
  885. $_SESSION['return'][] = array(
  886. 'type' => 'danger',
  887. 'log' => array(__FUNCTION__, $_data_log),
  888. 'msg' => 'access_denied'
  889. );
  890. return false;
  891. }
  892. switch ($_data["tfa_method"]) {
  893. case "yubi_otp":
  894. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  895. $yubico_id = $_data['yubico_id'];
  896. $yubico_key = $_data['yubico_key'];
  897. $yubi = new Auth_Yubico($yubico_id, $yubico_key);
  898. if (!$yubi) {
  899. $_SESSION['return'][] = array(
  900. 'type' => 'danger',
  901. 'log' => array(__FUNCTION__, $_data_log),
  902. 'msg' => 'access_denied'
  903. );
  904. return false;
  905. }
  906. if (!ctype_alnum($_data["otp_token"]) || strlen($_data["otp_token"]) != 44) {
  907. $_SESSION['return'][] = array(
  908. 'type' => 'danger',
  909. 'log' => array(__FUNCTION__, $_data_log),
  910. 'msg' => 'tfa_token_invalid'
  911. );
  912. return false;
  913. }
  914. $yauth = $yubi->verify($_data["otp_token"]);
  915. if (PEAR::isError($yauth)) {
  916. $_SESSION['return'][] = array(
  917. 'type' => 'danger',
  918. 'log' => array(__FUNCTION__, $_data_log),
  919. 'msg' => array('yotp_verification_failed', $yauth->getMessage())
  920. );
  921. return false;
  922. }
  923. try {
  924. // We could also do a modhex translation here
  925. $yubico_modhex_id = substr($_data["otp_token"], 0, 12);
  926. $stmt = $pdo->prepare("DELETE FROM `tfa`
  927. WHERE `username` = :username
  928. AND (`authmech` != 'yubi_otp')
  929. OR (`authmech` = 'yubi_otp' AND `secret` LIKE :modhex)");
  930. $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id));
  931. $stmt = $pdo->prepare("INSERT INTO `tfa` (`key_id`, `username`, `authmech`, `active`, `secret`) VALUES
  932. (:key_id, :username, 'yubi_otp', '1', :secret)");
  933. $stmt->execute(array(':key_id' => $key_id, ':username' => $username, ':secret' => $yubico_id . ':' . $yubico_key . ':' . $yubico_modhex_id));
  934. }
  935. catch (PDOException $e) {
  936. $_SESSION['return'][] = array(
  937. 'type' => 'danger',
  938. 'log' => array(__FUNCTION__, $_data_log),
  939. 'msg' => array('mysql_error', $e)
  940. );
  941. return false;
  942. }
  943. $_SESSION['return'][] = array(
  944. 'type' => 'success',
  945. 'log' => array(__FUNCTION__, $_data_log),
  946. 'msg' => array('object_modified', htmlspecialchars($username))
  947. );
  948. break;
  949. case "u2f":
  950. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  951. try {
  952. $reg = $u2f->doRegister(json_decode($_SESSION['regReq']), json_decode($_data['token']));
  953. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username AND `authmech` != 'u2f'");
  954. $stmt->execute(array(':username' => $username));
  955. $stmt = $pdo->prepare("INSERT INTO `tfa` (`username`, `key_id`, `authmech`, `keyHandle`, `publicKey`, `certificate`, `counter`, `active`) VALUES (?, ?, 'u2f', ?, ?, ?, ?, '1')");
  956. $stmt->execute(array($username, $key_id, $reg->keyHandle, $reg->publicKey, $reg->certificate, $reg->counter));
  957. $_SESSION['return'][] = array(
  958. 'type' => 'success',
  959. 'log' => array(__FUNCTION__, $_data_log),
  960. 'msg' => array('object_modified', $username)
  961. );
  962. $_SESSION['regReq'] = null;
  963. }
  964. catch (Exception $e) {
  965. $_SESSION['return'][] = array(
  966. 'type' => 'danger',
  967. 'log' => array(__FUNCTION__, $_data_log),
  968. 'msg' => array('u2f_verification_failed', $e->getMessage())
  969. );
  970. $_SESSION['regReq'] = null;
  971. return false;
  972. }
  973. break;
  974. case "totp":
  975. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  976. if ($tfa->verifyCode($_POST['totp_secret'], $_POST['totp_confirm_token']) === true) {
  977. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
  978. $stmt->execute(array(':username' => $username));
  979. $stmt = $pdo->prepare("INSERT INTO `tfa` (`username`, `key_id`, `authmech`, `secret`, `active`) VALUES (?, ?, 'totp', ?, '1')");
  980. $stmt->execute(array($username, $key_id, $_POST['totp_secret']));
  981. $_SESSION['return'][] = array(
  982. 'type' => 'success',
  983. 'log' => array(__FUNCTION__, $_data_log),
  984. 'msg' => array('object_modified', $username)
  985. );
  986. }
  987. else {
  988. $_SESSION['return'][] = array(
  989. 'type' => 'danger',
  990. 'log' => array(__FUNCTION__, $_data_log),
  991. 'msg' => 'totp_verification_failed'
  992. );
  993. }
  994. break;
  995. case "none":
  996. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
  997. $stmt->execute(array(':username' => $username));
  998. $_SESSION['return'][] = array(
  999. 'type' => 'success',
  1000. 'log' => array(__FUNCTION__, $_data_log),
  1001. 'msg' => array('object_modified', htmlspecialchars($username))
  1002. );
  1003. break;
  1004. }
  1005. }
  1006. function fido2($_data) {
  1007. global $pdo;
  1008. $_data_log = $_data;
  1009. // Not logging registration data, only actions
  1010. // Silent errors for "get" requests
  1011. switch ($_data["action"]) {
  1012. case "register":
  1013. $username = $_SESSION['mailcow_cc_username'];
  1014. if ($_SESSION['mailcow_cc_role'] != "domainadmin" &&
  1015. $_SESSION['mailcow_cc_role'] != "admin") {
  1016. $_SESSION['return'][] = array(
  1017. 'type' => 'danger',
  1018. 'log' => array(__FUNCTION__, $_data["action"]),
  1019. 'msg' => 'access_denied'
  1020. );
  1021. return false;
  1022. }
  1023. $stmt = $pdo->prepare("INSERT INTO `fido2` (`username`, `rpId`, `credentialPublicKey`, `certificateChain`, `certificate`, `certificateIssuer`, `certificateSubject`, `signatureCounter`, `AAGUID`, `credentialId`)
  1024. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
  1025. $stmt->execute(array(
  1026. $username,
  1027. $_data['registration']->rpId,
  1028. $_data['registration']->credentialPublicKey,
  1029. $_data['registration']->certificateChain,
  1030. $_data['registration']->certificate,
  1031. $_data['registration']->certificateIssuer,
  1032. $_data['registration']->certificateSubject,
  1033. $_data['registration']->signatureCounter,
  1034. $_data['registration']->AAGUID,
  1035. $_data['registration']->credentialId)
  1036. );
  1037. $_SESSION['return'][] = array(
  1038. 'type' => 'success',
  1039. 'log' => array(__FUNCTION__, $_data["action"]),
  1040. 'msg' => array('object_modified', $username)
  1041. );
  1042. break;
  1043. case "get_user_cids":
  1044. // Used to exclude existing CredentialIds while registering
  1045. $username = $_SESSION['mailcow_cc_username'];
  1046. if ($_SESSION['mailcow_cc_role'] != "domainadmin" &&
  1047. $_SESSION['mailcow_cc_role'] != "admin") {
  1048. return false;
  1049. }
  1050. $stmt = $pdo->prepare("SELECT `credentialId` FROM `fido2` WHERE `username` = :username");
  1051. $stmt->execute(array(':username' => $username));
  1052. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1053. while($row = array_shift($rows)) {
  1054. $cids[] = $row['credentialId'];
  1055. }
  1056. return $cids;
  1057. break;
  1058. case "get_all_cids":
  1059. // Only needed when using fido2 with username
  1060. $stmt = $pdo->query("SELECT `credentialId` FROM `fido2`");
  1061. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1062. while($row = array_shift($rows)) {
  1063. $cids[] = $row['credentialId'];
  1064. }
  1065. return $cids;
  1066. break;
  1067. case "get_by_b64cid":
  1068. if (!isset($_data['cid']) || empty($_data['cid'])) {
  1069. return false;
  1070. }
  1071. $stmt = $pdo->prepare("SELECT `certificateSubject`, `username`, `credentialPublicKey`, SHA2(`credentialId`, 256) AS `cid` FROM `fido2` WHERE TO_BASE64(`credentialId`) = :cid");
  1072. $stmt->execute(array(':cid' => $_data['cid']));
  1073. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1074. if (empty($row) || empty($row['credentialPublicKey']) || empty($row['username'])) {
  1075. return false;
  1076. }
  1077. $data['pub_key'] = $row['credentialPublicKey'];
  1078. $data['username'] = $row['username'];
  1079. $data['subject'] = $row['certificateSubject'];
  1080. $data['cid'] = $row['cid'];
  1081. return $data;
  1082. break;
  1083. case "get_friendly_names":
  1084. $username = $_SESSION['mailcow_cc_username'];
  1085. if ($_SESSION['mailcow_cc_role'] != "domainadmin" &&
  1086. $_SESSION['mailcow_cc_role'] != "admin") {
  1087. return false;
  1088. }
  1089. $stmt = $pdo->prepare("SELECT SHA2(`credentialId`, 256) AS `cid`, `created`, `certificateSubject`, `friendlyName` FROM `fido2` WHERE `username` = :username");
  1090. $stmt->execute(array(':username' => $username));
  1091. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1092. while($row = array_shift($rows)) {
  1093. $fns[] = array(
  1094. "subject" => (empty($row['certificateSubject']) ? 'Unknown (' . $row['created'] . ')' : $row['certificateSubject']),
  1095. "fn" => $row['friendlyName'],
  1096. "cid" => $row['cid']
  1097. );
  1098. }
  1099. return $fns;
  1100. break;
  1101. case "unset_fido2_key":
  1102. $username = $_SESSION['mailcow_cc_username'];
  1103. if ($_SESSION['mailcow_cc_role'] != "domainadmin" &&
  1104. $_SESSION['mailcow_cc_role'] != "admin") {
  1105. $_SESSION['return'][] = array(
  1106. 'type' => 'danger',
  1107. 'log' => array(__FUNCTION__, $_data["action"]),
  1108. 'msg' => 'access_denied'
  1109. );
  1110. return false;
  1111. }
  1112. $stmt = $pdo->prepare("DELETE FROM `fido2` WHERE `username` = :username AND SHA2(`credentialId`, 256) = :cid");
  1113. $stmt->execute(array(
  1114. ':username' => $username,
  1115. ':cid' => $_data['post_data']['unset_fido2_key']
  1116. ));
  1117. $_SESSION['return'][] = array(
  1118. 'type' => 'success',
  1119. 'log' => array(__FUNCTION__, $_data_log),
  1120. 'msg' => array('object_modified', htmlspecialchars($username))
  1121. );
  1122. break;
  1123. case "edit_fn":
  1124. $username = $_SESSION['mailcow_cc_username'];
  1125. if ($_SESSION['mailcow_cc_role'] != "domainadmin" &&
  1126. $_SESSION['mailcow_cc_role'] != "admin") {
  1127. $_SESSION['return'][] = array(
  1128. 'type' => 'danger',
  1129. 'log' => array(__FUNCTION__, $_data["action"]),
  1130. 'msg' => 'access_denied'
  1131. );
  1132. return false;
  1133. }
  1134. $stmt = $pdo->prepare("UPDATE `fido2` SET `friendlyName` = :friendlyName WHERE SHA2(`credentialId`, 256) = :cid AND `username` = :username");
  1135. $stmt->execute(array(
  1136. ':username' => $username,
  1137. ':friendlyName' => $_data['fido2_attrs']['fido2_fn'],
  1138. ':cid' => $_data['fido2_attrs']['fido2_cid']
  1139. ));
  1140. $_SESSION['return'][] = array(
  1141. 'type' => 'success',
  1142. 'log' => array(__FUNCTION__, $_data_log),
  1143. 'msg' => array('object_modified', htmlspecialchars($username))
  1144. );
  1145. break;
  1146. }
  1147. }
  1148. function unset_tfa_key($_data) {
  1149. // Can only unset own keys
  1150. // Needs at least one key left
  1151. global $pdo;
  1152. global $lang;
  1153. $_data_log = $_data;
  1154. $id = intval($_data['unset_tfa_key']);
  1155. $username = $_SESSION['mailcow_cc_username'];
  1156. if ($_SESSION['mailcow_cc_role'] != "domainadmin" &&
  1157. $_SESSION['mailcow_cc_role'] != "admin") {
  1158. $_SESSION['return'][] = array(
  1159. 'type' => 'danger',
  1160. 'log' => array(__FUNCTION__, $_data_log),
  1161. 'msg' => 'access_denied'
  1162. );
  1163. return false;
  1164. }
  1165. try {
  1166. if (!is_numeric($id)) {
  1167. $_SESSION['return'][] = array(
  1168. 'type' => 'danger',
  1169. 'log' => array(__FUNCTION__, $_data_log),
  1170. 'msg' => 'access_denied'
  1171. );
  1172. return false;
  1173. }
  1174. $stmt = $pdo->prepare("SELECT COUNT(*) AS `keys` FROM `tfa`
  1175. WHERE `username` = :username AND `active` = '1'");
  1176. $stmt->execute(array(':username' => $username));
  1177. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1178. if ($row['keys'] == "1") {
  1179. $_SESSION['return'][] = array(
  1180. 'type' => 'danger',
  1181. 'log' => array(__FUNCTION__, $_data_log),
  1182. 'msg' => 'last_key'
  1183. );
  1184. return false;
  1185. }
  1186. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username AND `id` = :id");
  1187. $stmt->execute(array(':username' => $username, ':id' => $id));
  1188. $_SESSION['return'][] = array(
  1189. 'type' => 'success',
  1190. 'log' => array(__FUNCTION__, $_data_log),
  1191. 'msg' => array('object_modified', $username)
  1192. );
  1193. }
  1194. catch (PDOException $e) {
  1195. $_SESSION['return'][] = array(
  1196. 'type' => 'danger',
  1197. 'log' => array(__FUNCTION__, $_data_log),
  1198. 'msg' => array('mysql_error', $e)
  1199. );
  1200. return false;
  1201. }
  1202. }
  1203. function get_tfa($username = null) {
  1204. global $pdo;
  1205. if (isset($_SESSION['mailcow_cc_username'])) {
  1206. $username = $_SESSION['mailcow_cc_username'];
  1207. }
  1208. elseif (empty($username)) {
  1209. return false;
  1210. }
  1211. $stmt = $pdo->prepare("SELECT * FROM `tfa`
  1212. WHERE `username` = :username AND `active` = '1'");
  1213. $stmt->execute(array(':username' => $username));
  1214. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1215. switch ($row["authmech"]) {
  1216. case "yubi_otp":
  1217. $data['name'] = "yubi_otp";
  1218. $data['pretty'] = "Yubico OTP";
  1219. $stmt = $pdo->prepare("SELECT `id`, `key_id`, RIGHT(`secret`, 12) AS 'modhex' FROM `tfa` WHERE `authmech` = 'yubi_otp' AND `username` = :username");
  1220. $stmt->execute(array(
  1221. ':username' => $username,
  1222. ));
  1223. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1224. while($row = array_shift($rows)) {
  1225. $data['additional'][] = $row;
  1226. }
  1227. return $data;
  1228. break;
  1229. case "u2f":
  1230. $data['name'] = "u2f";
  1231. $data['pretty'] = "Fido U2F";
  1232. $stmt = $pdo->prepare("SELECT `id`, `key_id` FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username");
  1233. $stmt->execute(array(
  1234. ':username' => $username,
  1235. ));
  1236. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1237. while($row = array_shift($rows)) {
  1238. $data['additional'][] = $row;
  1239. }
  1240. return $data;
  1241. break;
  1242. case "hotp":
  1243. $data['name'] = "hotp";
  1244. $data['pretty'] = "HMAC-based OTP";
  1245. return $data;
  1246. break;
  1247. case "totp":
  1248. $data['name'] = "totp";
  1249. $data['pretty'] = "Time-based OTP";
  1250. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `secret` FROM `tfa` WHERE `authmech` = 'totp' AND `username` = :username");
  1251. $stmt->execute(array(
  1252. ':username' => $username,
  1253. ));
  1254. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1255. while($row = array_shift($rows)) {
  1256. $data['additional'][] = $row;
  1257. }
  1258. return $data;
  1259. break;
  1260. default:
  1261. $data['name'] = 'none';
  1262. $data['pretty'] = "-";
  1263. return $data;
  1264. break;
  1265. }
  1266. }
  1267. function verify_tfa_login($username, $token) {
  1268. global $pdo;
  1269. global $yubi;
  1270. global $u2f;
  1271. global $tfa;
  1272. $stmt = $pdo->prepare("SELECT `authmech` FROM `tfa`
  1273. WHERE `username` = :username AND `active` = '1'");
  1274. $stmt->execute(array(':username' => $username));
  1275. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1276. switch ($row["authmech"]) {
  1277. case "yubi_otp":
  1278. if (!ctype_alnum($token) || strlen($token) != 44) {
  1279. $_SESSION['return'][] = array(
  1280. 'type' => 'danger',
  1281. 'log' => array(__FUNCTION__, $username, '*'),
  1282. 'msg' => array('yotp_verification_failed', 'token length error')
  1283. );
  1284. return false;
  1285. }
  1286. $yubico_modhex_id = substr($token, 0, 12);
  1287. $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
  1288. WHERE `username` = :username
  1289. AND `authmech` = 'yubi_otp'
  1290. AND `active`='1'
  1291. AND `secret` LIKE :modhex");
  1292. $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id));
  1293. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1294. $yubico_auth = explode(':', $row['secret']);
  1295. $yubi = new Auth_Yubico($yubico_auth[0], $yubico_auth[1]);
  1296. $yauth = $yubi->verify($token);
  1297. if (PEAR::isError($yauth)) {
  1298. $_SESSION['return'][] = array(
  1299. 'type' => 'danger',
  1300. 'log' => array(__FUNCTION__, $username, '*'),
  1301. 'msg' => array('yotp_verification_failed', $yauth->getMessage())
  1302. );
  1303. return false;
  1304. }
  1305. else {
  1306. $_SESSION['tfa_id'] = $row['id'];
  1307. $_SESSION['return'][] = array(
  1308. 'type' => 'success',
  1309. 'log' => array(__FUNCTION__, $username, '*'),
  1310. 'msg' => 'verified_yotp_login'
  1311. );
  1312. return true;
  1313. }
  1314. $_SESSION['return'][] = array(
  1315. 'type' => 'danger',
  1316. 'log' => array(__FUNCTION__, $username, '*'),
  1317. 'msg' => array('yotp_verification_failed', 'unknown')
  1318. );
  1319. return false;
  1320. break;
  1321. case "u2f":
  1322. try {
  1323. $reg = $u2f->doAuthenticate(json_decode($_SESSION['authReq']), get_u2f_registrations($username), json_decode($token));
  1324. $stmt = $pdo->prepare("SELECT `id` FROM `tfa` WHERE `keyHandle` = ?");
  1325. $stmt->execute(array($reg->keyHandle));
  1326. $row_key_id = $stmt->fetch(PDO::FETCH_ASSOC);
  1327. $_SESSION['tfa_id'] = $row_key_id['id'];
  1328. $_SESSION['authReq'] = null;
  1329. $_SESSION['return'][] = array(
  1330. 'type' => 'success',
  1331. 'log' => array(__FUNCTION__, $username, '*'),
  1332. 'msg' => 'verified_u2f_login'
  1333. );
  1334. return true;
  1335. }
  1336. catch (Exception $e) {
  1337. $_SESSION['return'][] = array(
  1338. 'type' => 'danger',
  1339. 'log' => array(__FUNCTION__, $username, '*'),
  1340. 'msg' => array('u2f_verification_failed', $e->getMessage())
  1341. );
  1342. $_SESSION['regReq'] = null;
  1343. return false;
  1344. }
  1345. $_SESSION['return'][] = array(
  1346. 'type' => 'danger',
  1347. 'log' => array(__FUNCTION__, $username, '*'),
  1348. 'msg' => array('u2f_verification_failed', 'unknown')
  1349. );
  1350. return false;
  1351. break;
  1352. case "hotp":
  1353. return false;
  1354. break;
  1355. case "totp":
  1356. try {
  1357. $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
  1358. WHERE `username` = :username
  1359. AND `authmech` = 'totp'
  1360. AND `active`='1'");
  1361. $stmt->execute(array(':username' => $username));
  1362. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1363. if ($tfa->verifyCode($row['secret'], $_POST['token']) === true) {
  1364. $_SESSION['tfa_id'] = $row['id'];
  1365. $_SESSION['return'][] = array(
  1366. 'type' => 'success',
  1367. 'log' => array(__FUNCTION__, $username, '*'),
  1368. 'msg' => 'verified_totp_login'
  1369. );
  1370. return true;
  1371. }
  1372. $_SESSION['return'][] = array(
  1373. 'type' => 'danger',
  1374. 'log' => array(__FUNCTION__, $username, '*'),
  1375. 'msg' => 'totp_verification_failed'
  1376. );
  1377. return false;
  1378. }
  1379. catch (PDOException $e) {
  1380. $_SESSION['return'][] = array(
  1381. 'type' => 'danger',
  1382. 'log' => array(__FUNCTION__, $username, '*'),
  1383. 'msg' => array('mysql_error', $e)
  1384. );
  1385. return false;
  1386. }
  1387. break;
  1388. default:
  1389. $_SESSION['return'][] = array(
  1390. 'type' => 'danger',
  1391. 'log' => array(__FUNCTION__, $username, '*'),
  1392. 'msg' => 'unknown_tfa_method'
  1393. );
  1394. return false;
  1395. break;
  1396. }
  1397. return false;
  1398. }
  1399. function admin_api($access, $action, $data = null) {
  1400. global $pdo;
  1401. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1402. $_SESSION['return'][] = array(
  1403. 'type' => 'danger',
  1404. 'log' => array(__FUNCTION__),
  1405. 'msg' => 'access_denied'
  1406. );
  1407. return false;
  1408. }
  1409. if ($access !== "ro" && $access !== "rw") {
  1410. $_SESSION['return'][] = array(
  1411. 'type' => 'danger',
  1412. 'log' => array(__FUNCTION__),
  1413. 'msg' => 'invalid access type'
  1414. );
  1415. return false;
  1416. }
  1417. if ($action == "edit") {
  1418. $active = (!empty($data['active'])) ? 1 : 0;
  1419. $skip_ip_check = (isset($data['skip_ip_check'])) ? 1 : 0;
  1420. $allow_from = array_map('trim', preg_split( "/( |,|;|\n)/", $data['allow_from']));
  1421. foreach ($allow_from as $key => $val) {
  1422. if (empty($val)) {
  1423. unset($allow_from[$key]);
  1424. continue;
  1425. }
  1426. if (valid_network($val) !== true) {
  1427. $_SESSION['return'][] = array(
  1428. 'type' => 'warning',
  1429. 'log' => array(__FUNCTION__, $data),
  1430. 'msg' => array('ip_invalid', htmlspecialchars($allow_from[$key]))
  1431. );
  1432. unset($allow_from[$key]);
  1433. continue;
  1434. }
  1435. }
  1436. $allow_from = implode(',', array_unique(array_filter($allow_from)));
  1437. if (empty($allow_from) && $skip_ip_check == 0) {
  1438. $_SESSION['return'][] = array(
  1439. 'type' => 'danger',
  1440. 'log' => array(__FUNCTION__, $data),
  1441. 'msg' => 'ip_list_empty'
  1442. );
  1443. return false;
  1444. }
  1445. $api_key = implode('-', array(
  1446. strtoupper(bin2hex(random_bytes(3))),
  1447. strtoupper(bin2hex(random_bytes(3))),
  1448. strtoupper(bin2hex(random_bytes(3))),
  1449. strtoupper(bin2hex(random_bytes(3))),
  1450. strtoupper(bin2hex(random_bytes(3)))
  1451. ));
  1452. $stmt = $pdo->query("SELECT `api_key` FROM `api` WHERE `access` = '" . $access . "'");
  1453. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  1454. if (empty($num_results)) {
  1455. $stmt = $pdo->prepare("INSERT INTO `api` (`api_key`, `skip_ip_check`, `active`, `allow_from`, `access`)
  1456. VALUES (:api_key, :skip_ip_check, :active, :allow_from, :access);");
  1457. $stmt->execute(array(
  1458. ':api_key' => $api_key,
  1459. ':skip_ip_check' => $skip_ip_check,
  1460. ':active' => $active,
  1461. ':allow_from' => $allow_from,
  1462. ':access' => $access
  1463. ));
  1464. }
  1465. else {
  1466. if ($skip_ip_check == 0) {
  1467. $stmt = $pdo->prepare("UPDATE `api` SET `skip_ip_check` = :skip_ip_check,
  1468. `active` = :active,
  1469. `allow_from` = :allow_from
  1470. WHERE `access` = :access;");
  1471. $stmt->execute(array(
  1472. ':active' => $active,
  1473. ':skip_ip_check' => $skip_ip_check,
  1474. ':allow_from' => $allow_from,
  1475. ':access' => $access
  1476. ));
  1477. }
  1478. else {
  1479. $stmt = $pdo->prepare("UPDATE `api` SET `skip_ip_check` = :skip_ip_check,
  1480. `active` = :active
  1481. WHERE `access` = :access;");
  1482. $stmt->execute(array(
  1483. ':active' => $active,
  1484. ':skip_ip_check' => $skip_ip_check,
  1485. ':access' => $access
  1486. ));
  1487. }
  1488. }
  1489. }
  1490. elseif ($action == "regen_key") {
  1491. $api_key = implode('-', array(
  1492. strtoupper(bin2hex(random_bytes(3))),
  1493. strtoupper(bin2hex(random_bytes(3))),
  1494. strtoupper(bin2hex(random_bytes(3))),
  1495. strtoupper(bin2hex(random_bytes(3))),
  1496. strtoupper(bin2hex(random_bytes(3)))
  1497. ));
  1498. $stmt = $pdo->prepare("UPDATE `api` SET `api_key` = :api_key WHERE `access` = :access");
  1499. $stmt->execute(array(
  1500. ':api_key' => $api_key,
  1501. ':access' => $access
  1502. ));
  1503. }
  1504. elseif ($action == "get") {
  1505. $stmt = $pdo->query("SELECT * FROM `api` WHERE `access` = '" . $access . "'");
  1506. $apidata = $stmt->fetch(PDO::FETCH_ASSOC);
  1507. $apidata['allow_from'] = str_replace(',', PHP_EOL, $apidata['allow_from']);
  1508. return $apidata;
  1509. }
  1510. $_SESSION['return'][] = array(
  1511. 'type' => 'success',
  1512. 'log' => array(__FUNCTION__, $data),
  1513. 'msg' => 'admin_api_modified'
  1514. );
  1515. }
  1516. function license($action, $data = null) {
  1517. global $pdo;
  1518. global $redis;
  1519. global $lang;
  1520. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1521. $_SESSION['return'][] = array(
  1522. 'type' => 'danger',
  1523. 'log' => array(__FUNCTION__),
  1524. 'msg' => 'access_denied'
  1525. );
  1526. return false;
  1527. }
  1528. switch ($action) {
  1529. case "verify":
  1530. // Keep result until revalidate button is pressed or session expired
  1531. $stmt = $pdo->query("SELECT `version` FROM `versions` WHERE `application` = 'GUID'");
  1532. $versions = $stmt->fetch(PDO::FETCH_ASSOC);
  1533. $post = array('guid' => $versions['version']);
  1534. $curl = curl_init('https://verify.mailcow.email');
  1535. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  1536. curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
  1537. curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
  1538. $response = curl_exec($curl);
  1539. curl_close($curl);
  1540. $json_return = json_decode($response, true);
  1541. if ($response && $json_return) {
  1542. if ($json_return['response'] === "ok") {
  1543. $_SESSION['gal']['valid'] = "true";
  1544. $_SESSION['gal']['c'] = $json_return['c'];
  1545. $_SESSION['gal']['s'] = $json_return['s'];
  1546. if ($json_return['m'] == 'NoMoore') {
  1547. $_SESSION['gal']['m'] = '🐄';
  1548. }
  1549. else {
  1550. $_SESSION['gal']['m'] = str_repeat('🐄', substr_count($json_return['m'], 'o'));
  1551. }
  1552. }
  1553. elseif ($json_return['response'] === "invalid") {
  1554. $_SESSION['gal']['valid'] = "false";
  1555. $_SESSION['gal']['c'] = $lang['mailbox']['no'];
  1556. $_SESSION['gal']['s'] = $lang['mailbox']['no'];
  1557. $_SESSION['gal']['m'] = $lang['mailbox']['no'];
  1558. }
  1559. }
  1560. else {
  1561. $_SESSION['gal']['valid'] = "false";
  1562. $_SESSION['gal']['c'] = $lang['danger']['temp_error'];
  1563. $_SESSION['gal']['s'] = $lang['danger']['temp_error'];
  1564. $_SESSION['gal']['m'] = $lang['danger']['temp_error'];
  1565. }
  1566. try {
  1567. // json_encode needs "true"/"false" instead of true/false, to not encode it to 0 or 1
  1568. $redis->Set('LICENSE_STATUS_CACHE', json_encode($_SESSION['gal']));
  1569. }
  1570. catch (RedisException $e) {
  1571. $_SESSION['return'][] = array(
  1572. 'type' => 'danger',
  1573. 'log' => array(__FUNCTION__, $_action, $_data_log),
  1574. 'msg' => array('redis_error', $e)
  1575. );
  1576. return false;
  1577. }
  1578. return $_SESSION['gal']['valid'];
  1579. break;
  1580. case "guid":
  1581. $stmt = $pdo->query("SELECT `version` FROM `versions` WHERE `application` = 'GUID'");
  1582. $versions = $stmt->fetch(PDO::FETCH_ASSOC);
  1583. return $versions['version'];
  1584. break;
  1585. }
  1586. }
  1587. function rspamd_ui($action, $data = null) {
  1588. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1589. $_SESSION['return'][] = array(
  1590. 'type' => 'danger',
  1591. 'log' => array(__FUNCTION__),
  1592. 'msg' => 'access_denied'
  1593. );
  1594. return false;
  1595. }
  1596. switch ($action) {
  1597. case "edit":
  1598. $rspamd_ui_pass = $data['rspamd_ui_pass'];
  1599. $rspamd_ui_pass2 = $data['rspamd_ui_pass2'];
  1600. if (empty($rspamd_ui_pass) || empty($rspamd_ui_pass2)) {
  1601. $_SESSION['return'][] = array(
  1602. 'type' => 'danger',
  1603. 'log' => array(__FUNCTION__, '*', '*'),
  1604. 'msg' => 'password_empty'
  1605. );
  1606. return false;
  1607. }
  1608. if ($rspamd_ui_pass != $rspamd_ui_pass2) {
  1609. $_SESSION['return'][] = array(
  1610. 'type' => 'danger',
  1611. 'log' => array(__FUNCTION__, '*', '*'),
  1612. 'msg' => 'password_mismatch'
  1613. );
  1614. return false;
  1615. }
  1616. if (strlen($rspamd_ui_pass) < 6) {
  1617. $_SESSION['return'][] = array(
  1618. 'type' => 'danger',
  1619. 'log' => array(__FUNCTION__, '*', '*'),
  1620. 'msg' => 'rspamd_ui_pw_length'
  1621. );
  1622. return false;
  1623. }
  1624. $docker_return = docker('post', 'rspamd-mailcow', 'exec', array('cmd' => 'rspamd', 'task' => 'worker_password', 'raw' => $rspamd_ui_pass), array('Content-Type: application/json'));
  1625. if ($docker_return_array = json_decode($docker_return, true)) {
  1626. if ($docker_return_array['type'] == 'success') {
  1627. $_SESSION['return'][] = array(
  1628. 'type' => 'success',
  1629. 'log' => array(__FUNCTION__, '*', '*'),
  1630. 'msg' => 'rspamd_ui_pw_set'
  1631. );
  1632. return true;
  1633. }
  1634. else {
  1635. $_SESSION['return'][] = array(
  1636. 'type' => $docker_return_array['type'],
  1637. 'log' => array(__FUNCTION__, '*', '*'),
  1638. 'msg' => $docker_return_array['msg']
  1639. );
  1640. return false;
  1641. }
  1642. }
  1643. else {
  1644. $_SESSION['return'][] = array(
  1645. 'type' => 'danger',
  1646. 'log' => array(__FUNCTION__, '*', '*'),
  1647. 'msg' => 'unknown'
  1648. );
  1649. return false;
  1650. }
  1651. break;
  1652. }
  1653. }
  1654. function get_u2f_registrations($username) {
  1655. global $pdo;
  1656. $sel = $pdo->prepare("SELECT * FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = ? AND `active` = '1'");
  1657. $sel->execute(array($username));
  1658. return $sel->fetchAll(PDO::FETCH_OBJ);
  1659. }
  1660. function get_logs($application, $lines = false) {
  1661. if ($lines === false) {
  1662. $lines = $GLOBALS['LOG_LINES'] - 1;
  1663. }
  1664. elseif(is_numeric($lines) && $lines >= 1) {
  1665. $lines = abs(intval($lines) - 1);
  1666. }
  1667. else {
  1668. list ($from, $to) = explode('-', $lines);
  1669. $from = intval($from);
  1670. $to = intval($to);
  1671. if ($from < 1 || $to < $from) { return false; }
  1672. }
  1673. global $redis;
  1674. global $pdo;
  1675. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1676. return false;
  1677. }
  1678. // SQL
  1679. if ($application == "mailcow-ui") {
  1680. if (isset($from) && isset($to)) {
  1681. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :from, :to");
  1682. $stmt->execute(array(
  1683. ':from' => $from - 1,
  1684. ':to' => $to
  1685. ));
  1686. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1687. }
  1688. else {
  1689. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :lines");
  1690. $stmt->execute(array(
  1691. ':lines' => $lines + 1,
  1692. ));
  1693. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1694. }
  1695. if (is_array($data)) {
  1696. return $data;
  1697. }
  1698. }
  1699. // Redis
  1700. if ($application == "dovecot-mailcow") {
  1701. if (isset($from) && isset($to)) {
  1702. $data = $redis->lRange('DOVECOT_MAILLOG', $from - 1, $to - 1);
  1703. }
  1704. else {
  1705. $data = $redis->lRange('DOVECOT_MAILLOG', 0, $lines);
  1706. }
  1707. if ($data) {
  1708. foreach ($data as $json_line) {
  1709. $data_array[] = json_decode($json_line, true);
  1710. }
  1711. return $data_array;
  1712. }
  1713. }
  1714. if ($application == "postfix-mailcow") {
  1715. if (isset($from) && isset($to)) {
  1716. $data = $redis->lRange('POSTFIX_MAILLOG', $from - 1, $to - 1);
  1717. }
  1718. else {
  1719. $data = $redis->lRange('POSTFIX_MAILLOG', 0, $lines);
  1720. }
  1721. if ($data) {
  1722. foreach ($data as $json_line) {
  1723. $data_array[] = json_decode($json_line, true);
  1724. }
  1725. return $data_array;
  1726. }
  1727. }
  1728. if ($application == "sogo-mailcow") {
  1729. if (isset($from) && isset($to)) {
  1730. $data = $redis->lRange('SOGO_LOG', $from - 1, $to - 1);
  1731. }
  1732. else {
  1733. $data = $redis->lRange('SOGO_LOG', 0, $lines);
  1734. }
  1735. if ($data) {
  1736. foreach ($data as $json_line) {
  1737. $data_array[] = json_decode($json_line, true);
  1738. }
  1739. return $data_array;
  1740. }
  1741. }
  1742. if ($application == "watchdog-mailcow") {
  1743. if (isset($from) && isset($to)) {
  1744. $data = $redis->lRange('WATCHDOG_LOG', $from - 1, $to - 1);
  1745. }
  1746. else {
  1747. $data = $redis->lRange('WATCHDOG_LOG', 0, $lines);
  1748. }
  1749. if ($data) {
  1750. foreach ($data as $json_line) {
  1751. $data_array[] = json_decode($json_line, true);
  1752. }
  1753. return $data_array;
  1754. }
  1755. }
  1756. if ($application == "acme-mailcow") {
  1757. if (isset($from) && isset($to)) {
  1758. $data = $redis->lRange('ACME_LOG', $from - 1, $to - 1);
  1759. }
  1760. else {
  1761. $data = $redis->lRange('ACME_LOG', 0, $lines);
  1762. }
  1763. if ($data) {
  1764. foreach ($data as $json_line) {
  1765. $data_array[] = json_decode($json_line, true);
  1766. }
  1767. return $data_array;
  1768. }
  1769. }
  1770. if ($application == "ratelimited") {
  1771. if (isset($from) && isset($to)) {
  1772. $data = $redis->lRange('RL_LOG', $from - 1, $to - 1);
  1773. }
  1774. else {
  1775. $data = $redis->lRange('RL_LOG', 0, $lines);
  1776. }
  1777. if ($data) {
  1778. foreach ($data as $json_line) {
  1779. $data_array[] = json_decode($json_line, true);
  1780. }
  1781. return $data_array;
  1782. }
  1783. }
  1784. if ($application == "api-mailcow") {
  1785. if (isset($from) && isset($to)) {
  1786. $data = $redis->lRange('API_LOG', $from - 1, $to - 1);
  1787. }
  1788. else {
  1789. $data = $redis->lRange('API_LOG', 0, $lines);
  1790. }
  1791. if ($data) {
  1792. foreach ($data as $json_line) {
  1793. $data_array[] = json_decode($json_line, true);
  1794. }
  1795. return $data_array;
  1796. }
  1797. }
  1798. if ($application == "netfilter-mailcow") {
  1799. if (isset($from) && isset($to)) {
  1800. $data = $redis->lRange('NETFILTER_LOG', $from - 1, $to - 1);
  1801. }
  1802. else {
  1803. $data = $redis->lRange('NETFILTER_LOG', 0, $lines);
  1804. }
  1805. if ($data) {
  1806. foreach ($data as $json_line) {
  1807. $data_array[] = json_decode($json_line, true);
  1808. }
  1809. return $data_array;
  1810. }
  1811. }
  1812. if ($application == "autodiscover-mailcow") {
  1813. if (isset($from) && isset($to)) {
  1814. $data = $redis->lRange('AUTODISCOVER_LOG', $from - 1, $to - 1);
  1815. }
  1816. else {
  1817. $data = $redis->lRange('AUTODISCOVER_LOG', 0, $lines);
  1818. }
  1819. if ($data) {
  1820. foreach ($data as $json_line) {
  1821. $data_array[] = json_decode($json_line, true);
  1822. }
  1823. return $data_array;
  1824. }
  1825. }
  1826. if ($application == "rspamd-history") {
  1827. $curl = curl_init();
  1828. curl_setopt($curl, CURLOPT_UNIX_SOCKET_PATH, '/var/lib/rspamd/rspamd.sock');
  1829. if (!is_numeric($lines)) {
  1830. list ($from, $to) = explode('-', $lines);
  1831. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?from=" . intval($from) . "&to=" . intval($to));
  1832. }
  1833. else {
  1834. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?to=" . intval($lines));
  1835. }
  1836. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  1837. $history = curl_exec($curl);
  1838. if (!curl_errno($curl)) {
  1839. $data_array = json_decode($history, true);
  1840. curl_close($curl);
  1841. return $data_array['rows'];
  1842. }
  1843. curl_close($curl);
  1844. return false;
  1845. }
  1846. if ($application == "rspamd-stats") {
  1847. $curl = curl_init();
  1848. curl_setopt($curl, CURLOPT_UNIX_SOCKET_PATH, '/var/lib/rspamd/rspamd.sock');
  1849. curl_setopt($curl, CURLOPT_URL,"http://rspamd/stat");
  1850. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  1851. $stats = curl_exec($curl);
  1852. if (!curl_errno($curl)) {
  1853. $data_array = json_decode($stats, true);
  1854. curl_close($curl);
  1855. return $data_array;
  1856. }
  1857. curl_close($curl);
  1858. return false;
  1859. }
  1860. return false;
  1861. }
  1862. function getGUID() {
  1863. if (function_exists('com_create_guid')) {
  1864. return com_create_guid();
  1865. }
  1866. mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
  1867. $charid = strtoupper(md5(uniqid(rand(), true)));
  1868. $hyphen = chr(45);// "-"
  1869. return substr($charid, 0, 8).$hyphen
  1870. .substr($charid, 8, 4).$hyphen
  1871. .substr($charid,12, 4).$hyphen
  1872. .substr($charid,16, 4).$hyphen
  1873. .substr($charid,20,12);
  1874. }
  1875. function solr_status() {
  1876. $curl = curl_init();
  1877. $endpoint = 'http://solr:8983/solr/admin/cores';
  1878. $params = array(
  1879. 'action' => 'STATUS',
  1880. 'core' => 'dovecot-fts',
  1881. 'indexInfo' => 'true'
  1882. );
  1883. $url = $endpoint . '?' . http_build_query($params);
  1884. curl_setopt($curl, CURLOPT_URL, $url);
  1885. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  1886. curl_setopt($curl, CURLOPT_POST, 0);
  1887. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  1888. $response_core = curl_exec($curl);
  1889. if ($response_core === false) {
  1890. $err = curl_error($curl);
  1891. curl_close($curl);
  1892. return false;
  1893. }
  1894. else {
  1895. curl_close($curl);
  1896. $curl = curl_init();
  1897. $status_core = json_decode($response_core, true);
  1898. $url = 'http://solr:8983/solr/admin/info/system';
  1899. curl_setopt($curl, CURLOPT_URL, $url);
  1900. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  1901. curl_setopt($curl, CURLOPT_POST, 0);
  1902. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  1903. $response_sysinfo = curl_exec($curl);
  1904. if ($response_sysinfo === false) {
  1905. $err = curl_error($curl);
  1906. curl_close($curl);
  1907. return false;
  1908. }
  1909. else {
  1910. curl_close($curl);
  1911. $status_sysinfo = json_decode($response_sysinfo, true);
  1912. $status = array_merge($status_core, $status_sysinfo);
  1913. return (!empty($status['status']['dovecot-fts']) && !empty($status['jvm']['memory'])) ? $status : false;
  1914. }
  1915. return (!empty($status['status']['dovecot-fts'])) ? $status['status']['dovecot-fts'] : false;
  1916. }
  1917. return false;
  1918. }
  1919. function cleanupJS($ignore = '', $folder = '/tmp/*.js') {
  1920. $now = time();
  1921. foreach (glob($folder) as $filename) {
  1922. if(strpos($filename, $ignore) !== false) {
  1923. continue;
  1924. }
  1925. if (is_file($filename)) {
  1926. if ($now - filemtime($filename) >= 60 * 60) {
  1927. unlink($filename);
  1928. }
  1929. }
  1930. }
  1931. }
  1932. function cleanupCSS($ignore = '', $folder = '/tmp/*.css') {
  1933. $now = time();
  1934. foreach (glob($folder) as $filename) {
  1935. if(strpos($filename, $ignore) !== false) {
  1936. continue;
  1937. }
  1938. if (is_file($filename)) {
  1939. if ($now - filemtime($filename) >= 60 * 60) {
  1940. unlink($filename);
  1941. }
  1942. }
  1943. }
  1944. }
  1945. ?>