functions.inc.php 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278
  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, $app_passwd_data = false) {
  788. global $pdo;
  789. global $redis;
  790. global $imap_server;
  791. if ($app_passwd_data === false) {
  792. $app_passwd_data['eas'] = false;
  793. $app_passwd_data['dav'] = false;
  794. $app_passwd_data['proxyauth'] = false;
  795. }
  796. if (!filter_var($user, FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $user))) {
  797. $_SESSION['return'][] = array(
  798. 'type' => 'danger',
  799. 'log' => array(__FUNCTION__, $user, '*'),
  800. 'msg' => 'malformed_username'
  801. );
  802. return false;
  803. }
  804. // Validate admin
  805. $user = strtolower(trim($user));
  806. $stmt = $pdo->prepare("SELECT `password` FROM `admin`
  807. WHERE `superadmin` = '1'
  808. AND `active` = '1'
  809. AND `username` = :user");
  810. $stmt->execute(array(':user' => $user));
  811. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  812. foreach ($rows as $row) {
  813. if (verify_hash($row['password'], $pass)) {
  814. if (get_tfa($user)['name'] != "none") {
  815. $_SESSION['pending_mailcow_cc_username'] = $user;
  816. $_SESSION['pending_mailcow_cc_role'] = "admin";
  817. $_SESSION['pending_tfa_method'] = get_tfa($user)['name'];
  818. unset($_SESSION['ldelay']);
  819. $_SESSION['return'][] = array(
  820. 'type' => 'info',
  821. 'log' => array(__FUNCTION__, $user, '*'),
  822. 'msg' => 'awaiting_tfa_confirmation'
  823. );
  824. return "pending";
  825. }
  826. else {
  827. unset($_SESSION['ldelay']);
  828. // Reactivate TFA if it was set to "deactivate TFA for next login"
  829. $stmt = $pdo->prepare("UPDATE `tfa` SET `active`='1' WHERE `username` = :user");
  830. $stmt->execute(array(':user' => $user));
  831. $_SESSION['return'][] = array(
  832. 'type' => 'success',
  833. 'log' => array(__FUNCTION__, $user, '*'),
  834. 'msg' => array('logged_in_as', $user)
  835. );
  836. return "admin";
  837. }
  838. }
  839. }
  840. // Validate domain admin
  841. $stmt = $pdo->prepare("SELECT `password` FROM `admin`
  842. WHERE `superadmin` = '0'
  843. AND `active`='1'
  844. AND `username` = :user");
  845. $stmt->execute(array(':user' => $user));
  846. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  847. foreach ($rows as $row) {
  848. if (verify_hash($row['password'], $pass) !== false) {
  849. if (get_tfa($user)['name'] != "none") {
  850. $_SESSION['pending_mailcow_cc_username'] = $user;
  851. $_SESSION['pending_mailcow_cc_role'] = "domainadmin";
  852. $_SESSION['pending_tfa_method'] = get_tfa($user)['name'];
  853. unset($_SESSION['ldelay']);
  854. $_SESSION['return'][] = array(
  855. 'type' => 'info',
  856. 'log' => array(__FUNCTION__, $user, '*'),
  857. 'msg' => 'awaiting_tfa_confirmation'
  858. );
  859. return "pending";
  860. }
  861. else {
  862. unset($_SESSION['ldelay']);
  863. // Reactivate TFA if it was set to "deactivate TFA for next login"
  864. $stmt = $pdo->prepare("UPDATE `tfa` SET `active`='1' WHERE `username` = :user");
  865. $stmt->execute(array(':user' => $user));
  866. $_SESSION['return'][] = array(
  867. 'type' => 'success',
  868. 'log' => array(__FUNCTION__, $user, '*'),
  869. 'msg' => array('logged_in_as', $user)
  870. );
  871. return "domainadmin";
  872. }
  873. }
  874. }
  875. // Validate mailbox user
  876. $stmt = $pdo->prepare("SELECT `password` FROM `mailbox`
  877. INNER JOIN domain on mailbox.domain = domain.domain
  878. WHERE `kind` NOT REGEXP 'location|thing|group'
  879. AND `mailbox`.`active`='1'
  880. AND `domain`.`active`='1'
  881. AND `username` = :user");
  882. $stmt->execute(array(':user' => $user));
  883. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  884. if ($app_passwd_data['eas'] === true) {
  885. $stmt = $pdo->prepare("SELECT `app_passwd`.`password` as `password`, `app_passwd`.`id` as `app_passwd_id` FROM `app_passwd`
  886. INNER JOIN `mailbox` ON `mailbox`.`username` = `app_passwd`.`mailbox`
  887. INNER JOIN `domain` ON `mailbox`.`domain` = `domain`.`domain`
  888. WHERE `mailbox`.`kind` NOT REGEXP 'location|thing|group'
  889. AND `mailbox`.`active` = '1'
  890. AND `domain`.`active` = '1'
  891. AND `app_passwd`.`active` = '1'
  892. AND `app_passwd`.`eas_access` = '1'
  893. AND `app_passwd`.`mailbox` = :user");
  894. $stmt->execute(array(':user' => $user));
  895. $rows = array_merge($rows, $stmt->fetchAll(PDO::FETCH_ASSOC));
  896. }
  897. elseif ($app_passwd_data['dav'] === true) {
  898. $stmt = $pdo->prepare("SELECT `app_passwd`.`password` as `password`, `app_passwd`.`id` as `app_passwd_id` FROM `app_passwd`
  899. INNER JOIN `mailbox` ON `mailbox`.`username` = `app_passwd`.`mailbox`
  900. INNER JOIN `domain` ON `mailbox`.`domain` = `domain`.`domain`
  901. WHERE `mailbox`.`kind` NOT REGEXP 'location|thing|group'
  902. AND `mailbox`.`active` = '1'
  903. AND `domain`.`active` = '1'
  904. AND `app_passwd`.`active` = '1'
  905. AND `app_passwd`.`dav_access` = '1'
  906. AND `app_passwd`.`mailbox` = :user");
  907. $stmt->execute(array(':user' => $user));
  908. $rows = array_merge($rows, $stmt->fetchAll(PDO::FETCH_ASSOC));
  909. }
  910. foreach ($rows as $row) {
  911. if (verify_hash($row['password'], $pass) !== false) {
  912. unset($_SESSION['ldelay']);
  913. $_SESSION['return'][] = array(
  914. 'type' => 'success',
  915. 'log' => array(__FUNCTION__, $user, '*'),
  916. 'msg' => array('logged_in_as', $user)
  917. );
  918. if ($app_passwd_data['proxyauth'] === true) {
  919. $service = ($app_passwd_data['eas'] === true) ? 'EAS' : (($app_passwd_data['dav'] === true) ? 'DAV' : 'SSO');
  920. $stmt = $pdo->prepare("REPLACE INTO sasl_log (`service`, `app_password`, `username`, `real_rip`) VALUES (:service, :app_id, :username, :remote_addr)");
  921. $stmt->execute(array(
  922. ':service' => $service,
  923. ':app_id' => $row['app_passwd_id'],
  924. ':username' => $user,
  925. ':remote_addr' => $_SERVER['REMOTE_ADDR']
  926. ));
  927. }
  928. return "user";
  929. }
  930. }
  931. if (!isset($_SESSION['ldelay'])) {
  932. $_SESSION['ldelay'] = "0";
  933. $redis->publish("F2B_CHANNEL", "mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  934. error_log("mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  935. }
  936. elseif (!isset($_SESSION['mailcow_cc_username'])) {
  937. $_SESSION['ldelay'] = $_SESSION['ldelay']+0.5;
  938. $redis->publish("F2B_CHANNEL", "mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  939. error_log("mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  940. }
  941. $_SESSION['return'][] = array(
  942. 'type' => 'danger',
  943. 'log' => array(__FUNCTION__, $user, '*'),
  944. 'msg' => 'login_failed'
  945. );
  946. sleep($_SESSION['ldelay']);
  947. return false;
  948. }
  949. function formatBytes($size, $precision = 2) {
  950. if(!is_numeric($size)) {
  951. return "0";
  952. }
  953. $base = log($size, 1024);
  954. $suffixes = array(' Byte', ' KiB', ' MiB', ' GiB', ' TiB');
  955. if ($size == "0") {
  956. return "0";
  957. }
  958. return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
  959. }
  960. function update_sogo_static_view() {
  961. if (getenv('SKIP_SOGO') == "y") {
  962. return true;
  963. }
  964. global $pdo;
  965. global $lang;
  966. $stmt = $pdo->query("SELECT 'OK' FROM INFORMATION_SCHEMA.TABLES
  967. WHERE TABLE_NAME = 'sogo_view'");
  968. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  969. if ($num_results != 0) {
  970. $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`)
  971. SELECT `c_uid`, `domain`, `c_name`, `c_password`, `c_cn`, `mail`, `aliases`, `ad_aliases`, `ext_acl`, `kind`, `multiple_bookings` from sogo_view");
  972. $stmt = $pdo->query("DELETE FROM _sogo_static_view WHERE `c_uid` NOT IN (SELECT `username` FROM `mailbox` WHERE `active` = '1');");
  973. }
  974. flush_memcached();
  975. }
  976. function edit_user_account($_data) {
  977. global $lang;
  978. global $pdo;
  979. $_data_log = $_data;
  980. !isset($_data_log['user_new_pass']) ?: $_data_log['user_new_pass'] = '*';
  981. !isset($_data_log['user_new_pass2']) ?: $_data_log['user_new_pass2'] = '*';
  982. !isset($_data_log['user_old_pass']) ?: $_data_log['user_old_pass'] = '*';
  983. $username = $_SESSION['mailcow_cc_username'];
  984. $role = $_SESSION['mailcow_cc_role'];
  985. $password_old = $_data['user_old_pass'];
  986. if (filter_var($username, FILTER_VALIDATE_EMAIL === false) || $role != 'user') {
  987. $_SESSION['return'][] = array(
  988. 'type' => 'danger',
  989. 'log' => array(__FUNCTION__, $_data_log),
  990. 'msg' => 'access_denied'
  991. );
  992. return false;
  993. }
  994. $stmt = $pdo->prepare("SELECT `password` FROM `mailbox`
  995. WHERE `kind` NOT REGEXP 'location|thing|group'
  996. AND `username` = :user");
  997. $stmt->execute(array(':user' => $username));
  998. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  999. if (!verify_hash($row['password'], $password_old)) {
  1000. $_SESSION['return'][] = array(
  1001. 'type' => 'danger',
  1002. 'log' => array(__FUNCTION__, $_data_log),
  1003. 'msg' => 'access_denied'
  1004. );
  1005. return false;
  1006. }
  1007. if (!empty($_data['user_new_pass']) && !empty($_data['user_new_pass2'])) {
  1008. $password_new = $_data['user_new_pass'];
  1009. $password_new2 = $_data['user_new_pass2'];
  1010. if (password_check($password_new, $password_new2) !== true) {
  1011. return false;
  1012. }
  1013. $password_hashed = hash_password($password_new);
  1014. $stmt = $pdo->prepare("UPDATE `mailbox` SET `password` = :password_hashed,
  1015. `attributes` = JSON_SET(`attributes`, '$.force_pw_update', '0'),
  1016. `attributes` = JSON_SET(`attributes`, '$.passwd_update', NOW())
  1017. WHERE `username` = :username");
  1018. $stmt->execute(array(
  1019. ':password_hashed' => $password_hashed,
  1020. ':username' => $username
  1021. ));
  1022. }
  1023. update_sogo_static_view();
  1024. $_SESSION['return'][] = array(
  1025. 'type' => 'success',
  1026. 'log' => array(__FUNCTION__, $_data_log),
  1027. 'msg' => array('mailbox_modified', htmlspecialchars($username))
  1028. );
  1029. }
  1030. function user_get_alias_details($username) {
  1031. global $pdo;
  1032. global $lang;
  1033. $data['direct_aliases'] = array();
  1034. $data['shared_aliases'] = array();
  1035. if ($_SESSION['mailcow_cc_role'] == "user") {
  1036. $username = $_SESSION['mailcow_cc_username'];
  1037. }
  1038. if (!filter_var($username, FILTER_VALIDATE_EMAIL)) {
  1039. return false;
  1040. }
  1041. if (!hasMailboxObjectAccess($username, $_SESSION['mailcow_cc_role'], $username)) {
  1042. return false;
  1043. }
  1044. $data['address'] = $username;
  1045. $stmt = $pdo->prepare("SELECT `address` AS `shared_aliases`, `public_comment` FROM `alias`
  1046. WHERE `goto` REGEXP :username_goto
  1047. AND `address` NOT LIKE '@%'
  1048. AND `goto` != :username_goto2
  1049. AND `address` != :username_address");
  1050. $stmt->execute(array(
  1051. ':username_goto' => '(^|,)'.$username.'($|,)',
  1052. ':username_goto2' => $username,
  1053. ':username_address' => $username
  1054. ));
  1055. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1056. while ($row = array_shift($run)) {
  1057. $data['shared_aliases'][$row['shared_aliases']]['public_comment'] = htmlspecialchars($row['public_comment']);
  1058. //$data['shared_aliases'][] = $row['shared_aliases'];
  1059. }
  1060. $stmt = $pdo->prepare("SELECT `address` AS `direct_aliases`, `public_comment` FROM `alias`
  1061. WHERE `goto` = :username_goto
  1062. AND `address` NOT LIKE '@%'
  1063. AND `address` != :username_address");
  1064. $stmt->execute(
  1065. array(
  1066. ':username_goto' => $username,
  1067. ':username_address' => $username
  1068. ));
  1069. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1070. while ($row = array_shift($run)) {
  1071. $data['direct_aliases'][$row['direct_aliases']]['public_comment'] = htmlspecialchars($row['public_comment']);
  1072. }
  1073. $stmt = $pdo->prepare("SELECT CONCAT(local_part, '@', alias_domain) AS `ad_alias`, `alias_domain` FROM `mailbox`
  1074. LEFT OUTER JOIN `alias_domain` on `target_domain` = `domain`
  1075. WHERE `username` = :username ;");
  1076. $stmt->execute(array(':username' => $username));
  1077. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1078. while ($row = array_shift($run)) {
  1079. if (empty($row['ad_alias'])) {
  1080. continue;
  1081. }
  1082. $data['direct_aliases'][$row['ad_alias']]['public_comment'] = $lang['add']['alias_domain'];
  1083. $data['alias_domains'][] = $row['alias_domain'];
  1084. }
  1085. $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 '@%';");
  1086. $stmt->execute(array(':username' => $username));
  1087. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1088. while ($row = array_shift($run)) {
  1089. $data['aliases_also_send_as'] = $row['send_as'];
  1090. }
  1091. $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 '@%';");
  1092. $stmt->execute(array(':username' => $username));
  1093. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1094. while ($row = array_shift($run)) {
  1095. $data['aliases_send_as_all'] = $row['send_as'];
  1096. }
  1097. $stmt = $pdo->prepare("SELECT IFNULL(GROUP_CONCAT(`address` SEPARATOR ', '), '') as `address` FROM `alias` WHERE `goto` REGEXP :username AND `address` LIKE '@%';");
  1098. $stmt->execute(array(':username' => '(^|,)'.$username.'($|,)'));
  1099. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1100. while ($row = array_shift($run)) {
  1101. $data['is_catch_all'] = $row['address'];
  1102. }
  1103. return $data;
  1104. }
  1105. function is_valid_domain_name($domain_name) {
  1106. if (empty($domain_name)) {
  1107. return false;
  1108. }
  1109. $domain_name = idn_to_ascii($domain_name, 0, INTL_IDNA_VARIANT_UTS46);
  1110. return (preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $domain_name)
  1111. && preg_match("/^.{1,253}$/", $domain_name)
  1112. && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $domain_name));
  1113. }
  1114. function set_tfa($_data) {
  1115. global $pdo;
  1116. global $yubi;
  1117. global $u2f;
  1118. global $tfa;
  1119. $_data_log = $_data;
  1120. !isset($_data_log['confirm_password']) ?: $_data_log['confirm_password'] = '*';
  1121. $username = $_SESSION['mailcow_cc_username'];
  1122. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1123. $_SESSION['return'][] = array(
  1124. 'type' => 'danger',
  1125. 'log' => array(__FUNCTION__, $_data_log),
  1126. 'msg' => 'access_denied'
  1127. );
  1128. return false;
  1129. }
  1130. $stmt = $pdo->prepare("SELECT `password` FROM `admin`
  1131. WHERE `username` = :username");
  1132. $stmt->execute(array(':username' => $username));
  1133. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1134. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  1135. if (!empty($num_results)) {
  1136. if (!verify_hash($row['password'], $_data["confirm_password"])) {
  1137. $_SESSION['return'][] = array(
  1138. 'type' => 'danger',
  1139. 'log' => array(__FUNCTION__, $_data_log),
  1140. 'msg' => 'access_denied'
  1141. );
  1142. return false;
  1143. }
  1144. }
  1145. $stmt = $pdo->prepare("SELECT `password` FROM `mailbox`
  1146. WHERE `username` = :username");
  1147. $stmt->execute(array(':username' => $username));
  1148. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1149. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  1150. if (!empty($num_results)) {
  1151. if (!verify_hash($row['password'], $_data["confirm_password"])) {
  1152. $_SESSION['return'][] = array(
  1153. 'type' => 'danger',
  1154. 'log' => array(__FUNCTION__, $_data_log),
  1155. 'msg' => 'access_denied'
  1156. );
  1157. return false;
  1158. }
  1159. }
  1160. switch ($_data["tfa_method"]) {
  1161. case "yubi_otp":
  1162. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  1163. $yubico_id = $_data['yubico_id'];
  1164. $yubico_key = $_data['yubico_key'];
  1165. $yubi = new Auth_Yubico($yubico_id, $yubico_key);
  1166. if (!$yubi) {
  1167. $_SESSION['return'][] = array(
  1168. 'type' => 'danger',
  1169. 'log' => array(__FUNCTION__, $_data_log),
  1170. 'msg' => 'access_denied'
  1171. );
  1172. return false;
  1173. }
  1174. if (!ctype_alnum($_data["otp_token"]) || strlen($_data["otp_token"]) != 44) {
  1175. $_SESSION['return'][] = array(
  1176. 'type' => 'danger',
  1177. 'log' => array(__FUNCTION__, $_data_log),
  1178. 'msg' => 'tfa_token_invalid'
  1179. );
  1180. return false;
  1181. }
  1182. $yauth = $yubi->verify($_data["otp_token"]);
  1183. if (PEAR::isError($yauth)) {
  1184. $_SESSION['return'][] = array(
  1185. 'type' => 'danger',
  1186. 'log' => array(__FUNCTION__, $_data_log),
  1187. 'msg' => array('yotp_verification_failed', $yauth->getMessage())
  1188. );
  1189. return false;
  1190. }
  1191. try {
  1192. // We could also do a modhex translation here
  1193. $yubico_modhex_id = substr($_data["otp_token"], 0, 12);
  1194. $stmt = $pdo->prepare("DELETE FROM `tfa`
  1195. WHERE `username` = :username
  1196. AND (`authmech` != 'yubi_otp')
  1197. OR (`authmech` = 'yubi_otp' AND `secret` LIKE :modhex)");
  1198. $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id));
  1199. $stmt = $pdo->prepare("INSERT INTO `tfa` (`key_id`, `username`, `authmech`, `active`, `secret`) VALUES
  1200. (:key_id, :username, 'yubi_otp', '1', :secret)");
  1201. $stmt->execute(array(':key_id' => $key_id, ':username' => $username, ':secret' => $yubico_id . ':' . $yubico_key . ':' . $yubico_modhex_id));
  1202. }
  1203. catch (PDOException $e) {
  1204. $_SESSION['return'][] = array(
  1205. 'type' => 'danger',
  1206. 'log' => array(__FUNCTION__, $_data_log),
  1207. 'msg' => array('mysql_error', $e)
  1208. );
  1209. return false;
  1210. }
  1211. $_SESSION['return'][] = array(
  1212. 'type' => 'success',
  1213. 'log' => array(__FUNCTION__, $_data_log),
  1214. 'msg' => array('object_modified', htmlspecialchars($username))
  1215. );
  1216. break;
  1217. case "u2f":
  1218. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  1219. try {
  1220. $reg = $u2f->doRegister(json_decode($_SESSION['regReq']), json_decode($_data['token']));
  1221. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username AND `authmech` != 'u2f'");
  1222. $stmt->execute(array(':username' => $username));
  1223. $stmt = $pdo->prepare("INSERT INTO `tfa` (`username`, `key_id`, `authmech`, `keyHandle`, `publicKey`, `certificate`, `counter`, `active`) VALUES (?, ?, 'u2f', ?, ?, ?, ?, '1')");
  1224. $stmt->execute(array($username, $key_id, $reg->keyHandle, $reg->publicKey, $reg->certificate, $reg->counter));
  1225. $_SESSION['return'][] = array(
  1226. 'type' => 'success',
  1227. 'log' => array(__FUNCTION__, $_data_log),
  1228. 'msg' => array('object_modified', $username)
  1229. );
  1230. $_SESSION['regReq'] = null;
  1231. }
  1232. catch (Exception $e) {
  1233. $_SESSION['return'][] = array(
  1234. 'type' => 'danger',
  1235. 'log' => array(__FUNCTION__, $_data_log),
  1236. 'msg' => array('u2f_verification_failed', $e->getMessage())
  1237. );
  1238. $_SESSION['regReq'] = null;
  1239. return false;
  1240. }
  1241. break;
  1242. case "totp":
  1243. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  1244. if ($tfa->verifyCode($_POST['totp_secret'], $_POST['totp_confirm_token']) === true) {
  1245. //$stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
  1246. //$stmt->execute(array(':username' => $username));
  1247. $stmt = $pdo->prepare("INSERT INTO `tfa` (`username`, `key_id`, `authmech`, `secret`, `active`) VALUES (?, ?, 'totp', ?, '1')");
  1248. $stmt->execute(array($username, $key_id, $_POST['totp_secret']));
  1249. $_SESSION['return'][] = array(
  1250. 'type' => 'success',
  1251. 'log' => array(__FUNCTION__, $_data_log),
  1252. 'msg' => array('object_modified', $username)
  1253. );
  1254. }
  1255. else {
  1256. $_SESSION['return'][] = array(
  1257. 'type' => 'danger',
  1258. 'log' => array(__FUNCTION__, $_data_log),
  1259. 'msg' => 'totp_verification_failed'
  1260. );
  1261. }
  1262. break;
  1263. case "none":
  1264. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
  1265. $stmt->execute(array(':username' => $username));
  1266. $_SESSION['return'][] = array(
  1267. 'type' => 'success',
  1268. 'log' => array(__FUNCTION__, $_data_log),
  1269. 'msg' => array('object_modified', htmlspecialchars($username))
  1270. );
  1271. break;
  1272. }
  1273. }
  1274. function fido2($_data) {
  1275. global $pdo;
  1276. $_data_log = $_data;
  1277. // Not logging registration data, only actions
  1278. // Silent errors for "get" requests
  1279. switch ($_data["action"]) {
  1280. case "register":
  1281. $username = $_SESSION['mailcow_cc_username'];
  1282. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1283. $_SESSION['return'][] = array(
  1284. 'type' => 'danger',
  1285. 'log' => array(__FUNCTION__, $_data["action"]),
  1286. 'msg' => 'access_denied'
  1287. );
  1288. return false;
  1289. }
  1290. $stmt = $pdo->prepare("INSERT INTO `fido2` (`username`, `rpId`, `credentialPublicKey`, `certificateChain`, `certificate`, `certificateIssuer`, `certificateSubject`, `signatureCounter`, `AAGUID`, `credentialId`)
  1291. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
  1292. $stmt->execute(array(
  1293. $username,
  1294. $_data['registration']->rpId,
  1295. $_data['registration']->credentialPublicKey,
  1296. $_data['registration']->certificateChain,
  1297. $_data['registration']->certificate,
  1298. $_data['registration']->certificateIssuer,
  1299. $_data['registration']->certificateSubject,
  1300. $_data['registration']->signatureCounter,
  1301. $_data['registration']->AAGUID,
  1302. $_data['registration']->credentialId)
  1303. );
  1304. $_SESSION['return'][] = array(
  1305. 'type' => 'success',
  1306. 'log' => array(__FUNCTION__, $_data["action"]),
  1307. 'msg' => array('object_modified', $username)
  1308. );
  1309. break;
  1310. case "get_user_cids":
  1311. // Used to exclude existing CredentialIds while registering
  1312. $username = $_SESSION['mailcow_cc_username'];
  1313. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1314. return false;
  1315. }
  1316. $stmt = $pdo->prepare("SELECT `credentialId` FROM `fido2` WHERE `username` = :username");
  1317. $stmt->execute(array(':username' => $username));
  1318. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1319. while($row = array_shift($rows)) {
  1320. $cids[] = $row['credentialId'];
  1321. }
  1322. return $cids;
  1323. break;
  1324. case "get_all_cids":
  1325. // Only needed when using fido2 with username
  1326. $stmt = $pdo->query("SELECT `credentialId` FROM `fido2`");
  1327. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1328. while($row = array_shift($rows)) {
  1329. $cids[] = $row['credentialId'];
  1330. }
  1331. return $cids;
  1332. break;
  1333. case "get_by_b64cid":
  1334. if (!isset($_data['cid']) || empty($_data['cid'])) {
  1335. return false;
  1336. }
  1337. $stmt = $pdo->prepare("SELECT `certificateSubject`, `username`, `credentialPublicKey`, SHA2(`credentialId`, 256) AS `cid` FROM `fido2` WHERE TO_BASE64(`credentialId`) = :cid");
  1338. $stmt->execute(array(':cid' => $_data['cid']));
  1339. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1340. if (empty($row) || empty($row['credentialPublicKey']) || empty($row['username'])) {
  1341. return false;
  1342. }
  1343. $data['pub_key'] = $row['credentialPublicKey'];
  1344. $data['username'] = $row['username'];
  1345. $data['subject'] = $row['certificateSubject'];
  1346. $data['cid'] = $row['cid'];
  1347. return $data;
  1348. break;
  1349. case "get_friendly_names":
  1350. $username = $_SESSION['mailcow_cc_username'];
  1351. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1352. return false;
  1353. }
  1354. $stmt = $pdo->prepare("SELECT SHA2(`credentialId`, 256) AS `cid`, `created`, `certificateSubject`, `friendlyName` FROM `fido2` WHERE `username` = :username");
  1355. $stmt->execute(array(':username' => $username));
  1356. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1357. while($row = array_shift($rows)) {
  1358. $fns[] = array(
  1359. "subject" => (empty($row['certificateSubject']) ? 'Unknown (' . $row['created'] . ')' : $row['certificateSubject']),
  1360. "fn" => $row['friendlyName'],
  1361. "cid" => $row['cid']
  1362. );
  1363. }
  1364. return $fns;
  1365. break;
  1366. case "unset_fido2_key":
  1367. $username = $_SESSION['mailcow_cc_username'];
  1368. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1369. $_SESSION['return'][] = array(
  1370. 'type' => 'danger',
  1371. 'log' => array(__FUNCTION__, $_data["action"]),
  1372. 'msg' => 'access_denied'
  1373. );
  1374. return false;
  1375. }
  1376. $stmt = $pdo->prepare("DELETE FROM `fido2` WHERE `username` = :username AND SHA2(`credentialId`, 256) = :cid");
  1377. $stmt->execute(array(
  1378. ':username' => $username,
  1379. ':cid' => $_data['post_data']['unset_fido2_key']
  1380. ));
  1381. $_SESSION['return'][] = array(
  1382. 'type' => 'success',
  1383. 'log' => array(__FUNCTION__, $_data_log),
  1384. 'msg' => array('object_modified', htmlspecialchars($username))
  1385. );
  1386. break;
  1387. case "edit_fn":
  1388. $username = $_SESSION['mailcow_cc_username'];
  1389. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1390. $_SESSION['return'][] = array(
  1391. 'type' => 'danger',
  1392. 'log' => array(__FUNCTION__, $_data["action"]),
  1393. 'msg' => 'access_denied'
  1394. );
  1395. return false;
  1396. }
  1397. $stmt = $pdo->prepare("UPDATE `fido2` SET `friendlyName` = :friendlyName WHERE SHA2(`credentialId`, 256) = :cid AND `username` = :username");
  1398. $stmt->execute(array(
  1399. ':username' => $username,
  1400. ':friendlyName' => $_data['fido2_attrs']['fido2_fn'],
  1401. ':cid' => $_data['fido2_attrs']['fido2_cid']
  1402. ));
  1403. $_SESSION['return'][] = array(
  1404. 'type' => 'success',
  1405. 'log' => array(__FUNCTION__, $_data_log),
  1406. 'msg' => array('object_modified', htmlspecialchars($username))
  1407. );
  1408. break;
  1409. }
  1410. }
  1411. function unset_tfa_key($_data) {
  1412. // Can only unset own keys
  1413. // Needs at least one key left
  1414. global $pdo;
  1415. global $lang;
  1416. $_data_log = $_data;
  1417. $id = intval($_data['unset_tfa_key']);
  1418. $username = $_SESSION['mailcow_cc_username'];
  1419. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1420. $_SESSION['return'][] = array(
  1421. 'type' => 'danger',
  1422. 'log' => array(__FUNCTION__, $_data_log),
  1423. 'msg' => 'access_denied'
  1424. );
  1425. return false;
  1426. }
  1427. try {
  1428. if (!is_numeric($id)) {
  1429. $_SESSION['return'][] = array(
  1430. 'type' => 'danger',
  1431. 'log' => array(__FUNCTION__, $_data_log),
  1432. 'msg' => 'access_denied'
  1433. );
  1434. return false;
  1435. }
  1436. $stmt = $pdo->prepare("SELECT COUNT(*) AS `keys` FROM `tfa`
  1437. WHERE `username` = :username AND `active` = '1'");
  1438. $stmt->execute(array(':username' => $username));
  1439. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1440. if ($row['keys'] == "1") {
  1441. $_SESSION['return'][] = array(
  1442. 'type' => 'danger',
  1443. 'log' => array(__FUNCTION__, $_data_log),
  1444. 'msg' => 'last_key'
  1445. );
  1446. return false;
  1447. }
  1448. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username AND `id` = :id");
  1449. $stmt->execute(array(':username' => $username, ':id' => $id));
  1450. $_SESSION['return'][] = array(
  1451. 'type' => 'success',
  1452. 'log' => array(__FUNCTION__, $_data_log),
  1453. 'msg' => array('object_modified', $username)
  1454. );
  1455. }
  1456. catch (PDOException $e) {
  1457. $_SESSION['return'][] = array(
  1458. 'type' => 'danger',
  1459. 'log' => array(__FUNCTION__, $_data_log),
  1460. 'msg' => array('mysql_error', $e)
  1461. );
  1462. return false;
  1463. }
  1464. }
  1465. function get_tfa($username = null) {
  1466. global $pdo;
  1467. if (isset($_SESSION['mailcow_cc_username'])) {
  1468. $username = $_SESSION['mailcow_cc_username'];
  1469. }
  1470. elseif (empty($username)) {
  1471. return false;
  1472. }
  1473. $stmt = $pdo->prepare("SELECT * FROM `tfa`
  1474. WHERE `username` = :username AND `active` = '1'");
  1475. $stmt->execute(array(':username' => $username));
  1476. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1477. if (isset($row["authmech"])) {
  1478. switch ($row["authmech"]) {
  1479. case "yubi_otp":
  1480. $data['name'] = "yubi_otp";
  1481. $data['pretty'] = "Yubico OTP";
  1482. $stmt = $pdo->prepare("SELECT `id`, `key_id`, RIGHT(`secret`, 12) AS 'modhex' FROM `tfa` WHERE `authmech` = 'yubi_otp' AND `username` = :username");
  1483. $stmt->execute(array(
  1484. ':username' => $username,
  1485. ));
  1486. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1487. while($row = array_shift($rows)) {
  1488. $data['additional'][] = $row;
  1489. }
  1490. return $data;
  1491. break;
  1492. case "u2f":
  1493. $data['name'] = "u2f";
  1494. $data['pretty'] = "Fido U2F";
  1495. $stmt = $pdo->prepare("SELECT `id`, `key_id` FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username");
  1496. $stmt->execute(array(
  1497. ':username' => $username,
  1498. ));
  1499. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1500. while($row = array_shift($rows)) {
  1501. $data['additional'][] = $row;
  1502. }
  1503. return $data;
  1504. break;
  1505. case "hotp":
  1506. $data['name'] = "hotp";
  1507. $data['pretty'] = "HMAC-based OTP";
  1508. return $data;
  1509. break;
  1510. case "totp":
  1511. $data['name'] = "totp";
  1512. $data['pretty'] = "Time-based OTP";
  1513. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `secret` FROM `tfa` WHERE `authmech` = 'totp' AND `username` = :username");
  1514. $stmt->execute(array(
  1515. ':username' => $username,
  1516. ));
  1517. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1518. while($row = array_shift($rows)) {
  1519. $data['additional'][] = $row;
  1520. }
  1521. return $data;
  1522. break;
  1523. default:
  1524. $data['name'] = 'none';
  1525. $data['pretty'] = "-";
  1526. return $data;
  1527. break;
  1528. }
  1529. }
  1530. else {
  1531. $data['name'] = 'none';
  1532. $data['pretty'] = "-";
  1533. return $data;
  1534. }
  1535. }
  1536. function verify_tfa_login($username, $token) {
  1537. global $pdo;
  1538. global $yubi;
  1539. global $u2f;
  1540. global $tfa;
  1541. $stmt = $pdo->prepare("SELECT `authmech` FROM `tfa`
  1542. WHERE `username` = :username AND `active` = '1'");
  1543. $stmt->execute(array(':username' => $username));
  1544. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1545. switch ($row["authmech"]) {
  1546. case "yubi_otp":
  1547. if (!ctype_alnum($token) || strlen($token) != 44) {
  1548. $_SESSION['return'][] = array(
  1549. 'type' => 'danger',
  1550. 'log' => array(__FUNCTION__, $username, '*'),
  1551. 'msg' => array('yotp_verification_failed', 'token length error')
  1552. );
  1553. return false;
  1554. }
  1555. $yubico_modhex_id = substr($token, 0, 12);
  1556. $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
  1557. WHERE `username` = :username
  1558. AND `authmech` = 'yubi_otp'
  1559. AND `active`='1'
  1560. AND `secret` LIKE :modhex");
  1561. $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id));
  1562. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1563. $yubico_auth = explode(':', $row['secret']);
  1564. $yubi = new Auth_Yubico($yubico_auth[0], $yubico_auth[1]);
  1565. $yauth = $yubi->verify($token);
  1566. if (PEAR::isError($yauth)) {
  1567. $_SESSION['return'][] = array(
  1568. 'type' => 'danger',
  1569. 'log' => array(__FUNCTION__, $username, '*'),
  1570. 'msg' => array('yotp_verification_failed', $yauth->getMessage())
  1571. );
  1572. return false;
  1573. }
  1574. else {
  1575. $_SESSION['tfa_id'] = $row['id'];
  1576. $_SESSION['return'][] = array(
  1577. 'type' => 'success',
  1578. 'log' => array(__FUNCTION__, $username, '*'),
  1579. 'msg' => 'verified_yotp_login'
  1580. );
  1581. return true;
  1582. }
  1583. $_SESSION['return'][] = array(
  1584. 'type' => 'danger',
  1585. 'log' => array(__FUNCTION__, $username, '*'),
  1586. 'msg' => array('yotp_verification_failed', 'unknown')
  1587. );
  1588. return false;
  1589. break;
  1590. case "u2f":
  1591. try {
  1592. $reg = $u2f->doAuthenticate(json_decode($_SESSION['authReq']), get_u2f_registrations($username), json_decode($token));
  1593. $stmt = $pdo->prepare("SELECT `id` FROM `tfa` WHERE `keyHandle` = ?");
  1594. $stmt->execute(array($reg->keyHandle));
  1595. $row_key_id = $stmt->fetch(PDO::FETCH_ASSOC);
  1596. $_SESSION['tfa_id'] = $row_key_id['id'];
  1597. $_SESSION['authReq'] = null;
  1598. $_SESSION['return'][] = array(
  1599. 'type' => 'success',
  1600. 'log' => array(__FUNCTION__, $username, '*'),
  1601. 'msg' => 'verified_u2f_login'
  1602. );
  1603. return true;
  1604. }
  1605. catch (Exception $e) {
  1606. $_SESSION['return'][] = array(
  1607. 'type' => 'danger',
  1608. 'log' => array(__FUNCTION__, $username, '*'),
  1609. 'msg' => array('u2f_verification_failed', $e->getMessage())
  1610. );
  1611. $_SESSION['regReq'] = null;
  1612. return false;
  1613. }
  1614. $_SESSION['return'][] = array(
  1615. 'type' => 'danger',
  1616. 'log' => array(__FUNCTION__, $username, '*'),
  1617. 'msg' => array('u2f_verification_failed', 'unknown')
  1618. );
  1619. return false;
  1620. break;
  1621. case "hotp":
  1622. return false;
  1623. break;
  1624. case "totp":
  1625. try {
  1626. $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
  1627. WHERE `username` = :username
  1628. AND `authmech` = 'totp'
  1629. AND `active`='1'");
  1630. $stmt->execute(array(':username' => $username));
  1631. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1632. foreach ($rows as $row) {
  1633. if ($tfa->verifyCode($row['secret'], $_POST['token']) === true) {
  1634. $_SESSION['tfa_id'] = $row['id'];
  1635. $_SESSION['return'][] = array(
  1636. 'type' => 'success',
  1637. 'log' => array(__FUNCTION__, $username, '*'),
  1638. 'msg' => 'verified_totp_login'
  1639. );
  1640. return true;
  1641. }
  1642. }
  1643. $_SESSION['return'][] = array(
  1644. 'type' => 'danger',
  1645. 'log' => array(__FUNCTION__, $username, '*'),
  1646. 'msg' => 'totp_verification_failed'
  1647. );
  1648. return false;
  1649. }
  1650. catch (PDOException $e) {
  1651. $_SESSION['return'][] = array(
  1652. 'type' => 'danger',
  1653. 'log' => array(__FUNCTION__, $username, '*'),
  1654. 'msg' => array('mysql_error', $e)
  1655. );
  1656. return false;
  1657. }
  1658. break;
  1659. default:
  1660. $_SESSION['return'][] = array(
  1661. 'type' => 'danger',
  1662. 'log' => array(__FUNCTION__, $username, '*'),
  1663. 'msg' => 'unknown_tfa_method'
  1664. );
  1665. return false;
  1666. break;
  1667. }
  1668. return false;
  1669. }
  1670. function admin_api($access, $action, $data = null) {
  1671. global $pdo;
  1672. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1673. $_SESSION['return'][] = array(
  1674. 'type' => 'danger',
  1675. 'log' => array(__FUNCTION__),
  1676. 'msg' => 'access_denied'
  1677. );
  1678. return false;
  1679. }
  1680. if ($access !== "ro" && $access !== "rw") {
  1681. $_SESSION['return'][] = array(
  1682. 'type' => 'danger',
  1683. 'log' => array(__FUNCTION__),
  1684. 'msg' => 'invalid access type'
  1685. );
  1686. return false;
  1687. }
  1688. if ($action == "edit") {
  1689. $active = (!empty($data['active'])) ? 1 : 0;
  1690. $skip_ip_check = (isset($data['skip_ip_check'])) ? 1 : 0;
  1691. $allow_from = array();
  1692. if (isset($data['allow_from'])) {
  1693. $allow_from = array_map('trim', preg_split( "/( |,|;|\n)/", $data['allow_from']));
  1694. }
  1695. foreach ($allow_from as $key => $val) {
  1696. if (empty($val)) {
  1697. unset($allow_from[$key]);
  1698. continue;
  1699. }
  1700. if (valid_network($val) !== true) {
  1701. $_SESSION['return'][] = array(
  1702. 'type' => 'warning',
  1703. 'log' => array(__FUNCTION__, $data),
  1704. 'msg' => array('ip_invalid', htmlspecialchars($allow_from[$key]))
  1705. );
  1706. unset($allow_from[$key]);
  1707. continue;
  1708. }
  1709. }
  1710. $allow_from = implode(',', array_unique(array_filter($allow_from)));
  1711. if (empty($allow_from) && $skip_ip_check == 0) {
  1712. $_SESSION['return'][] = array(
  1713. 'type' => 'danger',
  1714. 'log' => array(__FUNCTION__, $data),
  1715. 'msg' => 'ip_list_empty'
  1716. );
  1717. return false;
  1718. }
  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->query("SELECT `api_key` FROM `api` WHERE `access` = '" . $access . "'");
  1727. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  1728. if (empty($num_results)) {
  1729. $stmt = $pdo->prepare("INSERT INTO `api` (`api_key`, `skip_ip_check`, `active`, `allow_from`, `access`)
  1730. VALUES (:api_key, :skip_ip_check, :active, :allow_from, :access);");
  1731. $stmt->execute(array(
  1732. ':api_key' => $api_key,
  1733. ':skip_ip_check' => $skip_ip_check,
  1734. ':active' => $active,
  1735. ':allow_from' => $allow_from,
  1736. ':access' => $access
  1737. ));
  1738. }
  1739. else {
  1740. if ($skip_ip_check == 0) {
  1741. $stmt = $pdo->prepare("UPDATE `api` SET `skip_ip_check` = :skip_ip_check,
  1742. `active` = :active,
  1743. `allow_from` = :allow_from
  1744. WHERE `access` = :access;");
  1745. $stmt->execute(array(
  1746. ':active' => $active,
  1747. ':skip_ip_check' => $skip_ip_check,
  1748. ':allow_from' => $allow_from,
  1749. ':access' => $access
  1750. ));
  1751. }
  1752. else {
  1753. $stmt = $pdo->prepare("UPDATE `api` SET `skip_ip_check` = :skip_ip_check,
  1754. `active` = :active
  1755. WHERE `access` = :access;");
  1756. $stmt->execute(array(
  1757. ':active' => $active,
  1758. ':skip_ip_check' => $skip_ip_check,
  1759. ':access' => $access
  1760. ));
  1761. }
  1762. }
  1763. }
  1764. elseif ($action == "regen_key") {
  1765. $api_key = implode('-', array(
  1766. strtoupper(bin2hex(random_bytes(3))),
  1767. strtoupper(bin2hex(random_bytes(3))),
  1768. strtoupper(bin2hex(random_bytes(3))),
  1769. strtoupper(bin2hex(random_bytes(3))),
  1770. strtoupper(bin2hex(random_bytes(3)))
  1771. ));
  1772. $stmt = $pdo->prepare("UPDATE `api` SET `api_key` = :api_key WHERE `access` = :access");
  1773. $stmt->execute(array(
  1774. ':api_key' => $api_key,
  1775. ':access' => $access
  1776. ));
  1777. }
  1778. elseif ($action == "get") {
  1779. $stmt = $pdo->query("SELECT * FROM `api` WHERE `access` = '" . $access . "'");
  1780. $apidata = $stmt->fetch(PDO::FETCH_ASSOC);
  1781. if ($apidata !== false) {
  1782. $apidata['allow_from'] = str_replace(',', PHP_EOL, $apidata['allow_from']);
  1783. }
  1784. return $apidata;
  1785. }
  1786. $_SESSION['return'][] = array(
  1787. 'type' => 'success',
  1788. 'log' => array(__FUNCTION__, $data),
  1789. 'msg' => 'admin_api_modified'
  1790. );
  1791. }
  1792. function license($action, $data = null) {
  1793. global $pdo;
  1794. global $redis;
  1795. global $lang;
  1796. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1797. $_SESSION['return'][] = array(
  1798. 'type' => 'danger',
  1799. 'log' => array(__FUNCTION__),
  1800. 'msg' => 'access_denied'
  1801. );
  1802. return false;
  1803. }
  1804. switch ($action) {
  1805. case "verify":
  1806. // Keep result until revalidate button is pressed or session expired
  1807. $stmt = $pdo->query("SELECT `version` FROM `versions` WHERE `application` = 'GUID'");
  1808. $versions = $stmt->fetch(PDO::FETCH_ASSOC);
  1809. $post = array('guid' => $versions['version']);
  1810. $curl = curl_init('https://verify.mailcow.email');
  1811. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  1812. curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
  1813. curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
  1814. $response = curl_exec($curl);
  1815. curl_close($curl);
  1816. $json_return = json_decode($response, true);
  1817. if ($response && $json_return) {
  1818. if ($json_return['response'] === "ok") {
  1819. $_SESSION['gal']['valid'] = "true";
  1820. $_SESSION['gal']['c'] = $json_return['c'];
  1821. $_SESSION['gal']['s'] = $json_return['s'];
  1822. if ($json_return['m'] == 'NoMoore') {
  1823. $_SESSION['gal']['m'] = '🐄';
  1824. }
  1825. else {
  1826. $_SESSION['gal']['m'] = str_repeat('🐄', substr_count($json_return['m'], 'o'));
  1827. }
  1828. }
  1829. elseif ($json_return['response'] === "invalid") {
  1830. $_SESSION['gal']['valid'] = "false";
  1831. $_SESSION['gal']['c'] = $lang['mailbox']['no'];
  1832. $_SESSION['gal']['s'] = $lang['mailbox']['no'];
  1833. $_SESSION['gal']['m'] = $lang['mailbox']['no'];
  1834. }
  1835. }
  1836. else {
  1837. $_SESSION['gal']['valid'] = "false";
  1838. $_SESSION['gal']['c'] = $lang['danger']['temp_error'];
  1839. $_SESSION['gal']['s'] = $lang['danger']['temp_error'];
  1840. $_SESSION['gal']['m'] = $lang['danger']['temp_error'];
  1841. }
  1842. try {
  1843. // json_encode needs "true"/"false" instead of true/false, to not encode it to 0 or 1
  1844. $redis->Set('LICENSE_STATUS_CACHE', json_encode($_SESSION['gal']));
  1845. }
  1846. catch (RedisException $e) {
  1847. $_SESSION['return'][] = array(
  1848. 'type' => 'danger',
  1849. 'log' => array(__FUNCTION__, $_action, $_data_log),
  1850. 'msg' => array('redis_error', $e)
  1851. );
  1852. return false;
  1853. }
  1854. return $_SESSION['gal']['valid'];
  1855. break;
  1856. case "guid":
  1857. $stmt = $pdo->query("SELECT `version` FROM `versions` WHERE `application` = 'GUID'");
  1858. $versions = $stmt->fetch(PDO::FETCH_ASSOC);
  1859. return $versions['version'];
  1860. break;
  1861. }
  1862. }
  1863. function rspamd_ui($action, $data = null) {
  1864. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1865. $_SESSION['return'][] = array(
  1866. 'type' => 'danger',
  1867. 'log' => array(__FUNCTION__),
  1868. 'msg' => 'access_denied'
  1869. );
  1870. return false;
  1871. }
  1872. switch ($action) {
  1873. case "edit":
  1874. $rspamd_ui_pass = $data['rspamd_ui_pass'];
  1875. $rspamd_ui_pass2 = $data['rspamd_ui_pass2'];
  1876. if (empty($rspamd_ui_pass) || empty($rspamd_ui_pass2)) {
  1877. $_SESSION['return'][] = array(
  1878. 'type' => 'danger',
  1879. 'log' => array(__FUNCTION__, '*', '*'),
  1880. 'msg' => 'password_empty'
  1881. );
  1882. return false;
  1883. }
  1884. if ($rspamd_ui_pass != $rspamd_ui_pass2) {
  1885. $_SESSION['return'][] = array(
  1886. 'type' => 'danger',
  1887. 'log' => array(__FUNCTION__, '*', '*'),
  1888. 'msg' => 'password_mismatch'
  1889. );
  1890. return false;
  1891. }
  1892. if (strlen($rspamd_ui_pass) < 6) {
  1893. $_SESSION['return'][] = array(
  1894. 'type' => 'danger',
  1895. 'log' => array(__FUNCTION__, '*', '*'),
  1896. 'msg' => 'rspamd_ui_pw_length'
  1897. );
  1898. return false;
  1899. }
  1900. $docker_return = docker('post', 'rspamd-mailcow', 'exec', array('cmd' => 'rspamd', 'task' => 'worker_password', 'raw' => $rspamd_ui_pass), array('Content-Type: application/json'));
  1901. if ($docker_return_array = json_decode($docker_return, true)) {
  1902. if ($docker_return_array['type'] == 'success') {
  1903. $_SESSION['return'][] = array(
  1904. 'type' => 'success',
  1905. 'log' => array(__FUNCTION__, '*', '*'),
  1906. 'msg' => 'rspamd_ui_pw_set'
  1907. );
  1908. return true;
  1909. }
  1910. else {
  1911. $_SESSION['return'][] = array(
  1912. 'type' => $docker_return_array['type'],
  1913. 'log' => array(__FUNCTION__, '*', '*'),
  1914. 'msg' => $docker_return_array['msg']
  1915. );
  1916. return false;
  1917. }
  1918. }
  1919. else {
  1920. $_SESSION['return'][] = array(
  1921. 'type' => 'danger',
  1922. 'log' => array(__FUNCTION__, '*', '*'),
  1923. 'msg' => 'unknown'
  1924. );
  1925. return false;
  1926. }
  1927. break;
  1928. }
  1929. }
  1930. function get_u2f_registrations($username) {
  1931. global $pdo;
  1932. $sel = $pdo->prepare("SELECT * FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = ? AND `active` = '1'");
  1933. $sel->execute(array($username));
  1934. return $sel->fetchAll(PDO::FETCH_OBJ);
  1935. }
  1936. function get_logs($application, $lines = false) {
  1937. if ($lines === false) {
  1938. $lines = $GLOBALS['LOG_LINES'] - 1;
  1939. }
  1940. elseif(is_numeric($lines) && $lines >= 1) {
  1941. $lines = abs(intval($lines) - 1);
  1942. }
  1943. else {
  1944. list ($from, $to) = explode('-', $lines);
  1945. $from = intval($from);
  1946. $to = intval($to);
  1947. if ($from < 1 || $to < $from) { return false; }
  1948. }
  1949. global $redis;
  1950. global $pdo;
  1951. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1952. return false;
  1953. }
  1954. // SQL
  1955. if ($application == "mailcow-ui") {
  1956. if (isset($from) && isset($to)) {
  1957. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :from, :to");
  1958. $stmt->execute(array(
  1959. ':from' => $from - 1,
  1960. ':to' => $to
  1961. ));
  1962. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1963. }
  1964. else {
  1965. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :lines");
  1966. $stmt->execute(array(
  1967. ':lines' => $lines + 1,
  1968. ));
  1969. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1970. }
  1971. if (is_array($data)) {
  1972. return $data;
  1973. }
  1974. }
  1975. if ($application == "sasl") {
  1976. if (isset($from) && isset($to)) {
  1977. $stmt = $pdo->prepare("SELECT * FROM `sasl_log` ORDER BY `datetime` DESC LIMIT :from, :to");
  1978. $stmt->execute(array(
  1979. ':from' => $from - 1,
  1980. ':to' => $to
  1981. ));
  1982. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1983. }
  1984. else {
  1985. $stmt = $pdo->prepare("SELECT * FROM `sasl_log` ORDER BY `datetime` DESC LIMIT :lines");
  1986. $stmt->execute(array(
  1987. ':lines' => $lines + 1,
  1988. ));
  1989. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1990. }
  1991. if (is_array($data)) {
  1992. return $data;
  1993. }
  1994. }
  1995. // Redis
  1996. if ($application == "dovecot-mailcow") {
  1997. if (isset($from) && isset($to)) {
  1998. $data = $redis->lRange('DOVECOT_MAILLOG', $from - 1, $to - 1);
  1999. }
  2000. else {
  2001. $data = $redis->lRange('DOVECOT_MAILLOG', 0, $lines);
  2002. }
  2003. if ($data) {
  2004. foreach ($data as $json_line) {
  2005. $data_array[] = json_decode($json_line, true);
  2006. }
  2007. return $data_array;
  2008. }
  2009. }
  2010. if ($application == "postfix-mailcow") {
  2011. if (isset($from) && isset($to)) {
  2012. $data = $redis->lRange('POSTFIX_MAILLOG', $from - 1, $to - 1);
  2013. }
  2014. else {
  2015. $data = $redis->lRange('POSTFIX_MAILLOG', 0, $lines);
  2016. }
  2017. if ($data) {
  2018. foreach ($data as $json_line) {
  2019. $data_array[] = json_decode($json_line, true);
  2020. }
  2021. return $data_array;
  2022. }
  2023. }
  2024. if ($application == "sogo-mailcow") {
  2025. if (isset($from) && isset($to)) {
  2026. $data = $redis->lRange('SOGO_LOG', $from - 1, $to - 1);
  2027. }
  2028. else {
  2029. $data = $redis->lRange('SOGO_LOG', 0, $lines);
  2030. }
  2031. if ($data) {
  2032. foreach ($data as $json_line) {
  2033. $data_array[] = json_decode($json_line, true);
  2034. }
  2035. return $data_array;
  2036. }
  2037. }
  2038. if ($application == "watchdog-mailcow") {
  2039. if (isset($from) && isset($to)) {
  2040. $data = $redis->lRange('WATCHDOG_LOG', $from - 1, $to - 1);
  2041. }
  2042. else {
  2043. $data = $redis->lRange('WATCHDOG_LOG', 0, $lines);
  2044. }
  2045. if ($data) {
  2046. foreach ($data as $json_line) {
  2047. $data_array[] = json_decode($json_line, true);
  2048. }
  2049. return $data_array;
  2050. }
  2051. }
  2052. if ($application == "acme-mailcow") {
  2053. if (isset($from) && isset($to)) {
  2054. $data = $redis->lRange('ACME_LOG', $from - 1, $to - 1);
  2055. }
  2056. else {
  2057. $data = $redis->lRange('ACME_LOG', 0, $lines);
  2058. }
  2059. if ($data) {
  2060. foreach ($data as $json_line) {
  2061. $data_array[] = json_decode($json_line, true);
  2062. }
  2063. return $data_array;
  2064. }
  2065. }
  2066. if ($application == "ratelimited") {
  2067. if (isset($from) && isset($to)) {
  2068. $data = $redis->lRange('RL_LOG', $from - 1, $to - 1);
  2069. }
  2070. else {
  2071. $data = $redis->lRange('RL_LOG', 0, $lines);
  2072. }
  2073. if ($data) {
  2074. foreach ($data as $json_line) {
  2075. $data_array[] = json_decode($json_line, true);
  2076. }
  2077. return $data_array;
  2078. }
  2079. }
  2080. if ($application == "api-mailcow") {
  2081. if (isset($from) && isset($to)) {
  2082. $data = $redis->lRange('API_LOG', $from - 1, $to - 1);
  2083. }
  2084. else {
  2085. $data = $redis->lRange('API_LOG', 0, $lines);
  2086. }
  2087. if ($data) {
  2088. foreach ($data as $json_line) {
  2089. $data_array[] = json_decode($json_line, true);
  2090. }
  2091. return $data_array;
  2092. }
  2093. }
  2094. if ($application == "netfilter-mailcow") {
  2095. if (isset($from) && isset($to)) {
  2096. $data = $redis->lRange('NETFILTER_LOG', $from - 1, $to - 1);
  2097. }
  2098. else {
  2099. $data = $redis->lRange('NETFILTER_LOG', 0, $lines);
  2100. }
  2101. if ($data) {
  2102. foreach ($data as $json_line) {
  2103. $data_array[] = json_decode($json_line, true);
  2104. }
  2105. return $data_array;
  2106. }
  2107. }
  2108. if ($application == "autodiscover-mailcow") {
  2109. if (isset($from) && isset($to)) {
  2110. $data = $redis->lRange('AUTODISCOVER_LOG', $from - 1, $to - 1);
  2111. }
  2112. else {
  2113. $data = $redis->lRange('AUTODISCOVER_LOG', 0, $lines);
  2114. }
  2115. if ($data) {
  2116. foreach ($data as $json_line) {
  2117. $data_array[] = json_decode($json_line, true);
  2118. }
  2119. return $data_array;
  2120. }
  2121. }
  2122. if ($application == "rspamd-history") {
  2123. $curl = curl_init();
  2124. curl_setopt($curl, CURLOPT_UNIX_SOCKET_PATH, '/var/lib/rspamd/rspamd.sock');
  2125. if (!is_numeric($lines)) {
  2126. list ($from, $to) = explode('-', $lines);
  2127. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?from=" . intval($from) . "&to=" . intval($to));
  2128. }
  2129. else {
  2130. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?to=" . intval($lines));
  2131. }
  2132. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2133. $history = curl_exec($curl);
  2134. if (!curl_errno($curl)) {
  2135. $data_array = json_decode($history, true);
  2136. curl_close($curl);
  2137. return $data_array['rows'];
  2138. }
  2139. curl_close($curl);
  2140. return false;
  2141. }
  2142. if ($application == "rspamd-stats") {
  2143. $curl = curl_init();
  2144. curl_setopt($curl, CURLOPT_UNIX_SOCKET_PATH, '/var/lib/rspamd/rspamd.sock');
  2145. curl_setopt($curl, CURLOPT_URL,"http://rspamd/stat");
  2146. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2147. $stats = curl_exec($curl);
  2148. if (!curl_errno($curl)) {
  2149. $data_array = json_decode($stats, true);
  2150. curl_close($curl);
  2151. return $data_array;
  2152. }
  2153. curl_close($curl);
  2154. return false;
  2155. }
  2156. return false;
  2157. }
  2158. function getGUID() {
  2159. if (function_exists('com_create_guid')) {
  2160. return com_create_guid();
  2161. }
  2162. mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
  2163. $charid = strtoupper(md5(uniqid(rand(), true)));
  2164. $hyphen = chr(45);// "-"
  2165. return substr($charid, 0, 8).$hyphen
  2166. .substr($charid, 8, 4).$hyphen
  2167. .substr($charid,12, 4).$hyphen
  2168. .substr($charid,16, 4).$hyphen
  2169. .substr($charid,20,12);
  2170. }
  2171. function solr_status() {
  2172. $curl = curl_init();
  2173. $endpoint = 'http://solr:8983/solr/admin/cores';
  2174. $params = array(
  2175. 'action' => 'STATUS',
  2176. 'core' => 'dovecot-fts',
  2177. 'indexInfo' => 'true'
  2178. );
  2179. $url = $endpoint . '?' . http_build_query($params);
  2180. curl_setopt($curl, CURLOPT_URL, $url);
  2181. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  2182. curl_setopt($curl, CURLOPT_POST, 0);
  2183. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  2184. $response_core = curl_exec($curl);
  2185. if ($response_core === false) {
  2186. $err = curl_error($curl);
  2187. curl_close($curl);
  2188. return false;
  2189. }
  2190. else {
  2191. curl_close($curl);
  2192. $curl = curl_init();
  2193. $status_core = json_decode($response_core, true);
  2194. $url = 'http://solr:8983/solr/admin/info/system';
  2195. curl_setopt($curl, CURLOPT_URL, $url);
  2196. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  2197. curl_setopt($curl, CURLOPT_POST, 0);
  2198. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  2199. $response_sysinfo = curl_exec($curl);
  2200. if ($response_sysinfo === false) {
  2201. $err = curl_error($curl);
  2202. curl_close($curl);
  2203. return false;
  2204. }
  2205. else {
  2206. curl_close($curl);
  2207. $status_sysinfo = json_decode($response_sysinfo, true);
  2208. $status = array_merge($status_core, $status_sysinfo);
  2209. return (!empty($status['status']['dovecot-fts']) && !empty($status['jvm']['memory'])) ? $status : false;
  2210. }
  2211. return (!empty($status['status']['dovecot-fts'])) ? $status['status']['dovecot-fts'] : false;
  2212. }
  2213. return false;
  2214. }
  2215. function cleanupJS($ignore = '', $folder = '/tmp/*.js') {
  2216. $now = time();
  2217. foreach (glob($folder) as $filename) {
  2218. if(strpos($filename, $ignore) !== false) {
  2219. continue;
  2220. }
  2221. if (is_file($filename)) {
  2222. if ($now - filemtime($filename) >= 60 * 60) {
  2223. unlink($filename);
  2224. }
  2225. }
  2226. }
  2227. }
  2228. function cleanupCSS($ignore = '', $folder = '/tmp/*.css') {
  2229. $now = time();
  2230. foreach (glob($folder) as $filename) {
  2231. if(strpos($filename, $ignore) !== false) {
  2232. continue;
  2233. }
  2234. if (is_file($filename)) {
  2235. if ($now - filemtime($filename) >= 60 * 60) {
  2236. unlink($filename);
  2237. }
  2238. }
  2239. }
  2240. }
  2241. ?>