functions.inc.php 108 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939
  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. // generate random password for sogo to deny direct login
  819. $random_password = base64_encode(openssl_random_pseudo_bytes(24));
  820. $random_salt = base64_encode(openssl_random_pseudo_bytes(16));
  821. $random_hash = '{SSHA256}' . base64_encode(hash('sha256', base64_decode($password) . $salt, true) . $salt);
  822. $subquery = "GROUP BY mailbox.username";
  823. if ($mailbox_exists) {
  824. $subquery = "AND mailbox.username = :mailbox";
  825. }
  826. $query = "INSERT INTO _sogo_static_view (`c_uid`, `domain`, `c_name`, `c_password`, `c_cn`, `mail`, `aliases`, `ad_aliases`, `ext_acl`, `kind`, `multiple_bookings`)
  827. SELECT
  828. mailbox.username,
  829. mailbox.domain,
  830. mailbox.username,
  831. :random_hash,
  832. mailbox.name,
  833. mailbox.username,
  834. IFNULL(GROUP_CONCAT(ga.aliases ORDER BY ga.aliases SEPARATOR ' '), ''),
  835. IFNULL(gda.ad_alias, ''),
  836. IFNULL(external_acl.send_as_acl, ''),
  837. mailbox.kind,
  838. mailbox.multiple_bookings
  839. FROM
  840. mailbox
  841. LEFT OUTER JOIN grouped_mail_aliases ga ON ga.username REGEXP CONCAT('(^|,)', mailbox.username, '($|,)')
  842. LEFT OUTER JOIN grouped_domain_alias_address gda ON gda.username = mailbox.username
  843. LEFT OUTER JOIN grouped_sender_acl_external external_acl ON external_acl.username = mailbox.username
  844. WHERE
  845. mailbox.active = '1'
  846. $subquery
  847. ON DUPLICATE KEY UPDATE
  848. `domain` = VALUES(`domain`),
  849. `c_name` = VALUES(`c_name`),
  850. `c_password` = VALUES(`c_password`),
  851. `c_cn` = VALUES(`c_cn`),
  852. `mail` = VALUES(`mail`),
  853. `aliases` = VALUES(`aliases`),
  854. `ad_aliases` = VALUES(`ad_aliases`),
  855. `ext_acl` = VALUES(`ext_acl`),
  856. `kind` = VALUES(`kind`),
  857. `multiple_bookings` = VALUES(`multiple_bookings`)";
  858. if ($mailbox_exists) {
  859. $stmt = $pdo->prepare($query);
  860. $stmt->execute(array(
  861. ':random_hash' => $random_hash,
  862. ':mailbox' => $mailbox
  863. ));
  864. } else {
  865. $stmt = $pdo->prepare($query);
  866. $stmt->execute(array(
  867. ':random_hash' => $random_hash
  868. ));
  869. }
  870. $stmt = $pdo->query("DELETE FROM _sogo_static_view WHERE `c_uid` NOT IN (SELECT `username` FROM `mailbox` WHERE `active` = '1');");
  871. flush_memcached();
  872. }
  873. function edit_user_account($_data) {
  874. global $lang;
  875. global $pdo;
  876. $_data_log = $_data;
  877. !isset($_data_log['user_new_pass']) ?: $_data_log['user_new_pass'] = '*';
  878. !isset($_data_log['user_new_pass2']) ?: $_data_log['user_new_pass2'] = '*';
  879. !isset($_data_log['user_old_pass']) ?: $_data_log['user_old_pass'] = '*';
  880. $username = $_SESSION['mailcow_cc_username'];
  881. $role = $_SESSION['mailcow_cc_role'];
  882. $password_old = $_data['user_old_pass'];
  883. if (filter_var($username, FILTER_VALIDATE_EMAIL === false) || $role != 'user') {
  884. $_SESSION['return'][] = array(
  885. 'type' => 'danger',
  886. 'log' => array(__FUNCTION__, $_data_log),
  887. 'msg' => 'access_denied'
  888. );
  889. return false;
  890. }
  891. $stmt = $pdo->prepare("SELECT `password` FROM `mailbox`
  892. WHERE `kind` NOT REGEXP 'location|thing|group'
  893. AND `username` = :user AND authsource = 'mailcow'");
  894. $stmt->execute(array(':user' => $username));
  895. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  896. if (!verify_hash($row['password'], $password_old)) {
  897. $_SESSION['return'][] = array(
  898. 'type' => 'danger',
  899. 'log' => array(__FUNCTION__, $_data_log),
  900. 'msg' => 'access_denied'
  901. );
  902. return false;
  903. }
  904. if (!empty($_data['user_new_pass']) && !empty($_data['user_new_pass2'])) {
  905. $password_new = $_data['user_new_pass'];
  906. $password_new2 = $_data['user_new_pass2'];
  907. if (password_check($password_new, $password_new2) !== true) {
  908. return false;
  909. }
  910. $password_hashed = hash_password($password_new);
  911. $stmt = $pdo->prepare("UPDATE `mailbox` SET `password` = :password_hashed,
  912. `attributes` = JSON_SET(`attributes`, '$.force_pw_update', '0'),
  913. `attributes` = JSON_SET(`attributes`, '$.passwd_update', NOW())
  914. WHERE `username` = :username AND authsource = 'mailcow'");
  915. $stmt->execute(array(
  916. ':password_hashed' => $password_hashed,
  917. ':username' => $username
  918. ));
  919. }
  920. update_sogo_static_view();
  921. $_SESSION['return'][] = array(
  922. 'type' => 'success',
  923. 'log' => array(__FUNCTION__, $_data_log),
  924. 'msg' => array('mailbox_modified', htmlspecialchars($username))
  925. );
  926. }
  927. function user_get_alias_details($username) {
  928. global $pdo;
  929. global $lang;
  930. $data['direct_aliases'] = array();
  931. $data['shared_aliases'] = array();
  932. if ($_SESSION['mailcow_cc_role'] == "user") {
  933. $username = $_SESSION['mailcow_cc_username'];
  934. }
  935. if (!filter_var($username, FILTER_VALIDATE_EMAIL)) {
  936. return false;
  937. }
  938. if (!hasMailboxObjectAccess($username, $_SESSION['mailcow_cc_role'], $username)) {
  939. return false;
  940. }
  941. $data['address'] = $username;
  942. $stmt = $pdo->prepare("SELECT `address` AS `shared_aliases`, `public_comment` FROM `alias`
  943. WHERE `goto` REGEXP :username_goto
  944. AND `address` NOT LIKE '@%'
  945. AND `goto` != :username_goto2
  946. AND `address` != :username_address");
  947. $stmt->execute(array(
  948. ':username_goto' => '(^|,)'.$username.'($|,)',
  949. ':username_goto2' => $username,
  950. ':username_address' => $username
  951. ));
  952. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  953. while ($row = array_shift($run)) {
  954. $data['shared_aliases'][$row['shared_aliases']]['public_comment'] = htmlspecialchars($row['public_comment']);
  955. //$data['shared_aliases'][] = $row['shared_aliases'];
  956. }
  957. $stmt = $pdo->prepare("SELECT `address` AS `direct_aliases`, `public_comment` FROM `alias`
  958. WHERE `goto` = :username_goto
  959. AND `address` NOT LIKE '@%'
  960. AND `address` != :username_address");
  961. $stmt->execute(
  962. array(
  963. ':username_goto' => $username,
  964. ':username_address' => $username
  965. ));
  966. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  967. while ($row = array_shift($run)) {
  968. $data['direct_aliases'][$row['direct_aliases']]['public_comment'] = htmlspecialchars($row['public_comment']);
  969. }
  970. $stmt = $pdo->prepare("SELECT CONCAT(local_part, '@', alias_domain) AS `ad_alias`, `alias_domain` FROM `mailbox`
  971. LEFT OUTER JOIN `alias_domain` on `target_domain` = `domain`
  972. WHERE `username` = :username ;");
  973. $stmt->execute(array(':username' => $username));
  974. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  975. while ($row = array_shift($run)) {
  976. if (empty($row['ad_alias'])) {
  977. continue;
  978. }
  979. $data['direct_aliases'][$row['ad_alias']]['public_comment'] = $lang['add']['alias_domain'];
  980. $data['alias_domains'][] = $row['alias_domain'];
  981. }
  982. $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 '@%';");
  983. $stmt->execute(array(':username' => $username));
  984. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  985. while ($row = array_shift($run)) {
  986. $data['aliases_also_send_as'] = $row['send_as'];
  987. }
  988. $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 '@%';");
  989. $stmt->execute(array(':username' => $username));
  990. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  991. while ($row = array_shift($run)) {
  992. $data['aliases_send_as_all'] = $row['send_as'];
  993. }
  994. $stmt = $pdo->prepare("SELECT IFNULL(GROUP_CONCAT(`address` SEPARATOR ', '), '') as `address` FROM `alias` WHERE `goto` REGEXP :username AND `address` LIKE '@%';");
  995. $stmt->execute(array(':username' => '(^|,)'.$username.'($|,)'));
  996. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  997. while ($row = array_shift($run)) {
  998. $data['is_catch_all'] = $row['address'];
  999. }
  1000. return $data;
  1001. }
  1002. function is_valid_domain_name($domain_name) {
  1003. if (empty($domain_name)) {
  1004. return false;
  1005. }
  1006. $domain_name = idn_to_ascii($domain_name, 0, INTL_IDNA_VARIANT_UTS46);
  1007. return (preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $domain_name)
  1008. && preg_match("/^.{1,253}$/", $domain_name)
  1009. && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $domain_name));
  1010. }
  1011. function set_tfa($_data) {
  1012. global $pdo;
  1013. global $yubi;
  1014. global $tfa;
  1015. $_data_log = $_data;
  1016. $access_denied = null;
  1017. !isset($_data_log['confirm_password']) ?: $_data_log['confirm_password'] = '*';
  1018. $username = $_SESSION['mailcow_cc_username'];
  1019. // check for empty user and role
  1020. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) $access_denied = true;
  1021. // check admin confirm password
  1022. if ($access_denied === null) {
  1023. $stmt = $pdo->prepare("SELECT `password` FROM `admin`
  1024. WHERE `username` = :username");
  1025. $stmt->execute(array(':username' => $username));
  1026. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1027. if ($row) {
  1028. if (!verify_hash($row['password'], $_data["confirm_password"])) $access_denied = true;
  1029. else $access_denied = false;
  1030. }
  1031. }
  1032. // check mailbox confirm password
  1033. if ($access_denied === null) {
  1034. $stmt = $pdo->prepare("SELECT `password` FROM `mailbox`
  1035. WHERE `username` = :username");
  1036. $stmt->execute(array(':username' => $username));
  1037. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1038. if ($row) {
  1039. if (!verify_hash($row['password'], $_data["confirm_password"])) $access_denied = true;
  1040. else $access_denied = false;
  1041. }
  1042. }
  1043. // set access_denied error
  1044. if ($access_denied){
  1045. $_SESSION['return'][] = array(
  1046. 'type' => 'danger',
  1047. 'log' => array(__FUNCTION__, $_data_log),
  1048. 'msg' => 'access_denied'
  1049. );
  1050. return false;
  1051. }
  1052. switch ($_data["tfa_method"]) {
  1053. case "yubi_otp":
  1054. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  1055. $yubico_id = $_data['yubico_id'];
  1056. $yubico_key = $_data['yubico_key'];
  1057. $yubi = new Auth_Yubico($yubico_id, $yubico_key);
  1058. if (!$yubi) {
  1059. $_SESSION['return'][] = array(
  1060. 'type' => 'danger',
  1061. 'log' => array(__FUNCTION__, $_data_log),
  1062. 'msg' => 'access_denied'
  1063. );
  1064. return false;
  1065. }
  1066. if (!ctype_alnum($_data["otp_token"]) || strlen($_data["otp_token"]) != 44) {
  1067. $_SESSION['return'][] = array(
  1068. 'type' => 'danger',
  1069. 'log' => array(__FUNCTION__, $_data_log),
  1070. 'msg' => 'tfa_token_invalid'
  1071. );
  1072. return false;
  1073. }
  1074. $yauth = $yubi->verify($_data["otp_token"]);
  1075. if (PEAR::isError($yauth)) {
  1076. $_SESSION['return'][] = array(
  1077. 'type' => 'danger',
  1078. 'log' => array(__FUNCTION__, $_data_log),
  1079. 'msg' => array('yotp_verification_failed', $yauth->getMessage())
  1080. );
  1081. return false;
  1082. }
  1083. try {
  1084. // We could also do a modhex translation here
  1085. $yubico_modhex_id = substr($_data["otp_token"], 0, 12);
  1086. $stmt = $pdo->prepare("DELETE FROM `tfa`
  1087. WHERE `username` = :username
  1088. AND (`authmech` = 'yubi_otp' AND `secret` LIKE :modhex)");
  1089. $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id));
  1090. $stmt = $pdo->prepare("INSERT INTO `tfa` (`key_id`, `username`, `authmech`, `active`, `secret`) VALUES
  1091. (:key_id, :username, 'yubi_otp', '1', :secret)");
  1092. $stmt->execute(array(':key_id' => $key_id, ':username' => $username, ':secret' => $yubico_id . ':' . $yubico_key . ':' . $yubico_modhex_id));
  1093. }
  1094. catch (PDOException $e) {
  1095. $_SESSION['return'][] = array(
  1096. 'type' => 'danger',
  1097. 'log' => array(__FUNCTION__, $_data_log),
  1098. 'msg' => array('mysql_error', $e)
  1099. );
  1100. return false;
  1101. }
  1102. $_SESSION['return'][] = array(
  1103. 'type' => 'success',
  1104. 'log' => array(__FUNCTION__, $_data_log),
  1105. 'msg' => array('object_modified', htmlspecialchars($username))
  1106. );
  1107. break;
  1108. case "totp":
  1109. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  1110. if ($tfa->verifyCode($_POST['totp_secret'], $_POST['totp_confirm_token']) === true) {
  1111. //$stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
  1112. //$stmt->execute(array(':username' => $username));
  1113. $stmt = $pdo->prepare("INSERT INTO `tfa` (`username`, `key_id`, `authmech`, `secret`, `active`) VALUES (?, ?, 'totp', ?, '1')");
  1114. $stmt->execute(array($username, $key_id, $_POST['totp_secret']));
  1115. $_SESSION['return'][] = array(
  1116. 'type' => 'success',
  1117. 'log' => array(__FUNCTION__, $_data_log),
  1118. 'msg' => array('object_modified', $username)
  1119. );
  1120. }
  1121. else {
  1122. $_SESSION['return'][] = array(
  1123. 'type' => 'danger',
  1124. 'log' => array(__FUNCTION__, $_data_log),
  1125. 'msg' => 'totp_verification_failed'
  1126. );
  1127. }
  1128. break;
  1129. case "webauthn":
  1130. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  1131. $stmt = $pdo->prepare("INSERT INTO `tfa` (`username`, `key_id`, `authmech`, `keyHandle`, `publicKey`, `certificate`, `counter`, `active`)
  1132. VALUES (?, ?, 'webauthn', ?, ?, ?, ?, '1')");
  1133. $stmt->execute(array(
  1134. $username,
  1135. $key_id,
  1136. base64_encode($_data['registration']->credentialId),
  1137. $_data['registration']->credentialPublicKey,
  1138. $_data['registration']->certificate,
  1139. 0
  1140. ));
  1141. $_SESSION['return'][] = array(
  1142. 'type' => 'success',
  1143. 'log' => array(__FUNCTION__, $_data_log),
  1144. 'msg' => array('object_modified', $username)
  1145. );
  1146. break;
  1147. case "none":
  1148. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
  1149. $stmt->execute(array(':username' => $username));
  1150. $_SESSION['return'][] = array(
  1151. 'type' => 'success',
  1152. 'log' => array(__FUNCTION__, $_data_log),
  1153. 'msg' => array('object_modified', htmlspecialchars($username))
  1154. );
  1155. break;
  1156. }
  1157. }
  1158. function fido2($_data) {
  1159. global $pdo;
  1160. $_data_log = $_data;
  1161. // Not logging registration data, only actions
  1162. // Silent errors for "get" requests
  1163. switch ($_data["action"]) {
  1164. case "register":
  1165. $username = $_SESSION['mailcow_cc_username'];
  1166. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1167. $_SESSION['return'][] = array(
  1168. 'type' => 'danger',
  1169. 'log' => array(__FUNCTION__, $_data["action"]),
  1170. 'msg' => 'access_denied'
  1171. );
  1172. return false;
  1173. }
  1174. $stmt = $pdo->prepare("INSERT INTO `fido2` (`username`, `rpId`, `credentialPublicKey`, `certificateChain`, `certificate`, `certificateIssuer`, `certificateSubject`, `signatureCounter`, `AAGUID`, `credentialId`)
  1175. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
  1176. $stmt->execute(array(
  1177. $username,
  1178. $_data['registration']->rpId,
  1179. $_data['registration']->credentialPublicKey,
  1180. $_data['registration']->certificateChain,
  1181. $_data['registration']->certificate,
  1182. $_data['registration']->certificateIssuer,
  1183. $_data['registration']->certificateSubject,
  1184. $_data['registration']->signatureCounter,
  1185. $_data['registration']->AAGUID,
  1186. $_data['registration']->credentialId)
  1187. );
  1188. $_SESSION['return'][] = array(
  1189. 'type' => 'success',
  1190. 'log' => array(__FUNCTION__, $_data["action"]),
  1191. 'msg' => array('object_modified', $username)
  1192. );
  1193. break;
  1194. case "get_user_cids":
  1195. // Used to exclude existing CredentialIds while registering
  1196. $username = $_SESSION['mailcow_cc_username'];
  1197. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1198. return false;
  1199. }
  1200. $stmt = $pdo->prepare("SELECT `credentialId` FROM `fido2` WHERE `username` = :username");
  1201. $stmt->execute(array(':username' => $username));
  1202. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1203. while($row = array_shift($rows)) {
  1204. $cids[] = $row['credentialId'];
  1205. }
  1206. return $cids;
  1207. break;
  1208. case "get_all_cids":
  1209. // Only needed when using fido2 with username
  1210. $stmt = $pdo->query("SELECT `credentialId` FROM `fido2`");
  1211. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1212. while($row = array_shift($rows)) {
  1213. $cids[] = $row['credentialId'];
  1214. }
  1215. return $cids;
  1216. break;
  1217. case "get_by_b64cid":
  1218. if (!isset($_data['cid']) || empty($_data['cid'])) {
  1219. return false;
  1220. }
  1221. $stmt = $pdo->prepare("SELECT `certificateSubject`, `username`, `credentialPublicKey`, SHA2(`credentialId`, 256) AS `cid` FROM `fido2` WHERE `credentialId` = :cid");
  1222. $stmt->execute(array(':cid' => base64_decode($_data['cid'])));
  1223. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1224. if (empty($row) || empty($row['credentialPublicKey']) || empty($row['username'])) {
  1225. return false;
  1226. }
  1227. $data['pub_key'] = $row['credentialPublicKey'];
  1228. $data['username'] = $row['username'];
  1229. $data['subject'] = $row['certificateSubject'];
  1230. $data['cid'] = $row['cid'];
  1231. return $data;
  1232. break;
  1233. case "get_friendly_names":
  1234. $username = $_SESSION['mailcow_cc_username'];
  1235. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1236. return false;
  1237. }
  1238. $stmt = $pdo->prepare("SELECT SHA2(`credentialId`, 256) AS `cid`, `created`, `certificateSubject`, `friendlyName` FROM `fido2` WHERE `username` = :username");
  1239. $stmt->execute(array(':username' => $username));
  1240. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1241. while($row = array_shift($rows)) {
  1242. $fns[] = array(
  1243. "subject" => (empty($row['certificateSubject']) ? 'Unknown (' . $row['created'] . ')' : $row['certificateSubject']),
  1244. "fn" => $row['friendlyName'],
  1245. "cid" => $row['cid']
  1246. );
  1247. }
  1248. return $fns;
  1249. break;
  1250. case "unset_fido2_key":
  1251. $username = $_SESSION['mailcow_cc_username'];
  1252. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1253. $_SESSION['return'][] = array(
  1254. 'type' => 'danger',
  1255. 'log' => array(__FUNCTION__, $_data["action"]),
  1256. 'msg' => 'access_denied'
  1257. );
  1258. return false;
  1259. }
  1260. $stmt = $pdo->prepare("DELETE FROM `fido2` WHERE `username` = :username AND SHA2(`credentialId`, 256) = :cid");
  1261. $stmt->execute(array(
  1262. ':username' => $username,
  1263. ':cid' => $_data['post_data']['unset_fido2_key']
  1264. ));
  1265. $_SESSION['return'][] = array(
  1266. 'type' => 'success',
  1267. 'log' => array(__FUNCTION__, $_data_log),
  1268. 'msg' => array('object_modified', htmlspecialchars($username))
  1269. );
  1270. break;
  1271. case "edit_fn":
  1272. $username = $_SESSION['mailcow_cc_username'];
  1273. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1274. $_SESSION['return'][] = array(
  1275. 'type' => 'danger',
  1276. 'log' => array(__FUNCTION__, $_data["action"]),
  1277. 'msg' => 'access_denied'
  1278. );
  1279. return false;
  1280. }
  1281. $stmt = $pdo->prepare("UPDATE `fido2` SET `friendlyName` = :friendlyName WHERE SHA2(`credentialId`, 256) = :cid AND `username` = :username");
  1282. $stmt->execute(array(
  1283. ':username' => $username,
  1284. ':friendlyName' => $_data['fido2_attrs']['fido2_fn'],
  1285. ':cid' => $_data['fido2_attrs']['fido2_cid']
  1286. ));
  1287. $_SESSION['return'][] = array(
  1288. 'type' => 'success',
  1289. 'log' => array(__FUNCTION__, $_data_log),
  1290. 'msg' => array('object_modified', htmlspecialchars($username))
  1291. );
  1292. break;
  1293. }
  1294. }
  1295. function unset_tfa_key($_data) {
  1296. // Can only unset own keys
  1297. // Needs at least one key left
  1298. global $pdo;
  1299. global $lang;
  1300. $_data_log = $_data;
  1301. $access_denied = null;
  1302. $id = intval($_data['unset_tfa_key']);
  1303. $username = $_SESSION['mailcow_cc_username'];
  1304. // check for empty user and role
  1305. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) $access_denied = true;
  1306. try {
  1307. if (!is_numeric($id)) $access_denied = true;
  1308. // set access_denied error
  1309. if ($access_denied){
  1310. $_SESSION['return'][] = array(
  1311. 'type' => 'danger',
  1312. 'log' => array(__FUNCTION__, $_data_log),
  1313. 'msg' => 'access_denied'
  1314. );
  1315. return false;
  1316. }
  1317. // check if it's last key
  1318. $stmt = $pdo->prepare("SELECT COUNT(*) AS `keys` FROM `tfa`
  1319. WHERE `username` = :username AND `active` = '1'");
  1320. $stmt->execute(array(':username' => $username));
  1321. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1322. if ($row['keys'] == "1") {
  1323. $_SESSION['return'][] = array(
  1324. 'type' => 'danger',
  1325. 'log' => array(__FUNCTION__, $_data_log),
  1326. 'msg' => 'last_key'
  1327. );
  1328. return false;
  1329. }
  1330. // delete key
  1331. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username AND `id` = :id");
  1332. $stmt->execute(array(':username' => $username, ':id' => $id));
  1333. $_SESSION['return'][] = array(
  1334. 'type' => 'success',
  1335. 'log' => array(__FUNCTION__, $_data_log),
  1336. 'msg' => array('object_modified', $username)
  1337. );
  1338. }
  1339. catch (PDOException $e) {
  1340. $_SESSION['return'][] = array(
  1341. 'type' => 'danger',
  1342. 'log' => array(__FUNCTION__, $_data_log),
  1343. 'msg' => array('mysql_error', $e)
  1344. );
  1345. return false;
  1346. }
  1347. }
  1348. function get_tfa($username = null, $id = null) {
  1349. global $pdo;
  1350. if (isset($_SESSION['mailcow_cc_username'])) {
  1351. $username = $_SESSION['mailcow_cc_username'];
  1352. }
  1353. elseif (empty($username)) {
  1354. return false;
  1355. }
  1356. if (!isset($id)){
  1357. // fetch all tfa methods - just get information about possible authenticators
  1358. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `authmech` FROM `tfa`
  1359. WHERE `username` = :username AND `active` = '1'");
  1360. $stmt->execute(array(':username' => $username));
  1361. $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1362. // no tfa methods found
  1363. if (count($results) == 0) {
  1364. $data['name'] = 'none';
  1365. $data['pretty'] = "-";
  1366. $data['additional'] = array();
  1367. return $data;
  1368. }
  1369. $data['additional'] = $results;
  1370. return $data;
  1371. } else {
  1372. // fetch specific authenticator details by id
  1373. $stmt = $pdo->prepare("SELECT * FROM `tfa`
  1374. WHERE `username` = :username AND `id` = :id AND `active` = '1'");
  1375. $stmt->execute(array(':username' => $username, ':id' => $id));
  1376. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1377. if (isset($row["authmech"])) {
  1378. switch ($row["authmech"]) {
  1379. case "yubi_otp":
  1380. $data['name'] = "yubi_otp";
  1381. $data['pretty'] = "Yubico OTP";
  1382. $stmt = $pdo->prepare("SELECT `id`, `key_id`, RIGHT(`secret`, 12) AS 'modhex' FROM `tfa` WHERE `authmech` = 'yubi_otp' AND `username` = :username AND `id` = :id");
  1383. $stmt->execute(array(
  1384. ':username' => $username,
  1385. ':id' => $id
  1386. ));
  1387. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1388. while($row = array_shift($rows)) {
  1389. $data['additional'][] = $row;
  1390. }
  1391. return $data;
  1392. break;
  1393. // u2f - deprecated, should be removed
  1394. case "u2f":
  1395. $data['name'] = "u2f";
  1396. $data['pretty'] = "Fido U2F";
  1397. $stmt = $pdo->prepare("SELECT `id`, `key_id` FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username AND `id` = :id");
  1398. $stmt->execute(array(
  1399. ':username' => $username,
  1400. ':id' => $id
  1401. ));
  1402. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1403. while($row = array_shift($rows)) {
  1404. $data['additional'][] = $row;
  1405. }
  1406. return $data;
  1407. break;
  1408. case "hotp":
  1409. $data['name'] = "hotp";
  1410. $data['pretty'] = "HMAC-based OTP";
  1411. return $data;
  1412. break;
  1413. case "totp":
  1414. $data['name'] = "totp";
  1415. $data['pretty'] = "Time-based OTP";
  1416. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `secret` FROM `tfa` WHERE `authmech` = 'totp' AND `username` = :username AND `id` = :id");
  1417. $stmt->execute(array(
  1418. ':username' => $username,
  1419. ':id' => $id
  1420. ));
  1421. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1422. while($row = array_shift($rows)) {
  1423. $data['additional'][] = $row;
  1424. }
  1425. return $data;
  1426. break;
  1427. case "webauthn":
  1428. $data['name'] = "webauthn";
  1429. $data['pretty'] = "WebAuthn";
  1430. $stmt = $pdo->prepare("SELECT `id`, `key_id` FROM `tfa` WHERE `authmech` = 'webauthn' AND `username` = :username AND `id` = :id");
  1431. $stmt->execute(array(
  1432. ':username' => $username,
  1433. ':id' => $id
  1434. ));
  1435. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1436. while($row = array_shift($rows)) {
  1437. $data['additional'][] = $row;
  1438. }
  1439. return $data;
  1440. break;
  1441. default:
  1442. $data['name'] = 'none';
  1443. $data['pretty'] = "-";
  1444. return $data;
  1445. break;
  1446. }
  1447. }
  1448. else {
  1449. $data['name'] = 'none';
  1450. $data['pretty'] = "-";
  1451. return $data;
  1452. }
  1453. }
  1454. }
  1455. function verify_tfa_login($username, $_data) {
  1456. global $pdo;
  1457. global $yubi;
  1458. global $u2f;
  1459. global $tfa;
  1460. global $WebAuthn;
  1461. if ($_data['tfa_method'] != 'u2f'){
  1462. switch ($_data["tfa_method"]) {
  1463. case "yubi_otp":
  1464. if (!ctype_alnum($_data['token']) || strlen($_data['token']) != 44) {
  1465. $_SESSION['return'][] = array(
  1466. 'type' => 'danger',
  1467. 'log' => array(__FUNCTION__, $username, '*'),
  1468. 'msg' => array('yotp_verification_failed', 'token length error')
  1469. );
  1470. return false;
  1471. }
  1472. $yubico_modhex_id = substr($_data['token'], 0, 12);
  1473. $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
  1474. WHERE `username` = :username
  1475. AND `authmech` = 'yubi_otp'
  1476. AND `active` = '1'
  1477. AND `secret` LIKE :modhex");
  1478. $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id));
  1479. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1480. $yubico_auth = explode(':', $row['secret']);
  1481. $yubi = new Auth_Yubico($yubico_auth[0], $yubico_auth[1]);
  1482. $yauth = $yubi->verify($_data['token']);
  1483. if (PEAR::isError($yauth)) {
  1484. $_SESSION['return'][] = array(
  1485. 'type' => 'danger',
  1486. 'log' => array(__FUNCTION__, $username, '*'),
  1487. 'msg' => array('yotp_verification_failed', $yauth->getMessage())
  1488. );
  1489. return false;
  1490. }
  1491. else {
  1492. $_SESSION['tfa_id'] = $row['id'];
  1493. $_SESSION['return'][] = array(
  1494. 'type' => 'success',
  1495. 'log' => array(__FUNCTION__, $username, '*'),
  1496. 'msg' => 'verified_yotp_login'
  1497. );
  1498. return true;
  1499. }
  1500. $_SESSION['return'][] = array(
  1501. 'type' => 'danger',
  1502. 'log' => array(__FUNCTION__, $username, '*'),
  1503. 'msg' => array('yotp_verification_failed', 'unknown')
  1504. );
  1505. return false;
  1506. break;
  1507. case "hotp":
  1508. return false;
  1509. break;
  1510. case "totp":
  1511. try {
  1512. $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
  1513. WHERE `username` = :username
  1514. AND `authmech` = 'totp'
  1515. AND `id` = :id
  1516. AND `active`='1'");
  1517. $stmt->execute(array(':username' => $username, ':id' => $_data['id']));
  1518. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1519. foreach ($rows as $row) {
  1520. if ($tfa->verifyCode($row['secret'], $_data['token']) === true) {
  1521. $_SESSION['tfa_id'] = $row['id'];
  1522. $_SESSION['return'][] = array(
  1523. 'type' => 'success',
  1524. 'log' => array(__FUNCTION__, $username, '*'),
  1525. 'msg' => 'verified_totp_login'
  1526. );
  1527. return true;
  1528. }
  1529. }
  1530. $_SESSION['return'][] = array(
  1531. 'type' => 'danger',
  1532. 'log' => array(__FUNCTION__, $username, '*'),
  1533. 'msg' => 'totp_verification_failed'
  1534. );
  1535. return false;
  1536. }
  1537. catch (PDOException $e) {
  1538. $_SESSION['return'][] = array(
  1539. 'type' => 'danger',
  1540. 'log' => array(__FUNCTION__, $username, '*'),
  1541. 'msg' => array('mysql_error', $e)
  1542. );
  1543. return false;
  1544. }
  1545. break;
  1546. case "webauthn":
  1547. $tokenData = json_decode($_data['token']);
  1548. $clientDataJSON = base64_decode($tokenData->clientDataJSON);
  1549. $authenticatorData = base64_decode($tokenData->authenticatorData);
  1550. $signature = base64_decode($tokenData->signature);
  1551. $id = base64_decode($tokenData->id);
  1552. $challenge = $_SESSION['challenge'];
  1553. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `keyHandle`, `username`, `publicKey` FROM `tfa` WHERE `id` = :id AND `active`='1'");
  1554. $stmt->execute(array(':id' => $_data['id']));
  1555. $process_webauthn = $stmt->fetch(PDO::FETCH_ASSOC);
  1556. if (empty($process_webauthn)){
  1557. $_SESSION['return'][] = array(
  1558. 'type' => 'danger',
  1559. 'log' => array(__FUNCTION__, $username, '*'),
  1560. 'msg' => array('webauthn_authenticator_failed')
  1561. );
  1562. return false;
  1563. }
  1564. if (empty($process_webauthn['publicKey']) || $process_webauthn['publicKey'] === false) {
  1565. $_SESSION['return'][] = array(
  1566. 'type' => 'danger',
  1567. 'log' => array(__FUNCTION__, $username, '*'),
  1568. 'msg' => array('webauthn_publickey_failed')
  1569. );
  1570. return false;
  1571. }
  1572. if ($process_webauthn['username'] != $_SESSION['pending_mailcow_cc_username']){
  1573. $_SESSION['return'][] = array(
  1574. 'type' => 'danger',
  1575. 'log' => array(__FUNCTION__, $username, '*'),
  1576. 'msg' => array('webauthn_username_failed')
  1577. );
  1578. return false;
  1579. }
  1580. try {
  1581. $WebAuthn->processGet($clientDataJSON, $authenticatorData, $signature, $process_webauthn['publicKey'], $challenge, null, $GLOBALS['WEBAUTHN_UV_FLAG_LOGIN'], $GLOBALS['WEBAUTHN_USER_PRESENT_FLAG']);
  1582. }
  1583. catch (Throwable $ex) {
  1584. $_SESSION['return'][] = array(
  1585. 'type' => 'danger',
  1586. 'log' => array(__FUNCTION__, $username, '*'),
  1587. 'msg' => array('webauthn_verification_failed', $ex->getMessage())
  1588. );
  1589. return false;
  1590. }
  1591. $stmt = $pdo->prepare("SELECT `superadmin` FROM `admin` WHERE `username` = :username");
  1592. $stmt->execute(array(':username' => $process_webauthn['username']));
  1593. $obj_props = $stmt->fetch(PDO::FETCH_ASSOC);
  1594. if ($obj_props['superadmin'] === 1) {
  1595. $_SESSION["mailcow_cc_role"] = "admin";
  1596. }
  1597. elseif ($obj_props['superadmin'] === 0) {
  1598. $_SESSION["mailcow_cc_role"] = "domainadmin";
  1599. }
  1600. else {
  1601. $stmt = $pdo->prepare("SELECT `username` FROM `mailbox` WHERE `username` = :username");
  1602. $stmt->execute(array(':username' => $process_webauthn['username']));
  1603. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1604. if (!empty($row['username'])) {
  1605. $_SESSION["mailcow_cc_role"] = "user";
  1606. } else {
  1607. $_SESSION['return'][] = array(
  1608. 'type' => 'danger',
  1609. 'log' => array(__FUNCTION__, $username, '*'),
  1610. 'msg' => array('webauthn_role_failed')
  1611. );
  1612. return false;
  1613. }
  1614. }
  1615. $_SESSION["mailcow_cc_username"] = $process_webauthn['username'];
  1616. $_SESSION['tfa_id'] = $process_webauthn['id'];
  1617. $_SESSION['authReq'] = null;
  1618. unset($_SESSION["challenge"]);
  1619. $_SESSION['return'][] = array(
  1620. 'type' => 'success',
  1621. 'log' => array("webauthn_login"),
  1622. 'msg' => array('logged_in_as', $process_webauthn['username'])
  1623. );
  1624. return true;
  1625. break;
  1626. default:
  1627. $_SESSION['return'][] = array(
  1628. 'type' => 'danger',
  1629. 'log' => array(__FUNCTION__, $username, '*'),
  1630. 'msg' => 'unknown_tfa_method'
  1631. );
  1632. return false;
  1633. break;
  1634. }
  1635. return false;
  1636. } else {
  1637. // delete old keys that used u2f
  1638. $stmt = $pdo->prepare("SELECT * FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username");
  1639. $stmt->execute(array(':username' => $username));
  1640. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1641. if (count($rows) == 0) return false;
  1642. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username");
  1643. $stmt->execute(array(':username' => $username));
  1644. return true;
  1645. }
  1646. }
  1647. function admin_api($access, $action, $data = null) {
  1648. global $pdo;
  1649. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1650. $_SESSION['return'][] = array(
  1651. 'type' => 'danger',
  1652. 'log' => array(__FUNCTION__),
  1653. 'msg' => 'access_denied'
  1654. );
  1655. return false;
  1656. }
  1657. if ($access !== "ro" && $access !== "rw") {
  1658. $_SESSION['return'][] = array(
  1659. 'type' => 'danger',
  1660. 'log' => array(__FUNCTION__),
  1661. 'msg' => 'invalid access type'
  1662. );
  1663. return false;
  1664. }
  1665. if ($action == "edit") {
  1666. $active = (!empty($data['active'])) ? 1 : 0;
  1667. $skip_ip_check = (isset($data['skip_ip_check'])) ? 1 : 0;
  1668. $allow_from = array();
  1669. if (isset($data['allow_from'])) {
  1670. $allow_from = array_map('trim', preg_split( "/( |,|;|\n)/", $data['allow_from']));
  1671. }
  1672. foreach ($allow_from as $key => $val) {
  1673. if (empty($val)) {
  1674. unset($allow_from[$key]);
  1675. continue;
  1676. }
  1677. if (valid_network($val) !== true) {
  1678. $_SESSION['return'][] = array(
  1679. 'type' => 'warning',
  1680. 'log' => array(__FUNCTION__, $data),
  1681. 'msg' => array('ip_invalid', htmlspecialchars($allow_from[$key]))
  1682. );
  1683. unset($allow_from[$key]);
  1684. continue;
  1685. }
  1686. }
  1687. $allow_from = implode(',', array_unique(array_filter($allow_from)));
  1688. if (empty($allow_from) && $skip_ip_check == 0) {
  1689. $_SESSION['return'][] = array(
  1690. 'type' => 'danger',
  1691. 'log' => array(__FUNCTION__, $data),
  1692. 'msg' => 'ip_list_empty'
  1693. );
  1694. return false;
  1695. }
  1696. $api_key = implode('-', array(
  1697. strtoupper(bin2hex(random_bytes(3))),
  1698. strtoupper(bin2hex(random_bytes(3))),
  1699. strtoupper(bin2hex(random_bytes(3))),
  1700. strtoupper(bin2hex(random_bytes(3))),
  1701. strtoupper(bin2hex(random_bytes(3)))
  1702. ));
  1703. $stmt = $pdo->query("SELECT `api_key` FROM `api` WHERE `access` = '" . $access . "'");
  1704. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  1705. if (empty($num_results)) {
  1706. $stmt = $pdo->prepare("INSERT INTO `api` (`api_key`, `skip_ip_check`, `active`, `allow_from`, `access`)
  1707. VALUES (:api_key, :skip_ip_check, :active, :allow_from, :access);");
  1708. $stmt->execute(array(
  1709. ':api_key' => $api_key,
  1710. ':skip_ip_check' => $skip_ip_check,
  1711. ':active' => $active,
  1712. ':allow_from' => $allow_from,
  1713. ':access' => $access
  1714. ));
  1715. }
  1716. else {
  1717. if ($skip_ip_check == 0) {
  1718. $stmt = $pdo->prepare("UPDATE `api` SET `skip_ip_check` = :skip_ip_check,
  1719. `active` = :active,
  1720. `allow_from` = :allow_from
  1721. WHERE `access` = :access;");
  1722. $stmt->execute(array(
  1723. ':active' => $active,
  1724. ':skip_ip_check' => $skip_ip_check,
  1725. ':allow_from' => $allow_from,
  1726. ':access' => $access
  1727. ));
  1728. }
  1729. else {
  1730. $stmt = $pdo->prepare("UPDATE `api` SET `skip_ip_check` = :skip_ip_check,
  1731. `active` = :active
  1732. WHERE `access` = :access;");
  1733. $stmt->execute(array(
  1734. ':active' => $active,
  1735. ':skip_ip_check' => $skip_ip_check,
  1736. ':access' => $access
  1737. ));
  1738. }
  1739. }
  1740. }
  1741. elseif ($action == "regen_key") {
  1742. $api_key = implode('-', array(
  1743. strtoupper(bin2hex(random_bytes(3))),
  1744. strtoupper(bin2hex(random_bytes(3))),
  1745. strtoupper(bin2hex(random_bytes(3))),
  1746. strtoupper(bin2hex(random_bytes(3))),
  1747. strtoupper(bin2hex(random_bytes(3)))
  1748. ));
  1749. $stmt = $pdo->prepare("UPDATE `api` SET `api_key` = :api_key WHERE `access` = :access");
  1750. $stmt->execute(array(
  1751. ':api_key' => $api_key,
  1752. ':access' => $access
  1753. ));
  1754. }
  1755. elseif ($action == "get") {
  1756. $stmt = $pdo->query("SELECT * FROM `api` WHERE `access` = '" . $access . "'");
  1757. $apidata = $stmt->fetch(PDO::FETCH_ASSOC);
  1758. if ($apidata !== false) {
  1759. $apidata['allow_from'] = str_replace(',', PHP_EOL, $apidata['allow_from']);
  1760. }
  1761. return $apidata;
  1762. }
  1763. $_SESSION['return'][] = array(
  1764. 'type' => 'success',
  1765. 'log' => array(__FUNCTION__, $data),
  1766. 'msg' => 'admin_api_modified'
  1767. );
  1768. }
  1769. function license($action, $data = null) {
  1770. global $pdo;
  1771. global $redis;
  1772. global $lang;
  1773. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1774. $_SESSION['return'][] = array(
  1775. 'type' => 'danger',
  1776. 'log' => array(__FUNCTION__),
  1777. 'msg' => 'access_denied'
  1778. );
  1779. return false;
  1780. }
  1781. switch ($action) {
  1782. case "verify":
  1783. // Keep result until revalidate button is pressed or session expired
  1784. $stmt = $pdo->query("SELECT `version` FROM `versions` WHERE `application` = 'GUID'");
  1785. $versions = $stmt->fetch(PDO::FETCH_ASSOC);
  1786. $post = array('guid' => $versions['version']);
  1787. $curl = curl_init('https://verify.mailcow.email');
  1788. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  1789. curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
  1790. curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
  1791. $response = curl_exec($curl);
  1792. curl_close($curl);
  1793. $json_return = json_decode($response, true);
  1794. if ($response && $json_return) {
  1795. if ($json_return['response'] === "ok") {
  1796. $_SESSION['gal']['valid'] = "true";
  1797. $_SESSION['gal']['c'] = $json_return['c'];
  1798. $_SESSION['gal']['s'] = $json_return['s'];
  1799. if ($json_return['m'] == 'NoMoore') {
  1800. $_SESSION['gal']['m'] = '🐄';
  1801. }
  1802. else {
  1803. $_SESSION['gal']['m'] = str_repeat('🐄', substr_count($json_return['m'], 'o'));
  1804. }
  1805. }
  1806. elseif ($json_return['response'] === "invalid") {
  1807. $_SESSION['gal']['valid'] = "false";
  1808. $_SESSION['gal']['c'] = $lang['mailbox']['no'];
  1809. $_SESSION['gal']['s'] = $lang['mailbox']['no'];
  1810. $_SESSION['gal']['m'] = $lang['mailbox']['no'];
  1811. }
  1812. }
  1813. else {
  1814. $_SESSION['gal']['valid'] = "false";
  1815. $_SESSION['gal']['c'] = $lang['danger']['temp_error'];
  1816. $_SESSION['gal']['s'] = $lang['danger']['temp_error'];
  1817. $_SESSION['gal']['m'] = $lang['danger']['temp_error'];
  1818. }
  1819. try {
  1820. // json_encode needs "true"/"false" instead of true/false, to not encode it to 0 or 1
  1821. $redis->Set('LICENSE_STATUS_CACHE', json_encode($_SESSION['gal']));
  1822. }
  1823. catch (RedisException $e) {
  1824. $_SESSION['return'][] = array(
  1825. 'type' => 'danger',
  1826. 'log' => array(__FUNCTION__, $_action, $_data_log),
  1827. 'msg' => array('redis_error', $e)
  1828. );
  1829. return false;
  1830. }
  1831. return $_SESSION['gal']['valid'];
  1832. break;
  1833. case "guid":
  1834. $stmt = $pdo->query("SELECT `version` FROM `versions` WHERE `application` = 'GUID'");
  1835. $versions = $stmt->fetch(PDO::FETCH_ASSOC);
  1836. return $versions['version'];
  1837. break;
  1838. }
  1839. }
  1840. function rspamd_ui($action, $data = null) {
  1841. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1842. $_SESSION['return'][] = array(
  1843. 'type' => 'danger',
  1844. 'log' => array(__FUNCTION__),
  1845. 'msg' => 'access_denied'
  1846. );
  1847. return false;
  1848. }
  1849. switch ($action) {
  1850. case "edit":
  1851. $rspamd_ui_pass = $data['rspamd_ui_pass'];
  1852. $rspamd_ui_pass2 = $data['rspamd_ui_pass2'];
  1853. if (empty($rspamd_ui_pass) || empty($rspamd_ui_pass2)) {
  1854. $_SESSION['return'][] = array(
  1855. 'type' => 'danger',
  1856. 'log' => array(__FUNCTION__, '*', '*'),
  1857. 'msg' => 'password_empty'
  1858. );
  1859. return false;
  1860. }
  1861. if ($rspamd_ui_pass != $rspamd_ui_pass2) {
  1862. $_SESSION['return'][] = array(
  1863. 'type' => 'danger',
  1864. 'log' => array(__FUNCTION__, '*', '*'),
  1865. 'msg' => 'password_mismatch'
  1866. );
  1867. return false;
  1868. }
  1869. if (strlen($rspamd_ui_pass) < 6) {
  1870. $_SESSION['return'][] = array(
  1871. 'type' => 'danger',
  1872. 'log' => array(__FUNCTION__, '*', '*'),
  1873. 'msg' => 'rspamd_ui_pw_length'
  1874. );
  1875. return false;
  1876. }
  1877. $docker_return = docker('post', 'rspamd-mailcow', 'exec', array('cmd' => 'rspamd', 'task' => 'worker_password', 'raw' => $rspamd_ui_pass), array('Content-Type: application/json'));
  1878. if ($docker_return_array = json_decode($docker_return, true)) {
  1879. if ($docker_return_array['type'] == 'success') {
  1880. $_SESSION['return'][] = array(
  1881. 'type' => 'success',
  1882. 'log' => array(__FUNCTION__, '*', '*'),
  1883. 'msg' => 'rspamd_ui_pw_set'
  1884. );
  1885. return true;
  1886. }
  1887. else {
  1888. $_SESSION['return'][] = array(
  1889. 'type' => $docker_return_array['type'],
  1890. 'log' => array(__FUNCTION__, '*', '*'),
  1891. 'msg' => $docker_return_array['msg']
  1892. );
  1893. return false;
  1894. }
  1895. }
  1896. else {
  1897. $_SESSION['return'][] = array(
  1898. 'type' => 'danger',
  1899. 'log' => array(__FUNCTION__, '*', '*'),
  1900. 'msg' => 'unknown'
  1901. );
  1902. return false;
  1903. }
  1904. break;
  1905. }
  1906. }
  1907. function cors($action, $data = null) {
  1908. global $redis;
  1909. switch ($action) {
  1910. case "edit":
  1911. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1912. $_SESSION['return'][] = array(
  1913. 'type' => 'danger',
  1914. 'log' => array(__FUNCTION__, $action, $data),
  1915. 'msg' => 'access_denied'
  1916. );
  1917. return false;
  1918. }
  1919. $allowed_origins = isset($data['allowed_origins']) ? $data['allowed_origins'] : array($_SERVER['SERVER_NAME']);
  1920. $allowed_origins = !is_array($allowed_origins) ? array_filter(array_map('trim', explode("\n", $allowed_origins))) : $allowed_origins;
  1921. foreach ($allowed_origins as $origin) {
  1922. if (!filter_var($origin, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) && $origin != '*') {
  1923. $_SESSION['return'][] = array(
  1924. 'type' => 'danger',
  1925. 'log' => array(__FUNCTION__, $action, $data),
  1926. 'msg' => 'cors_invalid_origin'
  1927. );
  1928. return false;
  1929. }
  1930. }
  1931. $allowed_methods = isset($data['allowed_methods']) ? $data['allowed_methods'] : array('GET', 'POST', 'PUT', 'DELETE');
  1932. $allowed_methods = !is_array($allowed_methods) ? array_map('trim', preg_split( "/( |,|;|\n)/", $allowed_methods)) : $allowed_methods;
  1933. $available_methods = array('GET', 'POST', 'PUT', 'DELETE');
  1934. foreach ($allowed_methods as $method) {
  1935. if (!in_array($method, $available_methods)) {
  1936. $_SESSION['return'][] = array(
  1937. 'type' => 'danger',
  1938. 'log' => array(__FUNCTION__, $action, $data),
  1939. 'msg' => 'cors_invalid_method'
  1940. );
  1941. return false;
  1942. }
  1943. }
  1944. try {
  1945. $redis->hMSet('CORS_SETTINGS', array(
  1946. 'allowed_origins' => implode(', ', $allowed_origins),
  1947. 'allowed_methods' => implode(', ', $allowed_methods)
  1948. ));
  1949. } catch (RedisException $e) {
  1950. $_SESSION['return'][] = array(
  1951. 'type' => 'danger',
  1952. 'log' => array(__FUNCTION__, $action, $data),
  1953. 'msg' => array('redis_error', $e)
  1954. );
  1955. return false;
  1956. }
  1957. $_SESSION['return'][] = array(
  1958. 'type' => 'success',
  1959. 'log' => array(__FUNCTION__, $action, $data),
  1960. 'msg' => 'cors_headers_edited'
  1961. );
  1962. return true;
  1963. break;
  1964. case "get":
  1965. try {
  1966. $cors_settings = $redis->hMGet('CORS_SETTINGS', array('allowed_origins', 'allowed_methods'));
  1967. } catch (RedisException $e) {
  1968. $_SESSION['return'][] = array(
  1969. 'type' => 'danger',
  1970. 'log' => array(__FUNCTION__, $action, $data),
  1971. 'msg' => array('redis_error', $e)
  1972. );
  1973. }
  1974. $cors_settings = !$cors_settings ? array('allowed_origins' => $_SERVER['SERVER_NAME'], 'allowed_methods' => 'GET, POST, PUT, DELETE') : $cors_settings;
  1975. $cors_settings['allowed_origins'] = empty($cors_settings['allowed_origins']) ? $_SERVER['SERVER_NAME'] : $cors_settings['allowed_origins'];
  1976. $cors_settings['allowed_methods'] = empty($cors_settings['allowed_methods']) ? 'GET, POST, PUT, DELETE, OPTION' : $cors_settings['allowed_methods'];
  1977. return $cors_settings;
  1978. break;
  1979. case "set_headers":
  1980. $cors_settings = cors('get');
  1981. // check if requested origin is in allowed origins
  1982. $allowed_origins = explode(', ', $cors_settings['allowed_origins']);
  1983. $cors_settings['allowed_origins'] = $allowed_origins[0];
  1984. if (in_array('*', $allowed_origins)){
  1985. $cors_settings['allowed_origins'] = '*';
  1986. } else if (in_array($_SERVER['HTTP_ORIGIN'], $allowed_origins)) {
  1987. $cors_settings['allowed_origins'] = $_SERVER['HTTP_ORIGIN'];
  1988. }
  1989. // always allow OPTIONS for preflight request
  1990. $cors_settings["allowed_methods"] = empty($cors_settings["allowed_methods"]) ? 'OPTIONS' : $cors_settings["allowed_methods"] . ', ' . 'OPTIONS';
  1991. header('Access-Control-Allow-Origin: ' . $cors_settings['allowed_origins']);
  1992. header('Access-Control-Allow-Methods: '. $cors_settings['allowed_methods']);
  1993. header('Access-Control-Allow-Headers: Accept, Content-Type, X-Api-Key, Origin');
  1994. // Access-Control settings requested, this is just a preflight request
  1995. if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS' &&
  1996. isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']) &&
  1997. isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
  1998. $allowed_methods = explode(', ', $cors_settings["allowed_methods"]);
  1999. if (in_array($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'], $allowed_methods, true))
  2000. // method allowed send 200 OK
  2001. http_response_code(200);
  2002. else
  2003. // method not allowed send 405 METHOD NOT ALLOWED
  2004. http_response_code(405);
  2005. exit;
  2006. }
  2007. break;
  2008. }
  2009. }
  2010. function getBaseURL() {
  2011. $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
  2012. $host = $_SERVER['HTTP_HOST'];
  2013. $base_url = $protocol . '://' . $host;
  2014. return $base_url;
  2015. }
  2016. function uuid4() {
  2017. $data = openssl_random_pseudo_bytes(16);
  2018. $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
  2019. $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
  2020. return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
  2021. }
  2022. function identity_provider($_action, $_data = null, $_extra = null) {
  2023. global $pdo;
  2024. $data_log = $_data;
  2025. if (isset($data_log['client_secret'])) $data_log['client_secret'] = '*';
  2026. if (isset($data_log['access_token'])) $data_log['access_token'] = '*';
  2027. switch ($_action) {
  2028. case 'get':
  2029. $settings = array();
  2030. $stmt = $pdo->prepare("SELECT * FROM `identity_provider`;");
  2031. $stmt->execute();
  2032. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2033. foreach($rows as $row){
  2034. if ($row["key"] == 'mappers' || $row["key"] == 'templates'){
  2035. $settings[$row["key"]] = json_decode($row["value"]);
  2036. } else {
  2037. $settings[$row["key"]] = $row["value"];
  2038. }
  2039. }
  2040. // return default client_scopes for generic-oidc if none is set
  2041. if ($settings["authsource"] == "generic-oidc" && empty($settings["client_scopes"])){
  2042. $settings["client_scopes"] = "openid profile email";
  2043. }
  2044. if ($_extra['hide_sensitive']){
  2045. $settings['client_secret'] = '';
  2046. $settings['access_token'] = '';
  2047. }
  2048. return $settings;
  2049. break;
  2050. case 'edit':
  2051. if ($_SESSION['mailcow_cc_role'] != "admin") {
  2052. $_SESSION['return'][] = array(
  2053. 'type' => 'danger',
  2054. 'log' => array(__FUNCTION__, $_action, $_data),
  2055. 'msg' => 'access_denied'
  2056. );
  2057. return false;
  2058. }
  2059. if (!isset($_data['authsource'])){
  2060. $_SESSION['return'][] = array(
  2061. 'type' => 'danger',
  2062. 'log' => array(__FUNCTION__, $_action, $data_log),
  2063. 'msg' => array('required_data_missing', '')
  2064. );
  2065. return false;
  2066. }
  2067. $available_authsources = array(
  2068. "keycloak",
  2069. "generic-oidc",
  2070. "ldap"
  2071. );
  2072. $_data['authsource'] = strtolower($_data['authsource']);
  2073. if (!in_array($_data['authsource'], $available_authsources)){
  2074. $_SESSION['return'][] = array(
  2075. 'type' => 'danger',
  2076. 'log' => array(__FUNCTION__, $_action, $data_log),
  2077. 'msg' => array('invalid_authsource', $setting)
  2078. );
  2079. return false;
  2080. }
  2081. $stmt = $pdo->prepare("SELECT * FROM `mailbox`
  2082. WHERE `authsource` != 'mailcow'
  2083. AND `authsource` IS NOT NULL
  2084. AND `authsource` != :authsource");
  2085. $stmt->execute(array(':authsource' => $_data['authsource']));
  2086. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2087. if ($rows) {
  2088. $_SESSION['return'][] = array(
  2089. 'type' => 'danger',
  2090. 'log' => array(__FUNCTION__, $_action, $data_log),
  2091. 'msg' => array('authsource_in_use', $setting)
  2092. );
  2093. return false;
  2094. }
  2095. switch ($_data['authsource']) {
  2096. case "keycloak":
  2097. $_data['server_url'] = (!empty($_data['server_url'])) ? rtrim($_data['server_url'], '/') : null;
  2098. $_data['mailpassword_flow'] = isset($_data['mailpassword_flow']) ? intval($_data['mailpassword_flow']) : 0;
  2099. $_data['periodic_sync'] = isset($_data['periodic_sync']) ? intval($_data['periodic_sync']) : 0;
  2100. $_data['import_users'] = isset($_data['import_users']) ? intval($_data['import_users']) : 0;
  2101. $_data['sync_interval'] = (!empty($_data['sync_interval'])) ? intval($_data['sync_interval']) : 15;
  2102. $_data['sync_interval'] = $_data['sync_interval'] < 1 ? 1 : $_data['sync_interval'];
  2103. $required_settings = array('authsource', 'server_url', 'realm', 'client_id', 'client_secret', 'redirect_url', 'version', 'mailpassword_flow', 'periodic_sync', 'import_users', 'sync_interval');
  2104. break;
  2105. case "generic-oidc":
  2106. $_data['authorize_url'] = (!empty($_data['authorize_url'])) ? $_data['authorize_url'] : null;
  2107. $_data['token_url'] = (!empty($_data['token_url'])) ? $_data['token_url'] : null;
  2108. $_data['userinfo_url'] = (!empty($_data['userinfo_url'])) ? $_data['userinfo_url'] : null;
  2109. $_data['client_scopes'] = (!empty($_data['client_scopes'])) ? $_data['client_scopes'] : "openid profile email";
  2110. $required_settings = array('authsource', 'authorize_url', 'token_url', 'client_id', 'client_secret', 'redirect_url', 'userinfo_url', 'client_scopes');
  2111. break;
  2112. case "ldap":
  2113. $_data['port'] = (!empty($_data['port'])) ? intval($_data['port']) : 389;
  2114. $_data['username_field'] = (!empty($_data['username_field'])) ? $_data['username_field'] : "mail";
  2115. $_data['filter'] = (!empty($_data['filter'])) ? $_data['filter'] : "";
  2116. $_data['periodic_sync'] = isset($_data['periodic_sync']) ? intval($_data['periodic_sync']) : 0;
  2117. $_data['import_users'] = isset($_data['import_users']) ? intval($_data['import_users']) : 0;
  2118. $_data['sync_interval'] = (!empty($_data['sync_interval'])) ? intval($_data['sync_interval']) : 15;
  2119. $_data['sync_interval'] = $_data['sync_interval'] < 1 ? 1 : $_data['sync_interval'];
  2120. $required_settings = array('authsource', 'host', 'port', 'basedn', 'username_field', 'filter', 'attribute_field', 'binddn', 'bindpass', 'periodic_sync', 'import_users', 'sync_interval');
  2121. break;
  2122. }
  2123. $pdo->beginTransaction();
  2124. $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES (:key, :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
  2125. // add connection settings
  2126. foreach($required_settings as $setting){
  2127. if (!isset($_data[$setting])){
  2128. $_SESSION['return'][] = array(
  2129. 'type' => 'danger',
  2130. 'log' => array(__FUNCTION__, $_action, $data_log),
  2131. 'msg' => array('required_data_missing', $setting)
  2132. );
  2133. $pdo->rollback();
  2134. return false;
  2135. }
  2136. $stmt->bindParam(':key', $setting);
  2137. $stmt->bindParam(':value', $_data[$setting]);
  2138. $stmt->execute();
  2139. }
  2140. $pdo->commit();
  2141. // add mappers
  2142. if ($_data['mappers'] && $_data['templates']){
  2143. $_data['mappers'] = (!is_array($_data['mappers'])) ? array($_data['mappers']) : $_data['mappers'];
  2144. $_data['templates'] = (!is_array($_data['templates'])) ? array($_data['templates']) : $_data['templates'];
  2145. $mappers = array_filter($_data['mappers']);
  2146. $templates = array_filter($_data['templates']);
  2147. if (count($mappers) == count($templates)){
  2148. $mappers = json_encode($mappers);
  2149. $templates = json_encode($templates);
  2150. $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES ('mappers', :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
  2151. $stmt->bindParam(':value', $mappers);
  2152. $stmt->execute();
  2153. $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES ('templates', :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
  2154. $stmt->bindParam(':value', $templates);
  2155. $stmt->execute();
  2156. }
  2157. }
  2158. // delete old access_token
  2159. $stmt = $pdo->query("INSERT INTO identity_provider (`key`, `value`) VALUES ('access_token', '') ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
  2160. $_SESSION['return'][] = array(
  2161. 'type' => 'success',
  2162. 'log' => array(__FUNCTION__, $_action, $data_log),
  2163. 'msg' => array('object_modified', '')
  2164. );
  2165. return true;
  2166. break;
  2167. case 'test':
  2168. if ($_SESSION['mailcow_cc_role'] != "admin") {
  2169. $_SESSION['return'][] = array(
  2170. 'type' => 'danger',
  2171. 'log' => array(__FUNCTION__, $_action, $_data),
  2172. 'msg' => 'access_denied'
  2173. );
  2174. return false;
  2175. }
  2176. switch ($_data['authsource']) {
  2177. case 'keycloak':
  2178. case 'generic-oidc':
  2179. if ($_data['authsource'] == 'keycloak') {
  2180. $url = "{$_data['server_url']}/realms/{$_data['realm']}/protocol/openid-connect/token";
  2181. } else {
  2182. $url = $_data['token_url'];
  2183. }
  2184. $req = http_build_query(array(
  2185. 'grant_type' => 'client_credentials',
  2186. 'client_id' => $_data['client_id'],
  2187. 'client_secret' => $_data['client_secret']
  2188. ));
  2189. $curl = curl_init();
  2190. curl_setopt($curl, CURLOPT_URL, $url);
  2191. curl_setopt($curl, CURLOPT_TIMEOUT, 7);
  2192. curl_setopt($curl, CURLOPT_POST, 1);
  2193. curl_setopt($curl, CURLOPT_POSTFIELDS, $req);
  2194. curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
  2195. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2196. $res = curl_exec($curl);
  2197. $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  2198. curl_close ($curl);
  2199. if ($code != 200) {
  2200. return false;
  2201. }
  2202. break;
  2203. case 'ldap':
  2204. if (!$_data['host'] || !$_data['port'] || !$_data['basedn'] ||
  2205. !$_data['binddn'] || !$_data['bindpass']){
  2206. return false;
  2207. }
  2208. $provider = new \LdapRecord\Connection([
  2209. 'hosts' => [$_data['host']],
  2210. 'port' => $_data['port'],
  2211. 'base_dn' => $_data['basedn'],
  2212. 'username' => $_data['binddn'],
  2213. 'password' => $_data['bindpass']
  2214. ]);
  2215. try {
  2216. $provider->connect();
  2217. } catch (TypeError $e) {
  2218. return false;
  2219. } catch (\LdapRecord\Auth\BindException $e) {
  2220. return false;
  2221. }
  2222. break;
  2223. }
  2224. return true;
  2225. break;
  2226. case "delete":
  2227. if ($_SESSION['mailcow_cc_role'] != "admin") {
  2228. $_SESSION['return'][] = array(
  2229. 'type' => 'danger',
  2230. 'log' => array(__FUNCTION__, $_action, $_data),
  2231. 'msg' => 'access_denied'
  2232. );
  2233. return false;
  2234. }
  2235. $stmt = $pdo->query("SELECT * FROM `mailbox`
  2236. WHERE `authsource` != 'mailcow'
  2237. AND `authsource` IS NOT NULL");
  2238. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2239. if ($rows) {
  2240. $_SESSION['return'][] = array(
  2241. 'type' => 'danger',
  2242. 'log' => array(__FUNCTION__, $_action, $data_log),
  2243. 'msg' => array('authsource_in_use', $setting)
  2244. );
  2245. return false;
  2246. }
  2247. $stmt = $pdo->query("DELETE FROM identity_provider;");
  2248. $_SESSION['return'][] = array(
  2249. 'type' => 'success',
  2250. 'log' => array(__FUNCTION__, $_action, $data_log),
  2251. 'msg' => array('item_deleted', '')
  2252. );
  2253. return true;
  2254. break;
  2255. case "init":
  2256. $iam_settings = identity_provider('get');
  2257. $provider = null;
  2258. switch ($iam_settings['authsource']) {
  2259. case "keycloak":
  2260. if ($iam_settings['server_url'] && $iam_settings['realm'] && $iam_settings['client_id'] &&
  2261. $iam_settings['client_secret'] && $iam_settings['redirect_url'] && $iam_settings['version']){
  2262. $provider = new Stevenmaguire\OAuth2\Client\Provider\Keycloak([
  2263. 'authServerUrl' => $iam_settings['server_url'],
  2264. 'realm' => $iam_settings['realm'],
  2265. 'clientId' => $iam_settings['client_id'],
  2266. 'clientSecret' => $iam_settings['client_secret'],
  2267. 'redirectUri' => $iam_settings['redirect_url'],
  2268. 'version' => $iam_settings['version'],
  2269. // 'encryptionAlgorithm' => 'RS256', // optional
  2270. // 'encryptionKeyPath' => '../key.pem' // optional
  2271. // 'encryptionKey' => 'contents_of_key_or_certificate' // optional
  2272. ]);
  2273. }
  2274. break;
  2275. case "generic-oidc":
  2276. if ($iam_settings['client_id'] && $iam_settings['client_secret'] && $iam_settings['redirect_url'] &&
  2277. $iam_settings['authorize_url'] && $iam_settings['token_url'] && $iam_settings['userinfo_url']){
  2278. $provider = new \League\OAuth2\Client\Provider\GenericProvider([
  2279. 'clientId' => $iam_settings['client_id'],
  2280. 'clientSecret' => $iam_settings['client_secret'],
  2281. 'redirectUri' => $iam_settings['redirect_url'],
  2282. 'urlAuthorize' => $iam_settings['authorize_url'],
  2283. 'urlAccessToken' => $iam_settings['token_url'],
  2284. 'urlResourceOwnerDetails' => $iam_settings['userinfo_url'],
  2285. 'scopes' => $iam_settings['client_scopes']
  2286. ]);
  2287. }
  2288. break;
  2289. case "ldap":
  2290. if ($iam_settings['host'] && $iam_settings['port'] && $iam_settings['basedn'] &&
  2291. $iam_settings['binddn'] && $iam_settings['bindpass']){
  2292. $provider = new \LdapRecord\Connection([
  2293. 'hosts' => [$iam_settings['host']],
  2294. 'port' => $iam_settings['port'],
  2295. 'base_dn' => $iam_settings['basedn'],
  2296. 'username' => $iam_settings['binddn'],
  2297. 'password' => $iam_settings['bindpass']
  2298. ]);
  2299. try {
  2300. $provider->connect();
  2301. } catch (TypeError $e) {
  2302. $provider = null;
  2303. }
  2304. }
  2305. break;
  2306. }
  2307. return $provider;
  2308. break;
  2309. case "verify-sso":
  2310. $provider = $_data['iam_provider'];
  2311. $iam_settings = identity_provider('get');
  2312. if ($iam_settings['authsource'] != 'keycloak' && $iam_settings['authsource'] != 'generic-oidc'){
  2313. $_SESSION['return'][] = array(
  2314. 'type' => 'danger',
  2315. 'log' => array(__FUNCTION__),
  2316. 'msg' => array('login_failed', "no OIDC provider configured")
  2317. );
  2318. return false;
  2319. }
  2320. try {
  2321. $token = $provider->getAccessToken('authorization_code', ['code' => $_GET['code']]);
  2322. $_SESSION['iam_token'] = $token->getToken();
  2323. $_SESSION['iam_refresh_token'] = $token->getRefreshToken();
  2324. $info = $provider->getResourceOwner($token)->toArray();
  2325. } catch (Throwable $e) {
  2326. $_SESSION['return'][] = array(
  2327. 'type' => 'danger',
  2328. 'log' => array(__FUNCTION__),
  2329. 'msg' => array('login_failed', $e->getMessage())
  2330. );
  2331. return false;
  2332. }
  2333. // check if email address is given
  2334. if (empty($info['email'])) return false;
  2335. // token valid, get mailbox
  2336. $stmt = $pdo->prepare("SELECT * FROM `mailbox`
  2337. INNER JOIN domain on mailbox.domain = domain.domain
  2338. WHERE `kind` NOT REGEXP 'location|thing|group'
  2339. AND `mailbox`.`active`='1'
  2340. AND `domain`.`active`='1'
  2341. AND `username` = :user
  2342. AND (`authsource`='keycloak' OR `authsource`='generic-oidc')");
  2343. $stmt->execute(array(':user' => $info['email']));
  2344. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  2345. if ($row){
  2346. // success
  2347. set_user_loggedin_session($info['email']);
  2348. $_SESSION['return'][] = array(
  2349. 'type' => 'success',
  2350. 'log' => array(__FUNCTION__, $_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role']),
  2351. 'msg' => array('logged_in_as', $_SESSION['mailcow_cc_username'])
  2352. );
  2353. return true;
  2354. }
  2355. // get mapped template, if not set return false
  2356. // also return false if no mappers were defined
  2357. $user_template = $info['mailcow_template'];
  2358. if (empty($iam_settings['mappers']) || empty($user_template)){
  2359. clear_session();
  2360. $_SESSION['return'][] = array(
  2361. 'type' => 'danger',
  2362. 'log' => array(__FUNCTION__, $info['email']),
  2363. 'msg' => array('login_failed', 'empty attribute mapping or missing template attribute')
  2364. );
  2365. return false;
  2366. }
  2367. // check if matching attribute exist
  2368. $mapper_key = array_search($user_template, $iam_settings['mappers']);
  2369. if ($mapper_key === false) {
  2370. clear_session();
  2371. $_SESSION['return'][] = array(
  2372. 'type' => 'danger',
  2373. 'log' => array(__FUNCTION__, $info['email']),
  2374. 'msg' => array('login_failed', 'specified template not found')
  2375. );
  2376. return false;
  2377. }
  2378. // create mailbox
  2379. $create_res = mailbox('add', 'mailbox_from_template', array(
  2380. 'domain' => explode('@', $info['email'])[1],
  2381. 'local_part' => explode('@', $info['email'])[0],
  2382. 'name' => $info['firstName'] . " " . $info['lastName'],
  2383. 'authsource' => $iam_settings['authsource'],
  2384. 'template' => $iam_settings['templates'][$mapper_key]
  2385. ));
  2386. if (!$create_res){
  2387. clear_session();
  2388. $_SESSION['return'][] = array(
  2389. 'type' => 'danger',
  2390. 'log' => array(__FUNCTION__, $info['email']),
  2391. 'msg' => array('login_failed', 'mailbox creation failed')
  2392. );
  2393. return false;
  2394. }
  2395. set_user_loggedin_session($info['email']);
  2396. $_SESSION['return'][] = array(
  2397. 'type' => 'success',
  2398. 'log' => array(__FUNCTION__, $_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role']),
  2399. 'msg' => array('logged_in_as', $_SESSION['mailcow_cc_username'])
  2400. );
  2401. return true;
  2402. break;
  2403. case "refresh-token":
  2404. $provider = $_data['iam_provider'];
  2405. try {
  2406. $token = $provider->getAccessToken('refresh_token', ['refresh_token' => $_SESSION['iam_refresh_token']]);
  2407. $_SESSION['iam_token'] = $token->getToken();
  2408. $_SESSION['iam_refresh_token'] = $token->getRefreshToken();
  2409. $info = $provider->getResourceOwner($token)->toArray();
  2410. } catch (Throwable $e) {
  2411. clear_session();
  2412. $_SESSION['return'][] = array(
  2413. 'type' => 'danger',
  2414. 'log' => array(__FUNCTION__),
  2415. 'msg' => array('refresh_login_failed', $e->getMessage())
  2416. );
  2417. return false;
  2418. }
  2419. if (empty($info['email'])){
  2420. clear_session();
  2421. $_SESSION['return'][] = array(
  2422. 'type' => 'danger',
  2423. 'log' => array(__FUNCTION__, $_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role']),
  2424. 'msg' => 'refresh_login_failed'
  2425. );
  2426. return false;
  2427. }
  2428. $_SESSION['mailcow_cc_username'] = $info['email'];
  2429. $_SESSION['mailcow_cc_role'] = "user";
  2430. return true;
  2431. break;
  2432. case "get-redirect":
  2433. $iam_settings = identity_provider('get');
  2434. if ($iam_settings['authsource'] != 'keycloak' && $iam_settings['authsource'] != 'generic-oidc')
  2435. return false;
  2436. $provider = $_data['iam_provider'];
  2437. $authUrl = $provider->getAuthorizationUrl();
  2438. $_SESSION['oauth2state'] = $provider->getState();
  2439. return $authUrl;
  2440. break;
  2441. case "get-keycloak-admin-token":
  2442. // get access_token for service account of mailcow client
  2443. $iam_settings = identity_provider('get');
  2444. if ($iam_settings['authsource'] !== 'keycloak') return false;
  2445. if (isset($iam_settings['access_token'])) {
  2446. // check if access_token is valid
  2447. $url = "{$iam_settings['server_url']}/realms/{$iam_settings['realm']}/protocol/openid-connect/token/introspect";
  2448. $req = http_build_query(array(
  2449. 'token' => $iam_settings['access_token'],
  2450. 'client_id' => $iam_settings['client_id'],
  2451. 'client_secret' => $iam_settings['client_secret']
  2452. ));
  2453. $curl = curl_init();
  2454. curl_setopt($curl, CURLOPT_URL, $url);
  2455. curl_setopt($curl, CURLOPT_TIMEOUT, 7);
  2456. curl_setopt($curl, CURLOPT_POST, 1);
  2457. curl_setopt($curl, CURLOPT_POSTFIELDS, $req);
  2458. curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
  2459. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2460. curl_setopt($curl, CURLOPT_TIMEOUT, 5);
  2461. $res = json_decode(curl_exec($curl), true);
  2462. $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  2463. curl_close ($curl);
  2464. if ($code == 200 && $res['active'] == true) {
  2465. // token is valid
  2466. return $iam_settings['access_token'];
  2467. }
  2468. }
  2469. $url = "{$iam_settings['server_url']}/realms/{$iam_settings['realm']}/protocol/openid-connect/token";
  2470. $req = http_build_query(array(
  2471. 'grant_type' => 'client_credentials',
  2472. 'client_id' => $iam_settings['client_id'],
  2473. 'client_secret' => $iam_settings['client_secret']
  2474. ));
  2475. $curl = curl_init();
  2476. curl_setopt($curl, CURLOPT_URL, $url);
  2477. curl_setopt($curl, CURLOPT_TIMEOUT, 7);
  2478. curl_setopt($curl, CURLOPT_POST, 1);
  2479. curl_setopt($curl, CURLOPT_POSTFIELDS, $req);
  2480. curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
  2481. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2482. curl_setopt($curl, CURLOPT_TIMEOUT, 5);
  2483. $res = json_decode(curl_exec($curl), true);
  2484. $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  2485. curl_close ($curl);
  2486. if ($code != 200) {
  2487. return false;
  2488. }
  2489. $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES (:key, :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
  2490. $stmt->execute(array(
  2491. ':key' => 'access_token',
  2492. ':value' => $res['access_token']
  2493. ));
  2494. return $res['access_token'];
  2495. break;
  2496. }
  2497. }
  2498. function clear_session(){
  2499. session_regenerate_id(true);
  2500. session_unset();
  2501. session_destroy();
  2502. session_write_close();
  2503. }
  2504. function set_user_loggedin_session($user) {
  2505. $_SESSION['mailcow_cc_username'] = $user;
  2506. $_SESSION['mailcow_cc_role'] = 'user';
  2507. $sogo_sso_pass = file_get_contents("/etc/sogo-sso/sogo-sso.pass");
  2508. $_SESSION['sogo-sso-user-allowed'][] = $user;
  2509. $_SESSION['sogo-sso-pass'] = $sogo_sso_pass;
  2510. unset($_SESSION['pending_mailcow_cc_username']);
  2511. unset($_SESSION['pending_mailcow_cc_role']);
  2512. unset($_SESSION['pending_tfa_methods']);
  2513. }
  2514. function get_logs($application, $lines = false) {
  2515. if ($lines === false) {
  2516. $lines = $GLOBALS['LOG_LINES'] - 1;
  2517. }
  2518. elseif(is_numeric($lines) && $lines >= 1) {
  2519. $lines = abs(intval($lines) - 1);
  2520. }
  2521. else {
  2522. list ($from, $to) = explode('-', $lines);
  2523. $from = intval($from);
  2524. $to = intval($to);
  2525. if ($from < 1 || $to < $from) { return false; }
  2526. }
  2527. global $redis;
  2528. global $pdo;
  2529. if ($_SESSION['mailcow_cc_role'] != "admin") {
  2530. return false;
  2531. }
  2532. // SQL
  2533. if ($application == "mailcow-ui") {
  2534. if (isset($from) && isset($to)) {
  2535. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :from, :to");
  2536. $stmt->execute(array(
  2537. ':from' => $from - 1,
  2538. ':to' => $to
  2539. ));
  2540. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2541. }
  2542. else {
  2543. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :lines");
  2544. $stmt->execute(array(
  2545. ':lines' => $lines + 1,
  2546. ));
  2547. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2548. }
  2549. if (is_array($data)) {
  2550. return $data;
  2551. }
  2552. }
  2553. if ($application == "sasl") {
  2554. if (isset($from) && isset($to)) {
  2555. $stmt = $pdo->prepare("SELECT * FROM `sasl_log` ORDER BY `datetime` DESC LIMIT :from, :to");
  2556. $stmt->execute(array(
  2557. ':from' => $from - 1,
  2558. ':to' => $to
  2559. ));
  2560. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2561. }
  2562. else {
  2563. $stmt = $pdo->prepare("SELECT * FROM `sasl_log` ORDER BY `datetime` DESC LIMIT :lines");
  2564. $stmt->execute(array(
  2565. ':lines' => $lines + 1,
  2566. ));
  2567. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2568. }
  2569. if (is_array($data)) {
  2570. return $data;
  2571. }
  2572. }
  2573. // Redis
  2574. if ($application == "dovecot-mailcow") {
  2575. if (isset($from) && isset($to)) {
  2576. $data = $redis->lRange('DOVECOT_MAILLOG', $from - 1, $to - 1);
  2577. }
  2578. else {
  2579. $data = $redis->lRange('DOVECOT_MAILLOG', 0, $lines);
  2580. }
  2581. if ($data) {
  2582. foreach ($data as $json_line) {
  2583. $data_array[] = json_decode($json_line, true);
  2584. }
  2585. return $data_array;
  2586. }
  2587. }
  2588. if ($application == "cron-mailcow") {
  2589. if (isset($from) && isset($to)) {
  2590. $data = $redis->lRange('CRON_LOG', $from - 1, $to - 1);
  2591. }
  2592. else {
  2593. $data = $redis->lRange('CRON_LOG', 0, $lines);
  2594. }
  2595. if ($data) {
  2596. foreach ($data as $json_line) {
  2597. $data_array[] = json_decode($json_line, true);
  2598. }
  2599. return $data_array;
  2600. }
  2601. }
  2602. if ($application == "postfix-mailcow") {
  2603. if (isset($from) && isset($to)) {
  2604. $data = $redis->lRange('POSTFIX_MAILLOG', $from - 1, $to - 1);
  2605. }
  2606. else {
  2607. $data = $redis->lRange('POSTFIX_MAILLOG', 0, $lines);
  2608. }
  2609. if ($data) {
  2610. foreach ($data as $json_line) {
  2611. $data_array[] = json_decode($json_line, true);
  2612. }
  2613. return $data_array;
  2614. }
  2615. }
  2616. if ($application == "sogo-mailcow") {
  2617. if (isset($from) && isset($to)) {
  2618. $data = $redis->lRange('SOGO_LOG', $from - 1, $to - 1);
  2619. }
  2620. else {
  2621. $data = $redis->lRange('SOGO_LOG', 0, $lines);
  2622. }
  2623. if ($data) {
  2624. foreach ($data as $json_line) {
  2625. $data_array[] = json_decode($json_line, true);
  2626. }
  2627. return $data_array;
  2628. }
  2629. }
  2630. if ($application == "watchdog-mailcow") {
  2631. if (isset($from) && isset($to)) {
  2632. $data = $redis->lRange('WATCHDOG_LOG', $from - 1, $to - 1);
  2633. }
  2634. else {
  2635. $data = $redis->lRange('WATCHDOG_LOG', 0, $lines);
  2636. }
  2637. if ($data) {
  2638. foreach ($data as $json_line) {
  2639. $data_array[] = json_decode($json_line, true);
  2640. }
  2641. return $data_array;
  2642. }
  2643. }
  2644. if ($application == "acme-mailcow") {
  2645. if (isset($from) && isset($to)) {
  2646. $data = $redis->lRange('ACME_LOG', $from - 1, $to - 1);
  2647. }
  2648. else {
  2649. $data = $redis->lRange('ACME_LOG', 0, $lines);
  2650. }
  2651. if ($data) {
  2652. foreach ($data as $json_line) {
  2653. $data_array[] = json_decode($json_line, true);
  2654. }
  2655. return $data_array;
  2656. }
  2657. }
  2658. if ($application == "ratelimited") {
  2659. if (isset($from) && isset($to)) {
  2660. $data = $redis->lRange('RL_LOG', $from - 1, $to - 1);
  2661. }
  2662. else {
  2663. $data = $redis->lRange('RL_LOG', 0, $lines);
  2664. }
  2665. if ($data) {
  2666. foreach ($data as $json_line) {
  2667. $data_array[] = json_decode($json_line, true);
  2668. }
  2669. return $data_array;
  2670. }
  2671. }
  2672. if ($application == "api-mailcow") {
  2673. if (isset($from) && isset($to)) {
  2674. $data = $redis->lRange('API_LOG', $from - 1, $to - 1);
  2675. }
  2676. else {
  2677. $data = $redis->lRange('API_LOG', 0, $lines);
  2678. }
  2679. if ($data) {
  2680. foreach ($data as $json_line) {
  2681. $data_array[] = json_decode($json_line, true);
  2682. }
  2683. return $data_array;
  2684. }
  2685. }
  2686. if ($application == "netfilter-mailcow") {
  2687. if (isset($from) && isset($to)) {
  2688. $data = $redis->lRange('NETFILTER_LOG', $from - 1, $to - 1);
  2689. }
  2690. else {
  2691. $data = $redis->lRange('NETFILTER_LOG', 0, $lines);
  2692. }
  2693. if ($data) {
  2694. foreach ($data as $json_line) {
  2695. $data_array[] = json_decode($json_line, true);
  2696. }
  2697. return $data_array;
  2698. }
  2699. }
  2700. if ($application == "autodiscover-mailcow") {
  2701. if (isset($from) && isset($to)) {
  2702. $data = $redis->lRange('AUTODISCOVER_LOG', $from - 1, $to - 1);
  2703. }
  2704. else {
  2705. $data = $redis->lRange('AUTODISCOVER_LOG', 0, $lines);
  2706. }
  2707. if ($data) {
  2708. foreach ($data as $json_line) {
  2709. $data_array[] = json_decode($json_line, true);
  2710. }
  2711. return $data_array;
  2712. }
  2713. }
  2714. if ($application == "rspamd-history") {
  2715. $curl = curl_init();
  2716. curl_setopt($curl, CURLOPT_UNIX_SOCKET_PATH, '/var/lib/rspamd/rspamd.sock');
  2717. if (!is_numeric($lines)) {
  2718. list ($from, $to) = explode('-', $lines);
  2719. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?from=" . intval($from) . "&to=" . intval($to));
  2720. }
  2721. else {
  2722. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?to=" . intval($lines));
  2723. }
  2724. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2725. $history = curl_exec($curl);
  2726. if (!curl_errno($curl)) {
  2727. $data_array = json_decode($history, true);
  2728. curl_close($curl);
  2729. return $data_array['rows'];
  2730. }
  2731. curl_close($curl);
  2732. return false;
  2733. }
  2734. if ($application == "rspamd-stats") {
  2735. $curl = curl_init();
  2736. curl_setopt($curl, CURLOPT_UNIX_SOCKET_PATH, '/var/lib/rspamd/rspamd.sock');
  2737. curl_setopt($curl, CURLOPT_URL,"http://rspamd/stat");
  2738. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2739. $stats = curl_exec($curl);
  2740. if (!curl_errno($curl)) {
  2741. $data_array = json_decode($stats, true);
  2742. curl_close($curl);
  2743. return $data_array;
  2744. }
  2745. curl_close($curl);
  2746. return false;
  2747. }
  2748. return false;
  2749. }
  2750. function getGUID() {
  2751. if (function_exists('com_create_guid')) {
  2752. return com_create_guid();
  2753. }
  2754. mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
  2755. $charid = strtoupper(md5(uniqid(rand(), true)));
  2756. $hyphen = chr(45);// "-"
  2757. return substr($charid, 0, 8).$hyphen
  2758. .substr($charid, 8, 4).$hyphen
  2759. .substr($charid,12, 4).$hyphen
  2760. .substr($charid,16, 4).$hyphen
  2761. .substr($charid,20,12);
  2762. }
  2763. function solr_status() {
  2764. $curl = curl_init();
  2765. $endpoint = 'http://solr:8983/solr/admin/cores';
  2766. $params = array(
  2767. 'action' => 'STATUS',
  2768. 'core' => 'dovecot-fts',
  2769. 'indexInfo' => 'true'
  2770. );
  2771. $url = $endpoint . '?' . http_build_query($params);
  2772. curl_setopt($curl, CURLOPT_URL, $url);
  2773. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  2774. curl_setopt($curl, CURLOPT_POST, 0);
  2775. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  2776. $response_core = curl_exec($curl);
  2777. if ($response_core === false) {
  2778. $err = curl_error($curl);
  2779. curl_close($curl);
  2780. return false;
  2781. }
  2782. else {
  2783. curl_close($curl);
  2784. $curl = curl_init();
  2785. $status_core = json_decode($response_core, true);
  2786. $url = 'http://solr:8983/solr/admin/info/system';
  2787. curl_setopt($curl, CURLOPT_URL, $url);
  2788. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  2789. curl_setopt($curl, CURLOPT_POST, 0);
  2790. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  2791. $response_sysinfo = curl_exec($curl);
  2792. if ($response_sysinfo === false) {
  2793. $err = curl_error($curl);
  2794. curl_close($curl);
  2795. return false;
  2796. }
  2797. else {
  2798. curl_close($curl);
  2799. $status_sysinfo = json_decode($response_sysinfo, true);
  2800. $status = array_merge($status_core, $status_sysinfo);
  2801. return (!empty($status['status']['dovecot-fts']) && !empty($status['jvm']['memory'])) ? $status : false;
  2802. }
  2803. return (!empty($status['status']['dovecot-fts'])) ? $status['status']['dovecot-fts'] : false;
  2804. }
  2805. return false;
  2806. }
  2807. function cleanupJS($ignore = '', $folder = '/tmp/*.js') {
  2808. $now = time();
  2809. foreach (glob($folder) as $filename) {
  2810. if(strpos($filename, $ignore) !== false) {
  2811. continue;
  2812. }
  2813. if (is_file($filename)) {
  2814. if ($now - filemtime($filename) >= 60 * 60) {
  2815. unlink($filename);
  2816. }
  2817. }
  2818. }
  2819. }
  2820. function cleanupCSS($ignore = '', $folder = '/tmp/*.css') {
  2821. $now = time();
  2822. foreach (glob($folder) as $filename) {
  2823. if(strpos($filename, $ignore) !== false) {
  2824. continue;
  2825. }
  2826. if (is_file($filename)) {
  2827. if ($now - filemtime($filename) >= 60 * 60) {
  2828. unlink($filename);
  2829. }
  2830. }
  2831. }
  2832. }
  2833. ?>