functions.inc.php 93 KB

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