functions.inc.php 77 KB

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