functions.inc.php 66 KB

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