functions.inc.php 66 KB

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