functions.inc.php 51 KB

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