functions.inc.php 89 KB

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