functions.inc.php 87 KB

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