functions.inc.php 89 KB

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