functions.inc.php 78 KB

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