functions.inc.php 90 KB

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