2
0

functions.inc.php 83 KB

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