functions.inc.php 86 KB

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