2
0

functions.inc.php 67 KB

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