functions.inc.php 65 KB

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