functions.inc.php 143 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821
  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_generate(){
  209. $password_complexity = password_complexity('get');
  210. $min_length = max(16, intval($password_complexity['length']));
  211. $lowercase = range('a', 'z');
  212. $uppercase = range('A', 'Z');
  213. $digits = range(0, 9);
  214. $special_chars = str_split('!@#$%^&*()?=');
  215. $password = [
  216. $lowercase[random_int(0, count($lowercase) - 1)],
  217. $uppercase[random_int(0, count($uppercase) - 1)],
  218. $digits[random_int(0, count($digits) - 1)],
  219. $special_chars[random_int(0, count($special_chars) - 1)],
  220. ];
  221. $all = array_merge($lowercase, $uppercase, $digits, $special_chars);
  222. while (count($password) < $min_length) {
  223. $password[] = $all[random_int(0, count($all) - 1)];
  224. }
  225. // Cryptographically secure shuffle using Fisher-Yates algorithm
  226. $count = count($password);
  227. for ($i = $count - 1; $i > 0; $i--) {
  228. $j = random_int(0, $i);
  229. $temp = $password[$i];
  230. $password[$i] = $password[$j];
  231. $password[$j] = $temp;
  232. }
  233. return implode('', $password);
  234. }
  235. function password_check($password1, $password2) {
  236. $password_complexity = password_complexity('get');
  237. if (empty($password1) || empty($password2)) {
  238. $_SESSION['return'][] = array(
  239. 'type' => 'danger',
  240. 'log' => array(__FUNCTION__, $_action, $_type),
  241. 'msg' => 'password_complexity'
  242. );
  243. return false;
  244. }
  245. if ($password1 != $password2) {
  246. $_SESSION['return'][] = array(
  247. 'type' => 'danger',
  248. 'log' => array(__FUNCTION__, $_action, $_type),
  249. 'msg' => 'password_mismatch'
  250. );
  251. return false;
  252. }
  253. $given_password['length'] = strlen($password1);
  254. $given_password['special_chars'] = preg_match('/[^a-zA-Z\d]/', $password1);
  255. $given_password['chars'] = preg_match('/[a-zA-Z]/',$password1);
  256. $given_password['numbers'] = preg_match('/\d/', $password1);
  257. $lower = strlen(preg_replace("/[^a-z]/", '', $password1));
  258. $upper = strlen(preg_replace("/[^A-Z]/", '', $password1));
  259. $given_password['lowerupper'] = ($lower > 0 && $upper > 0) ? true : false;
  260. if (
  261. ($given_password['length'] < $password_complexity['length']) ||
  262. ($password_complexity['special_chars'] == 1 && (intval($given_password['special_chars']) != $password_complexity['special_chars'])) ||
  263. ($password_complexity['chars'] == 1 && (intval($given_password['chars']) != $password_complexity['chars'])) ||
  264. ($password_complexity['numbers'] == 1 && (intval($given_password['numbers']) != $password_complexity['numbers'])) ||
  265. ($password_complexity['lowerupper'] == 1 && (intval($given_password['lowerupper']) != $password_complexity['lowerupper']))
  266. ) {
  267. $_SESSION['return'][] = array(
  268. 'type' => 'danger',
  269. 'log' => array(__FUNCTION__, $_action, $_type),
  270. 'msg' => 'password_complexity'
  271. );
  272. return false;
  273. }
  274. return true;
  275. }
  276. function last_login($action, $username, $sasl_limit_days = 7, $ui_offset = 1) {
  277. global $pdo;
  278. global $redis;
  279. $sasl_limit_days = intval($sasl_limit_days);
  280. switch ($action) {
  281. case 'get':
  282. if (filter_var($username, FILTER_VALIDATE_EMAIL) && hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $username)) {
  283. $stmt = $pdo->prepare('SELECT `real_rip`, MAX(`datetime`) as `datetime`, `service`, `app_password`, MAX(`app_passwd`.`name`) as `app_password_name` FROM `sasl_log`
  284. LEFT OUTER JOIN `app_passwd` on `sasl_log`.`app_password` = `app_passwd`.`id`
  285. WHERE `username` = :username
  286. AND HOUR(TIMEDIFF(NOW(), `datetime`)) < :sasl_limit_days
  287. GROUP BY `real_rip`, `service`, `app_password`
  288. ORDER BY `datetime` DESC;');
  289. $stmt->execute(array(':username' => $username, ':sasl_limit_days' => ($sasl_limit_days * 24)));
  290. $sasl = $stmt->fetchAll(PDO::FETCH_ASSOC);
  291. foreach ($sasl as $k => $v) {
  292. if (!filter_var($sasl[$k]['real_rip'], FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
  293. $sasl[$k]['real_rip'] = 'Web/EAS/Internal (' . $sasl[$k]['real_rip'] . ')';
  294. }
  295. elseif (filter_var($sasl[$k]['real_rip'], FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
  296. try {
  297. $sasl[$k]['location'] = $redis->hGet('IP_SHORTCOUNTRY', $sasl[$k]['real_rip']);
  298. }
  299. catch (RedisException $e) {
  300. $_SESSION['return'][] = array(
  301. 'type' => 'danger',
  302. 'log' => array(__FUNCTION__, $_action, $_data_log),
  303. 'msg' => array('redis_error', $e)
  304. );
  305. return false;
  306. }
  307. if (!$sasl[$k]['location']) {
  308. $curl = curl_init();
  309. curl_setopt($curl, CURLOPT_URL,"https://dfdata.bella.network/country/" . $sasl[$k]['real_rip']);
  310. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  311. curl_setopt($curl, CURLOPT_USERAGENT, 'Moocow');
  312. curl_setopt($curl, CURLOPT_TIMEOUT, 5);
  313. $ip_data = curl_exec($curl);
  314. if (!curl_errno($curl)) {
  315. $ip_data_array = json_decode($ip_data, true);
  316. if ($ip_data_array !== false and !empty($ip_data_array['shortcountry'])) {
  317. $sasl[$k]['location'] = $ip_data_array['shortcountry'];
  318. try {
  319. $redis->hSet('IP_SHORTCOUNTRY', $sasl[$k]['real_rip'], $ip_data_array['shortcountry']);
  320. }
  321. catch (RedisException $e) {
  322. $_SESSION['return'][] = array(
  323. 'type' => 'danger',
  324. 'log' => array(__FUNCTION__, $_action, $_data_log),
  325. 'msg' => array('redis_error', $e)
  326. );
  327. curl_close($curl);
  328. return false;
  329. }
  330. }
  331. }
  332. curl_close($curl);
  333. }
  334. }
  335. }
  336. }
  337. else {
  338. $sasl = array();
  339. }
  340. if ($_SESSION['mailcow_cc_role'] == "admin" || $username == $_SESSION['mailcow_cc_username']) {
  341. $stmt = $pdo->prepare('SELECT `remote`, `time` FROM `logs`
  342. WHERE JSON_EXTRACT(`call`, "$[0]") = "check_login"
  343. AND JSON_EXTRACT(`call`, "$[1]") = :username
  344. AND `type` = "success" ORDER BY `time` DESC LIMIT 1 OFFSET :offset');
  345. $stmt->execute(array(
  346. ':username' => $username,
  347. ':offset' => $ui_offset
  348. ));
  349. $ui = $stmt->fetch(PDO::FETCH_ASSOC);
  350. }
  351. else {
  352. $ui = array();
  353. }
  354. return array('ui' => $ui, 'sasl' => $sasl);
  355. break;
  356. case 'reset':
  357. if (filter_var($username, FILTER_VALIDATE_EMAIL) && hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $username)) {
  358. $stmt = $pdo->prepare('DELETE FROM `sasl_log`
  359. WHERE `username` = :username');
  360. $stmt->execute(array(':username' => $username));
  361. }
  362. if ($_SESSION['mailcow_cc_role'] == "admin" || $username == $_SESSION['mailcow_cc_username']) {
  363. $stmt = $pdo->prepare('DELETE FROM `logs`
  364. WHERE JSON_EXTRACT(`call`, "$[0]") = "check_login"
  365. AND JSON_EXTRACT(`call`, "$[1]") = :username
  366. AND `type` = "success"');
  367. $stmt->execute(array(':username' => $username));
  368. }
  369. return true;
  370. break;
  371. }
  372. }
  373. function set_sasl_log($username, $real_rip, $service){
  374. global $pdo;
  375. try {
  376. if (!empty($_SESSION['app_passwd_id'])) {
  377. $app_password = $_SESSION['app_passwd_id'];
  378. } else {
  379. $app_password = 0;
  380. }
  381. $stmt = $pdo->prepare('REPLACE INTO `sasl_log` (`username`, `real_rip`, `service`, `app_password`) VALUES (:username, :real_rip, :service, :app_password)');
  382. $stmt->execute(array(
  383. ':username' => $username,
  384. ':real_rip' => $real_rip,
  385. ':service' => $service,
  386. ':app_password' => $app_password
  387. ));
  388. } catch (PDOException $e) {
  389. $_SESSION['return'][] = array(
  390. 'type' => 'danger',
  391. 'log' => array(__FUNCTION__, $_data_log),
  392. 'msg' => array('mysql_error', $e)
  393. );
  394. return false;
  395. }
  396. return true;
  397. }
  398. function flush_memcached() {
  399. try {
  400. $m = new Memcached();
  401. $m->addServer('memcached', 11211);
  402. $m->flush();
  403. }
  404. catch ( Exception $e ) {
  405. // Dunno
  406. }
  407. }
  408. function sys_mail($_data) {
  409. if ($_SESSION['mailcow_cc_role'] != "admin") {
  410. $_SESSION['return'][] = array(
  411. 'type' => 'danger',
  412. 'log' => array(__FUNCTION__),
  413. 'msg' => 'access_denied'
  414. );
  415. return false;
  416. }
  417. $excludes = $_data['mass_exclude'];
  418. $includes = $_data['mass_include'];
  419. $mailboxes = array();
  420. $mass_from = $_data['mass_from'];
  421. $mass_text = $_data['mass_text'];
  422. $mass_html = $_data['mass_html'];
  423. $mass_subject = $_data['mass_subject'];
  424. if (!filter_var($mass_from, FILTER_VALIDATE_EMAIL)) {
  425. $_SESSION['return'][] = array(
  426. 'type' => 'danger',
  427. 'log' => array(__FUNCTION__),
  428. 'msg' => 'from_invalid'
  429. );
  430. return false;
  431. }
  432. if (empty($mass_subject)) {
  433. $_SESSION['return'][] = array(
  434. 'type' => 'danger',
  435. 'log' => array(__FUNCTION__),
  436. 'msg' => 'subject_empty'
  437. );
  438. return false;
  439. }
  440. if (empty($mass_text)) {
  441. $_SESSION['return'][] = array(
  442. 'type' => 'danger',
  443. 'log' => array(__FUNCTION__),
  444. 'msg' => 'text_empty'
  445. );
  446. return false;
  447. }
  448. $domains = array_merge(mailbox('get', 'domains'), mailbox('get', 'alias_domains'));
  449. foreach ($domains as $domain) {
  450. foreach (mailbox('get', 'mailboxes', $domain) as $mailbox) {
  451. $mailboxes[] = $mailbox;
  452. }
  453. }
  454. if (!empty($includes)) {
  455. $rcpts = array_intersect($mailboxes, $includes);
  456. }
  457. elseif (!empty($excludes)) {
  458. $rcpts = array_diff($mailboxes, $excludes);
  459. }
  460. else {
  461. $rcpts = $mailboxes;
  462. }
  463. if (!empty($rcpts)) {
  464. ini_set('max_execution_time', 0);
  465. ini_set('max_input_time', 0);
  466. $mail = new PHPMailer;
  467. $mail->Timeout = 10;
  468. $mail->SMTPOptions = array(
  469. 'ssl' => array(
  470. 'verify_peer' => false,
  471. 'verify_peer_name' => false,
  472. 'allow_self_signed' => true
  473. )
  474. );
  475. $mail->isSMTP();
  476. $mail->Host = 'dovecot-mailcow';
  477. $mail->SMTPAuth = false;
  478. $mail->Port = 24;
  479. $mail->setFrom($mass_from);
  480. $mail->Subject = $mass_subject;
  481. $mail->CharSet ="UTF-8";
  482. if (!empty($mass_html)) {
  483. $mail->Body = $mass_html;
  484. $mail->AltBody = $mass_text;
  485. }
  486. else {
  487. $mail->Body = $mass_text;
  488. }
  489. $mail->XMailer = 'MooMassMail';
  490. foreach ($rcpts as $rcpt) {
  491. $mail->AddAddress($rcpt);
  492. if (!$mail->send()) {
  493. $_SESSION['return'][] = array(
  494. 'type' => 'warning',
  495. 'log' => array(__FUNCTION__),
  496. 'msg' => 'Mailer error (RCPT "' . htmlspecialchars($rcpt) . '"): ' . str_replace('https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting', '', $mail->ErrorInfo)
  497. );
  498. }
  499. $mail->ClearAllRecipients();
  500. }
  501. }
  502. $_SESSION['return'][] = array(
  503. 'type' => 'success',
  504. 'log' => array(__FUNCTION__),
  505. 'msg' => 'Mass mail job completed, sent ' . count($rcpts) . ' mails'
  506. );
  507. }
  508. function logger($_data = false) {
  509. /*
  510. logger() will be called as last function
  511. To manually log a message, logger needs to be called like below.
  512. logger(array(
  513. 'return' => array(
  514. array(
  515. 'type' => 'danger',
  516. 'log' => array(__FUNCTION__),
  517. 'msg' => $err
  518. )
  519. )
  520. ));
  521. These messages will not be printed as alert box.
  522. To do so, push them to $_SESSION['return'] and do not call logger as they will be included automatically:
  523. $_SESSION['return'][] = array(
  524. 'type' => 'danger',
  525. 'log' => array(__FUNCTION__, $user, '*'),
  526. 'msg' => $err
  527. );
  528. */
  529. global $pdo;
  530. if (!$_data) {
  531. $_data = $_SESSION;
  532. }
  533. if (!empty($_data['return'])) {
  534. $task = substr(strtoupper(md5(uniqid(rand(), true))), 0, 6);
  535. foreach ($_data['return'] as $return) {
  536. $type = $return['type'];
  537. $msg = null;
  538. if (isset($return['msg'])) {
  539. $msg = json_encode($return['msg'], JSON_UNESCAPED_UNICODE);
  540. }
  541. $call = null;
  542. if (isset($return['log'])) {
  543. $call = json_encode($return['log'], JSON_UNESCAPED_UNICODE);
  544. }
  545. if (!empty($_SESSION["dual-login"]["username"])) {
  546. $user = $_SESSION["dual-login"]["username"] . ' => ' . $_SESSION['mailcow_cc_username'];
  547. $role = $_SESSION["dual-login"]["role"] . ' => ' . $_SESSION['mailcow_cc_role'];
  548. }
  549. elseif (!empty($_SESSION['mailcow_cc_username'])) {
  550. $user = $_SESSION['mailcow_cc_username'];
  551. $role = $_SESSION['mailcow_cc_role'];
  552. }
  553. else {
  554. $user = 'unauthenticated';
  555. $role = 'unauthenticated';
  556. }
  557. // We cannot log when logs is missing...
  558. try {
  559. $stmt = $pdo->prepare("INSERT INTO `logs` (`type`, `task`, `msg`, `call`, `user`, `role`, `remote`, `time`) VALUES
  560. (:type, :task, :msg, :call, :user, :role, :remote, UNIX_TIMESTAMP())");
  561. $stmt->execute(array(
  562. ':type' => $type,
  563. ':task' => $task,
  564. ':call' => $call,
  565. ':msg' => $msg,
  566. ':user' => $user,
  567. ':role' => $role,
  568. ':remote' => get_remote_ip()
  569. ));
  570. }
  571. catch (PDOException $e) {
  572. # handle the exception here, as the exception handler function results in a white page
  573. error_log($e->getMessage(), 0);
  574. }
  575. }
  576. }
  577. else {
  578. return true;
  579. }
  580. }
  581. function hasDomainAccess($username, $role, $domain) {
  582. global $pdo;
  583. if (empty($domain) || !is_valid_domain_name($domain)) {
  584. return false;
  585. }
  586. if (isset($_SESSION['access_all_exception']) && $_SESSION['access_all_exception'] == "1") {
  587. return true;
  588. }
  589. if (!filter_var($username, FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $username))) {
  590. return false;
  591. }
  592. if ($role != 'admin' && $role != 'domainadmin') {
  593. return false;
  594. }
  595. if ($role == 'admin') {
  596. $stmt = $pdo->prepare("SELECT `domain` FROM `domain`
  597. WHERE `domain` = :domain");
  598. $stmt->execute(array(':domain' => $domain));
  599. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  600. $stmt = $pdo->prepare("SELECT `alias_domain` FROM `alias_domain`
  601. WHERE `alias_domain` = :domain");
  602. $stmt->execute(array(':domain' => $domain));
  603. $num_results = $num_results + count($stmt->fetchAll(PDO::FETCH_ASSOC));
  604. if ($num_results != 0) {
  605. return true;
  606. }
  607. }
  608. elseif ($role == 'domainadmin') {
  609. $stmt = $pdo->prepare("SELECT `domain` FROM `domain_admins`
  610. WHERE (
  611. `active`='1'
  612. AND `username` = :username
  613. AND (`domain` = :domain1 OR `domain` = (SELECT `target_domain` FROM `alias_domain` WHERE `alias_domain` = :domain2))
  614. )");
  615. $stmt->execute(array(':username' => $username, ':domain1' => $domain, ':domain2' => $domain));
  616. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  617. if (!empty($num_results)) {
  618. return true;
  619. }
  620. }
  621. return false;
  622. }
  623. function hasMailboxObjectAccess($username, $role, $object) {
  624. global $pdo;
  625. if (isset($_SESSION['access_all_exception']) && $_SESSION['access_all_exception'] == "1") {
  626. return true;
  627. }
  628. if (empty($username) || empty($role) || empty($object)) {
  629. return false;
  630. }
  631. if (!filter_var(html_entity_decode(rawurldecode($username)), FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $username))) {
  632. return false;
  633. }
  634. if ($role != 'admin' && $role != 'domainadmin' && $role != 'user') {
  635. return false;
  636. }
  637. if ($username == $object) {
  638. return true;
  639. }
  640. $stmt = $pdo->prepare("SELECT `domain` FROM `mailbox` WHERE `username` = :object");
  641. $stmt->execute(array(':object' => $object));
  642. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  643. if (isset($row['domain']) && hasDomainAccess($username, $role, $row['domain'])) {
  644. return true;
  645. }
  646. return false;
  647. }
  648. // does also verify mailboxes as a mailbox is a alias == goto
  649. function hasAliasObjectAccess($username, $role, $object) {
  650. global $pdo;
  651. if (isset($_SESSION['access_all_exception']) && $_SESSION['access_all_exception'] == "1") {
  652. return true;
  653. }
  654. if (empty($username) || empty($role) || empty($object)) {
  655. return false;
  656. }
  657. if (!filter_var(html_entity_decode(rawurldecode($username)), FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $username))) {
  658. return false;
  659. }
  660. if ($role != 'admin' && $role != 'domainadmin' && $role != 'user') {
  661. return false;
  662. }
  663. $stmt = $pdo->prepare("SELECT `domain` FROM `alias` WHERE `address` = :object");
  664. $stmt->execute(array(':object' => $object));
  665. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  666. if (isset($row['domain']) && hasDomainAccess($username, $role, $row['domain'])) {
  667. return true;
  668. }
  669. return false;
  670. }
  671. function hasACLAccess($type) {
  672. if (isset($_SESSION['access_all_exception']) && $_SESSION['access_all_exception'] == "1") {
  673. return true;
  674. }
  675. if (isset($_SESSION['acl'][$type]) && $_SESSION['acl'][$type] == "1") {
  676. return true;
  677. }
  678. return false;
  679. }
  680. function pem_to_der($pem_key) {
  681. // Need to remove BEGIN/END PUBLIC KEY
  682. $lines = explode("\n", trim($pem_key));
  683. unset($lines[count($lines)-1]);
  684. unset($lines[0]);
  685. return base64_decode(implode('', $lines));
  686. }
  687. function expand_ipv6($ip) {
  688. $hex = unpack("H*hex", inet_pton($ip));
  689. $ip = substr(preg_replace("/([A-f0-9]{4})/", "$1:", $hex['hex']), 0, -1);
  690. return $ip;
  691. }
  692. function generate_tlsa_digest($hostname, $port, $starttls = null) {
  693. if (!is_valid_domain_name($hostname)) {
  694. return "Not a valid hostname";
  695. }
  696. if (empty($starttls)) {
  697. $context = stream_context_create(array("ssl" => array("capture_peer_cert" => true, 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true)));
  698. $stream = stream_socket_client('ssl://' . $hostname . ':' . $port, $error_nr, $error_msg, 5, STREAM_CLIENT_CONNECT, $context);
  699. if (!$stream) {
  700. $error_msg = isset($error_msg) ? $error_msg : '-';
  701. return $error_nr . ': ' . $error_msg;
  702. }
  703. }
  704. else {
  705. $stream = stream_socket_client('tcp://' . $hostname . ':' . $port, $error_nr, $error_msg, 5);
  706. if (!$stream) {
  707. return $error_nr . ': ' . $error_msg;
  708. }
  709. $banner = fread($stream, 512 );
  710. if (preg_match("/^220/i", $banner)) { // SMTP
  711. fwrite($stream,"HELO tlsa.generator.local\r\n");
  712. fread($stream, 512);
  713. fwrite($stream,"STARTTLS\r\n");
  714. fread($stream, 512);
  715. }
  716. elseif (preg_match("/imap.+starttls/i", $banner)) { // IMAP
  717. fwrite($stream,"A1 STARTTLS\r\n");
  718. fread($stream, 512);
  719. }
  720. elseif (preg_match("/^\+OK/", $banner)) { // POP3
  721. fwrite($stream,"STLS\r\n");
  722. fread($stream, 512);
  723. }
  724. elseif (preg_match("/^OK/m", $banner)) { // Sieve
  725. fwrite($stream,"STARTTLS\r\n");
  726. fread($stream, 512);
  727. }
  728. else {
  729. return 'Unknown banner: "' . htmlspecialchars(trim($banner)) . '"';
  730. }
  731. // Upgrade connection
  732. stream_set_blocking($stream, true);
  733. stream_context_set_option($stream, 'ssl', 'capture_peer_cert', true);
  734. stream_context_set_option($stream, 'ssl', 'verify_peer', false);
  735. stream_context_set_option($stream, 'ssl', 'verify_peer_name', false);
  736. stream_context_set_option($stream, 'ssl', 'allow_self_signed', true);
  737. stream_socket_enable_crypto($stream, true, STREAM_CRYPTO_METHOD_ANY_CLIENT);
  738. stream_set_blocking($stream, false);
  739. }
  740. $params = stream_context_get_params($stream);
  741. if (!empty($params['options']['ssl']['peer_certificate'])) {
  742. $key_resource = openssl_pkey_get_public($params['options']['ssl']['peer_certificate']);
  743. // We cannot get ['rsa']['n'], the binary data would contain BEGIN/END PUBLIC KEY
  744. $key_data = openssl_pkey_get_details($key_resource)['key'];
  745. return '3 1 1 ' . openssl_digest(pem_to_der($key_data), 'sha256');
  746. }
  747. else {
  748. return 'Error: Cannot read peer certificate';
  749. }
  750. }
  751. function alertbox_log_parser($_data) {
  752. global $lang;
  753. if (isset($_data['return'])) {
  754. foreach ($_data['return'] as $return) {
  755. // Get type
  756. $type = $return['type'];
  757. // If a lang[type][msg] string exists, use it as message
  758. if (isset($return['type']) && isset($return['msg']) && !is_array($return['msg'])) {
  759. if (isset($lang[$return['type']][$return['msg']])) {
  760. $msg = $lang[$return['type']][$return['msg']];
  761. }
  762. else {
  763. $msg = $return['msg'];
  764. }
  765. }
  766. // If msg is an array, use first element as language string and run printf on it with remaining array elements
  767. elseif (is_array($return['msg'])) {
  768. $msg = array_shift($return['msg']);
  769. $msg = vsprintf(
  770. $lang[$return['type']][$msg],
  771. $return['msg']
  772. );
  773. }
  774. else {
  775. $msg = '-';
  776. }
  777. $log_array[] = array('msg' => $msg, 'type' => json_encode($type));
  778. }
  779. if (!empty($log_array)) {
  780. return $log_array;
  781. }
  782. }
  783. return false;
  784. }
  785. function verify_salted_hash($hash, $password, $algo, $salt_length) {
  786. // Decode hash
  787. $dhash = base64_decode($hash);
  788. // Get first n bytes of binary which equals a SSHA hash
  789. $ohash = substr($dhash, 0, $salt_length);
  790. // Remove SSHA hash from decoded hash to get original salt string
  791. $osalt = str_replace($ohash, '', $dhash);
  792. // Check single salted SSHA hash against extracted hash
  793. if (hash_equals(hash($algo, $password . $osalt, true), $ohash)) {
  794. return true;
  795. }
  796. return false;
  797. }
  798. function verify_hash($hash, $password) {
  799. if (preg_match('/^{(.+)}(.+)/i', $hash, $hash_array)) {
  800. $scheme = strtoupper($hash_array[1]);
  801. $hash = $hash_array[2];
  802. switch ($scheme) {
  803. case "ARGON2I":
  804. case "ARGON2ID":
  805. case "BLF-CRYPT":
  806. case "CRYPT":
  807. case "DES-CRYPT":
  808. case "MD5-CRYPT":
  809. case "MD5":
  810. case "SHA256-CRYPT":
  811. case "SHA512-CRYPT":
  812. return password_verify($password, $hash);
  813. case "CLEAR":
  814. case "CLEARTEXT":
  815. case "PLAIN":
  816. return $password == $hash;
  817. case "LDAP-MD5":
  818. $hash = base64_decode($hash);
  819. return hash_equals(hash('md5', $password, true), $hash);
  820. case "PBKDF2":
  821. $components = explode('$', $hash);
  822. $salt = $components[2];
  823. $rounds = $components[3];
  824. $hash = $components[4];
  825. return hash_equals(hash_pbkdf2('sha1', $password, $salt, $rounds), $hash);
  826. case "PBKDF2-SHA512":
  827. // Handle FreeIPA-style hash: {PBKDF2-SHA512}10000$<base64_salt>$<base64_hash>
  828. $components = explode('$', $hash);
  829. if (count($components) !== 3) return false;
  830. // 1st part: iteration count (integer)
  831. $iterations = intval($components[0]);
  832. if ($iterations <= 0) return false;
  833. // 2nd part: salt (base64-encoded)
  834. $salt = $components[1];
  835. // 3rd part: hash (base64-encoded)
  836. $stored_hash_b64 = $components[2];
  837. // Decode salt and hash from base64
  838. $salt_bin = base64_decode($salt, true);
  839. $hash_bin = base64_decode($stored_hash_b64, true);
  840. if ($salt_bin === false || $hash_bin === false) return false;
  841. // Get length of hash in bytes
  842. $hash_len = strlen($hash_bin);
  843. if ($hash_len === 0) return false;
  844. // Calculate PBKDF2-SHA512 hash for provided password
  845. $test_hash = hash_pbkdf2('sha512', $password, $salt_bin, $iterations, $hash_len, true);
  846. return hash_equals($hash_bin, $test_hash);
  847. case "PLAIN-MD4":
  848. return hash_equals(hash('md4', $password), $hash);
  849. case "PLAIN-MD5":
  850. return md5($password) == $hash;
  851. case "PLAIN-TRUNC":
  852. $components = explode('-', $hash);
  853. if (count($components) > 1) {
  854. $trunc_len = $components[0];
  855. $trunc_password = $components[1];
  856. return substr($password, 0, $trunc_len) == $trunc_password;
  857. } else {
  858. return $password == $hash;
  859. }
  860. case "SHA":
  861. case "SHA1":
  862. case "SHA256":
  863. case "SHA512":
  864. // SHA is an alias for SHA1
  865. $scheme = $scheme == "SHA" ? "sha1" : strtolower($scheme);
  866. $hash = base64_decode($hash);
  867. return hash_equals(hash($scheme, $password, true), $hash);
  868. case "SMD5":
  869. return verify_salted_hash($hash, $password, 'md5', 16);
  870. case "SSHA":
  871. return verify_salted_hash($hash, $password, 'sha1', 20);
  872. case "SSHA256":
  873. return verify_salted_hash($hash, $password, 'sha256', 32);
  874. case "SSHA512":
  875. return verify_salted_hash($hash, $password, 'sha512', 64);
  876. default:
  877. return false;
  878. }
  879. }
  880. return false;
  881. }
  882. function formatBytes($size, $precision = 2) {
  883. if(!is_numeric($size)) {
  884. return "0";
  885. }
  886. $base = log($size, 1024);
  887. $suffixes = array(' Byte', ' KiB', ' MiB', ' GiB', ' TiB');
  888. if ($size == "0") {
  889. return "0";
  890. }
  891. return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
  892. }
  893. function update_sogo_static_view($mailbox = null) {
  894. if (getenv('SKIP_SOGO') == "y") {
  895. return true;
  896. }
  897. global $pdo;
  898. global $lang;
  899. $mailbox_exists = false;
  900. if ($mailbox !== null) {
  901. // Check if the mailbox exists
  902. $stmt = $pdo->prepare("SELECT username FROM mailbox WHERE username = :mailbox AND active = '1'");
  903. $stmt->execute(array(':mailbox' => $mailbox));
  904. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  905. if ($row){
  906. $mailbox_exists = true;
  907. }
  908. }
  909. // generate random password for sogo to deny direct login
  910. $random_password = base64_encode(openssl_random_pseudo_bytes(24));
  911. $random_salt = base64_encode(openssl_random_pseudo_bytes(16));
  912. $random_hash = '{SSHA256}' . base64_encode(hash('sha256', base64_decode($password) . $salt, true) . $salt);
  913. $subquery = "GROUP BY mailbox.username";
  914. if ($mailbox_exists) {
  915. $subquery = "AND mailbox.username = :mailbox";
  916. }
  917. $query = "INSERT INTO _sogo_static_view (`c_uid`, `domain`, `c_name`, `c_password`, `c_cn`, `mail`, `aliases`, `ad_aliases`, `ext_acl`, `kind`, `multiple_bookings`)
  918. SELECT
  919. mailbox.username,
  920. mailbox.domain,
  921. mailbox.username,
  922. :random_hash,
  923. mailbox.name,
  924. mailbox.username,
  925. IFNULL(GROUP_CONCAT(ga.aliases ORDER BY ga.aliases SEPARATOR ' '), ''),
  926. IFNULL(gda.ad_alias, ''),
  927. IFNULL(external_acl.send_as_acl, ''),
  928. mailbox.kind,
  929. mailbox.multiple_bookings
  930. FROM
  931. mailbox
  932. LEFT OUTER JOIN grouped_mail_aliases ga ON ga.username REGEXP CONCAT('(^|,)', mailbox.username, '($|,)')
  933. LEFT OUTER JOIN grouped_domain_alias_address gda ON gda.username = mailbox.username
  934. LEFT OUTER JOIN grouped_sender_acl_external external_acl ON external_acl.username = mailbox.username
  935. WHERE
  936. mailbox.active = '1'
  937. $subquery
  938. ON DUPLICATE KEY UPDATE
  939. `domain` = VALUES(`domain`),
  940. `c_name` = VALUES(`c_name`),
  941. `c_password` = VALUES(`c_password`),
  942. `c_cn` = VALUES(`c_cn`),
  943. `mail` = VALUES(`mail`),
  944. `aliases` = VALUES(`aliases`),
  945. `ad_aliases` = VALUES(`ad_aliases`),
  946. `ext_acl` = VALUES(`ext_acl`),
  947. `kind` = VALUES(`kind`),
  948. `multiple_bookings` = VALUES(`multiple_bookings`)";
  949. if ($mailbox_exists) {
  950. $stmt = $pdo->prepare($query);
  951. $stmt->execute(array(
  952. ':random_hash' => $random_hash,
  953. ':mailbox' => $mailbox
  954. ));
  955. } else {
  956. $stmt = $pdo->prepare($query);
  957. $stmt->execute(array(
  958. ':random_hash' => $random_hash
  959. ));
  960. }
  961. $stmt = $pdo->query("DELETE FROM _sogo_static_view WHERE `c_uid` NOT IN (SELECT `username` FROM `mailbox` WHERE `active` = '1');");
  962. flush_memcached();
  963. }
  964. function edit_user_account($_data) {
  965. global $lang;
  966. global $pdo;
  967. $_data_log = $_data;
  968. !isset($_data_log['user_new_pass']) ?: $_data_log['user_new_pass'] = '*';
  969. !isset($_data_log['user_new_pass2']) ?: $_data_log['user_new_pass2'] = '*';
  970. !isset($_data_log['user_old_pass']) ?: $_data_log['user_old_pass'] = '*';
  971. $username = $_SESSION['mailcow_cc_username'];
  972. $role = $_SESSION['mailcow_cc_role'];
  973. $password_old = $_data['user_old_pass'];
  974. $pw_recovery_email = $_data['pw_recovery_email'];
  975. if (filter_var($username, FILTER_VALIDATE_EMAIL === false) || $role != 'user') {
  976. $_SESSION['return'][] = array(
  977. 'type' => 'danger',
  978. 'log' => array(__FUNCTION__, $_data_log),
  979. 'msg' => 'access_denied'
  980. );
  981. return false;
  982. }
  983. // edit password
  984. $is_forced_pw_update = !empty($_SESSION['pending_pw_update']);
  985. if (((!empty($password_old) || $is_forced_pw_update) && !empty($_data['user_new_pass']) && !empty($_data['user_new_pass2']))) {
  986. // Only verify old password if this is NOT a forced password update
  987. if (!$is_forced_pw_update) {
  988. $stmt = $pdo->prepare("SELECT `password` FROM `mailbox`
  989. WHERE `kind` NOT REGEXP 'location|thing|group'
  990. AND `username` = :user AND authsource = 'mailcow'");
  991. $stmt->execute(array(':user' => $username));
  992. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  993. if (!verify_hash($row['password'], $password_old)) {
  994. $_SESSION['return'][] = array(
  995. 'type' => 'danger',
  996. 'log' => array(__FUNCTION__, $_data_log),
  997. 'msg' => 'access_denied'
  998. );
  999. return false;
  1000. }
  1001. }
  1002. $password_new = $_data['user_new_pass'];
  1003. $password_new2 = $_data['user_new_pass2'];
  1004. if (password_check($password_new, $password_new2) !== true) {
  1005. return false;
  1006. }
  1007. $password_hashed = hash_password($password_new);
  1008. $stmt = $pdo->prepare("UPDATE `mailbox` SET `password` = :password_hashed,
  1009. `attributes` = JSON_SET(`attributes`, '$.force_pw_update', '0'),
  1010. `attributes` = JSON_SET(`attributes`, '$.passwd_update', NOW())
  1011. WHERE `username` = :username AND authsource = 'mailcow'");
  1012. $stmt->execute(array(
  1013. ':password_hashed' => $password_hashed,
  1014. ':username' => $username
  1015. ));
  1016. $_SESSION['pending_pw_update'] = false;
  1017. update_sogo_static_view();
  1018. }
  1019. // edit password recovery email
  1020. elseif (!empty($password_old) && isset($pw_recovery_email)) {
  1021. if (!isset($_SESSION['acl']['pw_reset']) || $_SESSION['acl']['pw_reset'] != "1" ) {
  1022. $_SESSION['return'][] = array(
  1023. 'type' => 'danger',
  1024. 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),
  1025. 'msg' => 'access_denied'
  1026. );
  1027. return false;
  1028. }
  1029. $stmt = $pdo->prepare("SELECT `password` FROM `mailbox`
  1030. WHERE `kind` NOT REGEXP 'location|thing|group'
  1031. AND `username` = :user AND authsource = 'mailcow'");
  1032. $stmt->execute(array(':user' => $username));
  1033. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1034. if (!verify_hash($row['password'], $password_old)) {
  1035. $_SESSION['return'][] = array(
  1036. 'type' => 'danger',
  1037. 'log' => array(__FUNCTION__, $_data_log),
  1038. 'msg' => 'access_denied'
  1039. );
  1040. return false;
  1041. }
  1042. $pw_recovery_email = (!filter_var($pw_recovery_email, FILTER_VALIDATE_EMAIL)) ? '' : $pw_recovery_email;
  1043. $stmt = $pdo->prepare("UPDATE `mailbox` SET `attributes` = JSON_SET(`attributes`, '$.recovery_email', :recovery_email)
  1044. WHERE `username` = :username AND authsource = 'mailcow'");
  1045. $stmt->execute(array(
  1046. ':recovery_email' => $pw_recovery_email,
  1047. ':username' => $username
  1048. ));
  1049. }
  1050. $_SESSION['return'][] = array(
  1051. 'type' => 'success',
  1052. 'log' => array(__FUNCTION__, $_data_log),
  1053. 'msg' => array('mailbox_modified', htmlspecialchars($username))
  1054. );
  1055. }
  1056. function user_get_alias_details($username) {
  1057. global $pdo;
  1058. global $lang;
  1059. $data['direct_aliases'] = array();
  1060. $data['shared_aliases'] = array();
  1061. if ($_SESSION['mailcow_cc_role'] == "user") {
  1062. $username = $_SESSION['mailcow_cc_username'];
  1063. }
  1064. if (!filter_var($username, FILTER_VALIDATE_EMAIL)) {
  1065. return false;
  1066. }
  1067. if (!hasMailboxObjectAccess($username, $_SESSION['mailcow_cc_role'], $username)) {
  1068. return false;
  1069. }
  1070. $data['address'] = $username;
  1071. $stmt = $pdo->prepare("SELECT `address` AS `shared_aliases`, `public_comment` FROM `alias`
  1072. WHERE `goto` REGEXP :username_goto
  1073. AND `address` NOT LIKE '@%'
  1074. AND `goto` != :username_goto2
  1075. AND `address` != :username_address");
  1076. $stmt->execute(array(
  1077. ':username_goto' => '(^|,)'.preg_quote($username, '/').'($|,)',
  1078. ':username_goto2' => $username,
  1079. ':username_address' => $username
  1080. ));
  1081. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1082. while ($row = array_shift($run)) {
  1083. $data['shared_aliases'][$row['shared_aliases']]['public_comment'] = htmlspecialchars($row['public_comment']);
  1084. //$data['shared_aliases'][] = $row['shared_aliases'];
  1085. }
  1086. $stmt = $pdo->prepare("SELECT `address` AS `direct_aliases`, `public_comment` FROM `alias`
  1087. WHERE `goto` = :username_goto
  1088. AND `address` NOT LIKE '@%'
  1089. AND `address` != :username_address");
  1090. $stmt->execute(
  1091. array(
  1092. ':username_goto' => $username,
  1093. ':username_address' => $username
  1094. ));
  1095. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1096. while ($row = array_shift($run)) {
  1097. $data['direct_aliases'][$row['direct_aliases']]['public_comment'] = htmlspecialchars($row['public_comment']);
  1098. }
  1099. $stmt = $pdo->prepare("SELECT CONCAT(local_part, '@', alias_domain) AS `ad_alias`, `alias_domain` FROM `mailbox`
  1100. LEFT OUTER JOIN `alias_domain` on `target_domain` = `domain`
  1101. WHERE `username` = :username ;");
  1102. $stmt->execute(array(':username' => $username));
  1103. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1104. while ($row = array_shift($run)) {
  1105. if (empty($row['ad_alias'])) {
  1106. continue;
  1107. }
  1108. $data['direct_aliases'][$row['ad_alias']]['public_comment'] = $lang['add']['alias_domain'];
  1109. $data['alias_domains'][] = $row['alias_domain'];
  1110. }
  1111. $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 '@%';");
  1112. $stmt->execute(array(':username' => $username));
  1113. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1114. while ($row = array_shift($run)) {
  1115. $data['aliases_also_send_as'] = $row['send_as'];
  1116. }
  1117. $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 '@%';");
  1118. $stmt->execute(array(':username' => $username));
  1119. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1120. while ($row = array_shift($run)) {
  1121. $data['aliases_send_as_all'] = $row['send_as'];
  1122. }
  1123. $stmt = $pdo->prepare("SELECT IFNULL(GROUP_CONCAT(`address` SEPARATOR ', '), '') as `address` FROM `alias` WHERE `goto` REGEXP :username AND `address` LIKE '@%';");
  1124. $stmt->execute(array(':username' => '(^|,)'.preg_quote($username, '/').'($|,)'));
  1125. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1126. while ($row = array_shift($run)) {
  1127. $data['is_catch_all'] = $row['address'];
  1128. }
  1129. return $data;
  1130. }
  1131. function is_valid_domain_name($domain_name, $options = array()) {
  1132. if (empty($domain_name)) {
  1133. return false;
  1134. }
  1135. // Convert domain name to ASCII for validation
  1136. $domain_name = idn_to_ascii($domain_name, 0, INTL_IDNA_VARIANT_UTS46);
  1137. if (isset($options['allow_wildcard']) && $options['allow_wildcard'] == true) {
  1138. // Remove '*.' if wildcard subdomains are allowed
  1139. if (strpos($domain_name, '*.') === 0) {
  1140. $domain_name = substr($domain_name, 2);
  1141. }
  1142. }
  1143. return (preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $domain_name)
  1144. && preg_match("/^.{1,253}$/", $domain_name)
  1145. && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $domain_name));
  1146. }
  1147. function set_tfa($_data) {
  1148. global $pdo;
  1149. global $yubi;
  1150. global $tfa;
  1151. global $iam_settings;
  1152. $_data_log = $_data;
  1153. !isset($_data_log['confirm_password']) ?: $_data_log['confirm_password'] = '*';
  1154. // skip password check if this is a forced TFA enrollment after login
  1155. if (!empty($_SESSION['pending_tfa_setup'])) {
  1156. $username = $_SESSION['mailcow_cc_username'];
  1157. if (empty($username) || !isset($_SESSION['mailcow_cc_role'])) {
  1158. $_SESSION['return'][] = array('type' => 'danger', 'log' => array(__FUNCTION__, $_data_log), 'msg' => 'access_denied');
  1159. return false;
  1160. }
  1161. } else {
  1162. $username = $_SESSION['mailcow_cc_username'];
  1163. $access_denied = null;
  1164. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) $access_denied = true;
  1165. // check admin password
  1166. if ($access_denied === null) {
  1167. $stmt = $pdo->prepare("SELECT `password` FROM `admin` WHERE `username` = :username");
  1168. $stmt->execute(array(':username' => $username));
  1169. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1170. if ($row) {
  1171. if (!verify_hash($row['password'], $_data["confirm_password"])) $access_denied = true;
  1172. else $access_denied = false;
  1173. }
  1174. }
  1175. // check mailbox password
  1176. if ($access_denied === null) {
  1177. $stmt = $pdo->prepare("SELECT `password`, `authsource` FROM `mailbox` WHERE `username` = :username");
  1178. $stmt->execute(array(':username' => $username));
  1179. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1180. if ($row) {
  1181. if ($row['authsource'] == 'ldap'){
  1182. if (!ldap_mbox_login($username, $_data["confirm_password"], $iam_settings)) $access_denied = true;
  1183. else $access_denied = false;
  1184. } else {
  1185. if (!verify_hash($row['password'], $_data["confirm_password"])) $access_denied = true;
  1186. else $access_denied = false;
  1187. }
  1188. }
  1189. }
  1190. if ($access_denied) {
  1191. $_SESSION['return'][] = array('type' => 'danger', 'log' => array(__FUNCTION__, $_data_log), 'msg' => 'access_denied');
  1192. return false;
  1193. }
  1194. }
  1195. switch ($_data["tfa_method"]) {
  1196. case "yubi_otp":
  1197. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  1198. $yubico_id = $_data['yubico_id'];
  1199. $yubico_key = $_data['yubico_key'];
  1200. $yubi = new Auth_Yubico($yubico_id, $yubico_key);
  1201. if (!$yubi) {
  1202. $_SESSION['return'][] = array(
  1203. 'type' => 'danger',
  1204. 'log' => array(__FUNCTION__, $_data_log),
  1205. 'msg' => 'access_denied'
  1206. );
  1207. return false;
  1208. }
  1209. if (!ctype_alnum($_data["otp_token"]) || strlen($_data["otp_token"]) != 44) {
  1210. $_SESSION['return'][] = array(
  1211. 'type' => 'danger',
  1212. 'log' => array(__FUNCTION__, $_data_log),
  1213. 'msg' => 'tfa_token_invalid'
  1214. );
  1215. return false;
  1216. }
  1217. $yauth = $yubi->verify($_data["otp_token"]);
  1218. if (PEAR::isError($yauth)) {
  1219. $_SESSION['return'][] = array(
  1220. 'type' => 'danger',
  1221. 'log' => array(__FUNCTION__, $_data_log),
  1222. 'msg' => array('yotp_verification_failed', $yauth->getMessage())
  1223. );
  1224. return false;
  1225. }
  1226. try {
  1227. // We could also do a modhex translation here
  1228. $yubico_modhex_id = substr($_data["otp_token"], 0, 12);
  1229. $stmt = $pdo->prepare("DELETE FROM `tfa`
  1230. WHERE `username` = :username
  1231. AND (`authmech` = 'yubi_otp' AND `secret` LIKE :modhex)");
  1232. $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id));
  1233. $stmt = $pdo->prepare("INSERT INTO `tfa` (`key_id`, `username`, `authmech`, `active`, `secret`) VALUES
  1234. (:key_id, :username, 'yubi_otp', '1', :secret)");
  1235. $stmt->execute(array(':key_id' => $key_id, ':username' => $username, ':secret' => $yubico_id . ':' . $yubico_key . ':' . $yubico_modhex_id));
  1236. }
  1237. catch (PDOException $e) {
  1238. $_SESSION['return'][] = array(
  1239. 'type' => 'danger',
  1240. 'log' => array(__FUNCTION__, $_data_log),
  1241. 'msg' => array('mysql_error', $e)
  1242. );
  1243. return false;
  1244. }
  1245. unset($_SESSION['pending_tfa_setup']);
  1246. $_SESSION['return'][] = array(
  1247. 'type' => 'success',
  1248. 'log' => array(__FUNCTION__, $_data_log),
  1249. 'msg' => array('object_modified', htmlspecialchars($username))
  1250. );
  1251. break;
  1252. case "totp":
  1253. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  1254. if ($tfa->verifyCode($_POST['totp_secret'], $_POST['totp_confirm_token']) === true) {
  1255. //$stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
  1256. //$stmt->execute(array(':username' => $username));
  1257. $stmt = $pdo->prepare("INSERT INTO `tfa` (`username`, `key_id`, `authmech`, `secret`, `active`) VALUES (?, ?, 'totp', ?, '1')");
  1258. $stmt->execute(array($username, $key_id, $_POST['totp_secret']));
  1259. unset($_SESSION['pending_tfa_setup']);
  1260. $_SESSION['return'][] = array(
  1261. 'type' => 'success',
  1262. 'log' => array(__FUNCTION__, $_data_log),
  1263. 'msg' => array('object_modified', $username)
  1264. );
  1265. }
  1266. else {
  1267. $_SESSION['return'][] = array(
  1268. 'type' => 'danger',
  1269. 'log' => array(__FUNCTION__, $_data_log),
  1270. 'msg' => 'totp_verification_failed'
  1271. );
  1272. }
  1273. break;
  1274. case "webauthn":
  1275. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  1276. $stmt = $pdo->prepare("INSERT INTO `tfa` (`username`, `key_id`, `authmech`, `keyHandle`, `publicKey`, `certificate`, `counter`, `active`)
  1277. VALUES (?, ?, 'webauthn', ?, ?, ?, ?, '1')");
  1278. $stmt->execute(array(
  1279. $username,
  1280. $key_id,
  1281. base64_encode($_data['registration']->credentialId),
  1282. $_data['registration']->credentialPublicKey,
  1283. $_data['registration']->certificate,
  1284. 0
  1285. ));
  1286. unset($_SESSION['pending_tfa_setup']);
  1287. $_SESSION['return'][] = array(
  1288. 'type' => 'success',
  1289. 'log' => array(__FUNCTION__, $_data_log),
  1290. 'msg' => array('object_modified', $username)
  1291. );
  1292. break;
  1293. case "none":
  1294. // Block TFA removal if force_tfa policy is active
  1295. $is_forced_tfa = false;
  1296. if ($_SESSION['mailcow_cc_role'] === 'user') {
  1297. $stmt_check = $pdo->prepare("SELECT JSON_EXTRACT(`attributes`, '$.force_tfa') FROM `mailbox` WHERE `username` = ?");
  1298. $stmt_check->execute(array($username));
  1299. $is_forced_tfa = ($stmt_check->fetchColumn() == '1');
  1300. } else {
  1301. $stmt_check = $pdo->prepare("SELECT JSON_EXTRACT(`attributes`, '$.force_tfa') FROM `admin` WHERE `username` = ?");
  1302. $stmt_check->execute(array($username));
  1303. $is_forced_tfa = ($stmt_check->fetchColumn() == '1');
  1304. }
  1305. if ($is_forced_tfa) {
  1306. $_SESSION['return'][] = array(
  1307. 'type' => 'danger',
  1308. 'log' => array(__FUNCTION__, $_data_log),
  1309. 'msg' => 'tfa_removal_blocked'
  1310. );
  1311. return false;
  1312. }
  1313. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
  1314. $stmt->execute(array(':username' => $username));
  1315. $_SESSION['return'][] = array(
  1316. 'type' => 'success',
  1317. 'log' => array(__FUNCTION__, $_data_log),
  1318. 'msg' => array('object_modified', htmlspecialchars($username))
  1319. );
  1320. break;
  1321. }
  1322. }
  1323. function fido2($_data) {
  1324. global $pdo;
  1325. global $WebAuthn;
  1326. $_data_log = $_data;
  1327. // Not logging registration data, only actions
  1328. // Silent errors for "get" requests
  1329. switch ($_data["action"]) {
  1330. case "register":
  1331. $username = $_SESSION['mailcow_cc_username'];
  1332. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1333. $_SESSION['return'][] = array(
  1334. 'type' => 'danger',
  1335. 'log' => array(__FUNCTION__, $_data["action"]),
  1336. 'msg' => 'access_denied'
  1337. );
  1338. return false;
  1339. }
  1340. $stmt = $pdo->prepare("INSERT INTO `fido2` (`username`, `rpId`, `credentialPublicKey`, `certificateChain`, `certificate`, `certificateIssuer`, `certificateSubject`, `signatureCounter`, `AAGUID`, `credentialId`)
  1341. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
  1342. $stmt->execute(array(
  1343. $username,
  1344. $_data['registration']->rpId,
  1345. $_data['registration']->credentialPublicKey,
  1346. $_data['registration']->certificateChain,
  1347. $_data['registration']->certificate,
  1348. $_data['registration']->certificateIssuer,
  1349. $_data['registration']->certificateSubject,
  1350. $_data['registration']->signatureCounter,
  1351. $_data['registration']->AAGUID,
  1352. $_data['registration']->credentialId)
  1353. );
  1354. $_SESSION['return'][] = array(
  1355. 'type' => 'success',
  1356. 'log' => array(__FUNCTION__, $_data["action"]),
  1357. 'msg' => array('object_modified', $username)
  1358. );
  1359. break;
  1360. case "get_user_cids":
  1361. // Used to exclude existing CredentialIds while registering
  1362. $username = $_SESSION['mailcow_cc_username'];
  1363. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1364. return false;
  1365. }
  1366. $stmt = $pdo->prepare("SELECT `credentialId` FROM `fido2` WHERE `username` = :username");
  1367. $stmt->execute(array(':username' => $username));
  1368. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1369. while($row = array_shift($rows)) {
  1370. $cids[] = $row['credentialId'];
  1371. }
  1372. return $cids;
  1373. break;
  1374. case "get_all_cids":
  1375. // Only needed when using fido2 with username
  1376. $stmt = $pdo->query("SELECT `credentialId` FROM `fido2`");
  1377. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1378. while($row = array_shift($rows)) {
  1379. $cids[] = $row['credentialId'];
  1380. }
  1381. return $cids;
  1382. break;
  1383. case "get_by_b64cid":
  1384. if (!isset($_data['cid']) || empty($_data['cid'])) {
  1385. return false;
  1386. }
  1387. $stmt = $pdo->prepare("SELECT `certificateSubject`, `username`, `credentialPublicKey`, SHA2(`credentialId`, 256) AS `cid` FROM `fido2` WHERE `credentialId` = :cid");
  1388. $stmt->execute(array(':cid' => base64_decode($_data['cid'])));
  1389. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1390. if (empty($row) || empty($row['credentialPublicKey']) || empty($row['username'])) {
  1391. return false;
  1392. }
  1393. $data['pub_key'] = $row['credentialPublicKey'];
  1394. $data['username'] = $row['username'];
  1395. $data['subject'] = $row['certificateSubject'];
  1396. $data['cid'] = $row['cid'];
  1397. return $data;
  1398. break;
  1399. case "get_friendly_names":
  1400. $username = $_SESSION['mailcow_cc_username'];
  1401. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1402. return false;
  1403. }
  1404. $stmt = $pdo->prepare("SELECT SHA2(`credentialId`, 256) AS `cid`, `created`, `certificateSubject`, `friendlyName` FROM `fido2` WHERE `username` = :username");
  1405. $stmt->execute(array(':username' => $username));
  1406. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1407. while($row = array_shift($rows)) {
  1408. $fns[] = array(
  1409. "subject" => (empty($row['certificateSubject']) ? 'Unknown (' . $row['created'] . ')' : $row['certificateSubject']),
  1410. "fn" => $row['friendlyName'],
  1411. "cid" => $row['cid']
  1412. );
  1413. }
  1414. return $fns;
  1415. break;
  1416. case "unset_fido2_key":
  1417. $username = $_SESSION['mailcow_cc_username'];
  1418. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1419. $_SESSION['return'][] = array(
  1420. 'type' => 'danger',
  1421. 'log' => array(__FUNCTION__, $_data["action"]),
  1422. 'msg' => 'access_denied'
  1423. );
  1424. return false;
  1425. }
  1426. $stmt = $pdo->prepare("DELETE FROM `fido2` WHERE `username` = :username AND SHA2(`credentialId`, 256) = :cid");
  1427. $stmt->execute(array(
  1428. ':username' => $username,
  1429. ':cid' => $_data['post_data']['unset_fido2_key']
  1430. ));
  1431. $_SESSION['return'][] = array(
  1432. 'type' => 'success',
  1433. 'log' => array(__FUNCTION__, $_data_log),
  1434. 'msg' => array('object_modified', htmlspecialchars($username))
  1435. );
  1436. break;
  1437. case "edit_fn":
  1438. $username = $_SESSION['mailcow_cc_username'];
  1439. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1440. $_SESSION['return'][] = array(
  1441. 'type' => 'danger',
  1442. 'log' => array(__FUNCTION__, $_data["action"]),
  1443. 'msg' => 'access_denied'
  1444. );
  1445. return false;
  1446. }
  1447. $stmt = $pdo->prepare("UPDATE `fido2` SET `friendlyName` = :friendlyName WHERE SHA2(`credentialId`, 256) = :cid AND `username` = :username");
  1448. $stmt->execute(array(
  1449. ':username' => $username,
  1450. ':friendlyName' => $_data['fido2_attrs']['fido2_fn'],
  1451. ':cid' => $_data['fido2_attrs']['fido2_cid']
  1452. ));
  1453. $_SESSION['return'][] = array(
  1454. 'type' => 'success',
  1455. 'log' => array(__FUNCTION__, $_data_log),
  1456. 'msg' => array('object_modified', htmlspecialchars($username))
  1457. );
  1458. break;
  1459. case "verify":
  1460. $role = "";
  1461. $tokenData = json_decode($_data['token']);
  1462. $clientDataJSON = base64_decode($tokenData->clientDataJSON);
  1463. $authenticatorData = base64_decode($tokenData->authenticatorData);
  1464. $signature = base64_decode($tokenData->signature);
  1465. $id = base64_decode($tokenData->id);
  1466. $challenge = $_SESSION['challenge'];
  1467. $process_fido2 = fido2(array("action" => "get_by_b64cid", "cid" => $tokenData->id));
  1468. if ($process_fido2['pub_key'] === false) {
  1469. $_SESSION['return'][] = array(
  1470. 'type' => 'danger',
  1471. 'log' => array("fido2_login", $_data['user'], $process_fido2['username']),
  1472. 'msg' => "login_failed"
  1473. );
  1474. return false;
  1475. }
  1476. try {
  1477. $WebAuthn->processGet($clientDataJSON, $authenticatorData, $signature, $process_fido2['pub_key'], $challenge, null, $GLOBALS['FIDO2_UV_FLAG_LOGIN'], $GLOBALS['FIDO2_USER_PRESENT_FLAG']);
  1478. }
  1479. catch (Throwable $ex) {
  1480. unset($process_fido2);
  1481. $_SESSION['return'][] = array(
  1482. 'type' => 'danger',
  1483. 'log' => array("fido2_login", $_data['user'], $process_fido2['username'], $ex->getMessage()),
  1484. 'msg' => "login_failed"
  1485. );
  1486. return false;
  1487. }
  1488. $return = new stdClass();
  1489. $return->success = true;
  1490. $stmt = $pdo->prepare("SELECT `superadmin` FROM `admin` WHERE `username` = :username");
  1491. $stmt->execute(array(':username' => $process_fido2['username']));
  1492. $obj_props = $stmt->fetch(PDO::FETCH_ASSOC);
  1493. if ($obj_props['superadmin'] === 1 && (!$_data['user'] || $_data['user'] == "admin")) {
  1494. $role = "admin";
  1495. }
  1496. elseif ($obj_props['superadmin'] === 0 && (!$_data['user'] || $_data['user'] == "domainadmin")) {
  1497. $role = "domainadmin";
  1498. }
  1499. elseif (!isset($obj_props['superadmin']) && (!$_data['user'] || $_data['user'] == "user")) {
  1500. $stmt = $pdo->prepare("SELECT `username` FROM `mailbox` WHERE `username` = :username");
  1501. $stmt->execute(array(':username' => $process_fido2['username']));
  1502. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1503. if ($row['username'] == $process_fido2['username']) {
  1504. $role = "user";
  1505. }
  1506. }
  1507. else {
  1508. $_SESSION['return'][] = array(
  1509. 'type' => 'danger',
  1510. 'log' => array("fido2_login", $_data['user'], $process_fido2['username']),
  1511. 'msg' => 'login_failed'
  1512. );
  1513. return false;
  1514. }
  1515. if (empty($role)) {
  1516. session_unset();
  1517. session_destroy();
  1518. $_SESSION['return'][] = array(
  1519. 'type' => 'danger',
  1520. 'log' => array("fido2_login", $_data['user'], $process_fido2['username']),
  1521. 'msg' => 'login_failed'
  1522. );
  1523. return false;
  1524. }
  1525. unset($_SESSION["challenge"]);
  1526. $_SESSION['return'][] = array(
  1527. 'type' => 'success',
  1528. 'log' => array("fido2_login", $_data['user'], $process_fido2['username']),
  1529. 'msg' => array('logged_in_as', $process_fido2['username'])
  1530. );
  1531. return array(
  1532. "role" => $role,
  1533. "username" => $process_fido2['username'],
  1534. "cid" => $process_fido2['cid']
  1535. );
  1536. break;
  1537. }
  1538. }
  1539. function unset_tfa_key($_data) {
  1540. // Can only unset own keys
  1541. // Needs at least one key left
  1542. global $pdo;
  1543. global $lang;
  1544. $_data_log = $_data;
  1545. $access_denied = null;
  1546. $id = intval($_data['unset_tfa_key']);
  1547. $username = $_SESSION['mailcow_cc_username'];
  1548. // check for empty user and role
  1549. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) $access_denied = true;
  1550. try {
  1551. if (!is_numeric($id)) $access_denied = true;
  1552. // set access_denied error
  1553. if ($access_denied){
  1554. $_SESSION['return'][] = array(
  1555. 'type' => 'danger',
  1556. 'log' => array(__FUNCTION__, $_data_log),
  1557. 'msg' => 'access_denied'
  1558. );
  1559. return false;
  1560. }
  1561. // Block key removal if force_tfa policy is active
  1562. $is_forced_tfa = false;
  1563. if ($_SESSION['mailcow_cc_role'] === 'user') {
  1564. $stmt_check = $pdo->prepare("SELECT JSON_EXTRACT(`attributes`, '$.force_tfa') FROM `mailbox` WHERE `username` = ?");
  1565. $stmt_check->execute(array($username));
  1566. $is_forced_tfa = ($stmt_check->fetchColumn() == '1');
  1567. } else {
  1568. $stmt_check = $pdo->prepare("SELECT JSON_EXTRACT(`attributes`, '$.force_tfa') FROM `admin` WHERE `username` = ?");
  1569. $stmt_check->execute(array($username));
  1570. $is_forced_tfa = ($stmt_check->fetchColumn() == '1');
  1571. }
  1572. if ($is_forced_tfa) {
  1573. $_SESSION['return'][] = array(
  1574. 'type' => 'danger',
  1575. 'log' => array(__FUNCTION__, $_data_log),
  1576. 'msg' => 'tfa_removal_blocked'
  1577. );
  1578. return false;
  1579. }
  1580. // check if it's last key
  1581. $stmt = $pdo->prepare("SELECT COUNT(*) AS `keys` FROM `tfa`
  1582. WHERE `username` = :username AND `active` = '1'");
  1583. $stmt->execute(array(':username' => $username));
  1584. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1585. if ($row['keys'] == "1") {
  1586. $_SESSION['return'][] = array(
  1587. 'type' => 'danger',
  1588. 'log' => array(__FUNCTION__, $_data_log),
  1589. 'msg' => 'last_key'
  1590. );
  1591. return false;
  1592. }
  1593. // delete key
  1594. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username AND `id` = :id");
  1595. $stmt->execute(array(':username' => $username, ':id' => $id));
  1596. $_SESSION['return'][] = array(
  1597. 'type' => 'success',
  1598. 'log' => array(__FUNCTION__, $_data_log),
  1599. 'msg' => array('object_modified', $username)
  1600. );
  1601. }
  1602. catch (PDOException $e) {
  1603. $_SESSION['return'][] = array(
  1604. 'type' => 'danger',
  1605. 'log' => array(__FUNCTION__, $_data_log),
  1606. 'msg' => array('mysql_error', $e)
  1607. );
  1608. return false;
  1609. }
  1610. }
  1611. function tfa_exists($username) {
  1612. global $pdo;
  1613. if (empty($username)) {
  1614. return false;
  1615. }
  1616. $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM `tfa` WHERE `username` = :username");
  1617. $stmt->execute(array(':username' => $username));
  1618. return $stmt->fetch(PDO::FETCH_ASSOC)['count'] > 0;
  1619. }
  1620. function get_tfa($username = null, $id = null) {
  1621. global $pdo;
  1622. if (empty($username) && isset($_SESSION['mailcow_cc_username'])) {
  1623. $username = $_SESSION['mailcow_cc_username'];
  1624. }
  1625. elseif (empty($username)) {
  1626. return false;
  1627. }
  1628. if (!isset($id)){
  1629. // fetch all tfa methods - just get information about possible authenticators
  1630. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `authmech` FROM `tfa`
  1631. WHERE `username` = :username AND `active` = '1'");
  1632. $stmt->execute(array(':username' => $username));
  1633. $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1634. // no tfa methods found
  1635. if (count($results) == 0) {
  1636. $data['name'] = 'none';
  1637. $data['pretty'] = "-";
  1638. $data['additional'] = array();
  1639. return $data;
  1640. }
  1641. $data['additional'] = $results;
  1642. return $data;
  1643. } else {
  1644. // fetch specific authenticator details by id
  1645. $stmt = $pdo->prepare("SELECT * FROM `tfa`
  1646. WHERE `username` = :username AND `id` = :id AND `active` = '1'");
  1647. $stmt->execute(array(':username' => $username, ':id' => $id));
  1648. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1649. if (isset($row["authmech"])) {
  1650. switch ($row["authmech"]) {
  1651. case "yubi_otp":
  1652. $data['name'] = "yubi_otp";
  1653. $data['pretty'] = "Yubico OTP";
  1654. $stmt = $pdo->prepare("SELECT `id`, `key_id`, RIGHT(`secret`, 12) AS 'modhex' FROM `tfa` WHERE `authmech` = 'yubi_otp' AND `username` = :username AND `id` = :id");
  1655. $stmt->execute(array(
  1656. ':username' => $username,
  1657. ':id' => $id
  1658. ));
  1659. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1660. while($row = array_shift($rows)) {
  1661. $data['additional'][] = $row;
  1662. }
  1663. return $data;
  1664. break;
  1665. // u2f - deprecated, should be removed
  1666. case "u2f":
  1667. $data['name'] = "u2f";
  1668. $data['pretty'] = "Fido U2F";
  1669. $stmt = $pdo->prepare("SELECT `id`, `key_id` FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username AND `id` = :id");
  1670. $stmt->execute(array(
  1671. ':username' => $username,
  1672. ':id' => $id
  1673. ));
  1674. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1675. while($row = array_shift($rows)) {
  1676. $data['additional'][] = $row;
  1677. }
  1678. return $data;
  1679. break;
  1680. case "hotp":
  1681. $data['name'] = "hotp";
  1682. $data['pretty'] = "HMAC-based OTP";
  1683. return $data;
  1684. break;
  1685. case "totp":
  1686. $data['name'] = "totp";
  1687. $data['pretty'] = "Time-based OTP";
  1688. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `secret` FROM `tfa` WHERE `authmech` = 'totp' AND `username` = :username AND `id` = :id");
  1689. $stmt->execute(array(
  1690. ':username' => $username,
  1691. ':id' => $id
  1692. ));
  1693. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1694. while($row = array_shift($rows)) {
  1695. $data['additional'][] = $row;
  1696. }
  1697. return $data;
  1698. break;
  1699. case "webauthn":
  1700. $data['name'] = "webauthn";
  1701. $data['pretty'] = "WebAuthn";
  1702. $stmt = $pdo->prepare("SELECT `id`, `key_id` FROM `tfa` WHERE `authmech` = 'webauthn' AND `username` = :username AND `id` = :id");
  1703. $stmt->execute(array(
  1704. ':username' => $username,
  1705. ':id' => $id
  1706. ));
  1707. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1708. while($row = array_shift($rows)) {
  1709. $data['additional'][] = $row;
  1710. }
  1711. return $data;
  1712. break;
  1713. default:
  1714. $data['name'] = 'none';
  1715. $data['pretty'] = "-";
  1716. return $data;
  1717. break;
  1718. }
  1719. }
  1720. else {
  1721. $data['name'] = 'none';
  1722. $data['pretty'] = "-";
  1723. return $data;
  1724. }
  1725. }
  1726. }
  1727. function verify_tfa_login($username, $_data) {
  1728. global $pdo;
  1729. global $yubi;
  1730. global $u2f;
  1731. global $tfa;
  1732. global $WebAuthn;
  1733. if ($_data['tfa_method'] != 'u2f'){
  1734. switch ($_data["tfa_method"]) {
  1735. case "yubi_otp":
  1736. if (!ctype_alnum($_data['token']) || strlen($_data['token']) != 44) {
  1737. $_SESSION['return'][] = array(
  1738. 'type' => 'danger',
  1739. 'log' => array(__FUNCTION__, $username, '*'),
  1740. 'msg' => array('yotp_verification_failed', 'token length error')
  1741. );
  1742. return false;
  1743. }
  1744. $yubico_modhex_id = substr($_data['token'], 0, 12);
  1745. $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
  1746. WHERE `username` = :username
  1747. AND `authmech` = 'yubi_otp'
  1748. AND `active` = '1'
  1749. AND `secret` LIKE :modhex");
  1750. $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id));
  1751. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1752. $yubico_auth = explode(':', $row['secret']);
  1753. $yubi = new Auth_Yubico($yubico_auth[0], $yubico_auth[1]);
  1754. $yauth = $yubi->verify($_data['token']);
  1755. if (PEAR::isError($yauth)) {
  1756. $_SESSION['return'][] = array(
  1757. 'type' => 'danger',
  1758. 'log' => array(__FUNCTION__, $username, '*'),
  1759. 'msg' => array('yotp_verification_failed', $yauth->getMessage())
  1760. );
  1761. return false;
  1762. }
  1763. else {
  1764. $_SESSION['tfa_id'] = $row['id'];
  1765. $_SESSION['return'][] = array(
  1766. 'type' => 'success',
  1767. 'log' => array(__FUNCTION__, $username, '*'),
  1768. 'msg' => 'verified_yotp_login'
  1769. );
  1770. return true;
  1771. }
  1772. $_SESSION['return'][] = array(
  1773. 'type' => 'danger',
  1774. 'log' => array(__FUNCTION__, $username, '*'),
  1775. 'msg' => array('yotp_verification_failed', 'unknown')
  1776. );
  1777. return false;
  1778. break;
  1779. case "hotp":
  1780. return false;
  1781. break;
  1782. case "totp":
  1783. try {
  1784. $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
  1785. WHERE `username` = :username
  1786. AND `authmech` = 'totp'
  1787. AND `id` = :id
  1788. AND `active`='1'");
  1789. $stmt->execute(array(':username' => $username, ':id' => $_data['id']));
  1790. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1791. foreach ($rows as $row) {
  1792. if ($tfa->verifyCode($row['secret'], $_data['token']) === true) {
  1793. $_SESSION['tfa_id'] = $row['id'];
  1794. $_SESSION['return'][] = array(
  1795. 'type' => 'success',
  1796. 'log' => array(__FUNCTION__, $username, '*'),
  1797. 'msg' => 'verified_totp_login'
  1798. );
  1799. return true;
  1800. }
  1801. }
  1802. $_SESSION['return'][] = array(
  1803. 'type' => 'danger',
  1804. 'log' => array(__FUNCTION__, $username, '*'),
  1805. 'msg' => 'totp_verification_failed'
  1806. );
  1807. return false;
  1808. }
  1809. catch (PDOException $e) {
  1810. $_SESSION['return'][] = array(
  1811. 'type' => 'danger',
  1812. 'log' => array(__FUNCTION__, $username, '*'),
  1813. 'msg' => array('mysql_error', $e)
  1814. );
  1815. return false;
  1816. }
  1817. break;
  1818. case "webauthn":
  1819. $tokenData = json_decode($_data['token']);
  1820. $clientDataJSON = base64_decode($tokenData->clientDataJSON);
  1821. $authenticatorData = base64_decode($tokenData->authenticatorData);
  1822. $signature = base64_decode($tokenData->signature);
  1823. $id = base64_decode($tokenData->id);
  1824. $challenge = $_SESSION['challenge'];
  1825. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `keyHandle`, `username`, `publicKey` FROM `tfa` WHERE `id` = :id AND `active`='1'");
  1826. $stmt->execute(array(':id' => $_data['id']));
  1827. $process_webauthn = $stmt->fetch(PDO::FETCH_ASSOC);
  1828. if (empty($process_webauthn)){
  1829. $_SESSION['return'][] = array(
  1830. 'type' => 'danger',
  1831. 'log' => array(__FUNCTION__, $username, '*'),
  1832. 'msg' => array('webauthn_authenticator_failed')
  1833. );
  1834. return false;
  1835. }
  1836. if (empty($process_webauthn['publicKey']) || $process_webauthn['publicKey'] === false) {
  1837. $_SESSION['return'][] = array(
  1838. 'type' => 'danger',
  1839. 'log' => array(__FUNCTION__, $username, '*'),
  1840. 'msg' => array('webauthn_publickey_failed')
  1841. );
  1842. return false;
  1843. }
  1844. if ($process_webauthn['username'] != $_SESSION['pending_mailcow_cc_username']){
  1845. $_SESSION['return'][] = array(
  1846. 'type' => 'danger',
  1847. 'log' => array(__FUNCTION__, $username, '*'),
  1848. 'msg' => array('webauthn_username_failed')
  1849. );
  1850. return false;
  1851. }
  1852. try {
  1853. $WebAuthn->processGet($clientDataJSON, $authenticatorData, $signature, $process_webauthn['publicKey'], $challenge, null, $GLOBALS['WEBAUTHN_UV_FLAG_LOGIN'], $GLOBALS['WEBAUTHN_USER_PRESENT_FLAG']);
  1854. }
  1855. catch (Throwable $ex) {
  1856. $_SESSION['return'][] = array(
  1857. 'type' => 'danger',
  1858. 'log' => array(__FUNCTION__, $username, '*'),
  1859. 'msg' => array('webauthn_verification_failed', $ex->getMessage())
  1860. );
  1861. return false;
  1862. }
  1863. $stmt = $pdo->prepare("SELECT `superadmin` FROM `admin` WHERE `username` = :username");
  1864. $stmt->execute(array(':username' => $process_webauthn['username']));
  1865. $obj_props = $stmt->fetch(PDO::FETCH_ASSOC);
  1866. if ($obj_props['superadmin'] === 1) {
  1867. $_SESSION["mailcow_cc_role"] = "admin";
  1868. }
  1869. elseif ($obj_props['superadmin'] === 0) {
  1870. $_SESSION["mailcow_cc_role"] = "domainadmin";
  1871. }
  1872. else {
  1873. $stmt = $pdo->prepare("SELECT `username` FROM `mailbox` WHERE `username` = :username");
  1874. $stmt->execute(array(':username' => $process_webauthn['username']));
  1875. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1876. if (!empty($row['username'])) {
  1877. $_SESSION["mailcow_cc_role"] = "user";
  1878. } else {
  1879. $_SESSION['return'][] = array(
  1880. 'type' => 'danger',
  1881. 'log' => array(__FUNCTION__, $username, '*'),
  1882. 'msg' => array('webauthn_role_failed')
  1883. );
  1884. return false;
  1885. }
  1886. }
  1887. $_SESSION["mailcow_cc_username"] = $process_webauthn['username'];
  1888. $_SESSION['tfa_id'] = $process_webauthn['id'];
  1889. $_SESSION['authReq'] = null;
  1890. unset($_SESSION["challenge"]);
  1891. $_SESSION['return'][] = array(
  1892. 'type' => 'success',
  1893. 'log' => array("webauthn_login"),
  1894. 'msg' => array('logged_in_as', $process_webauthn['username'])
  1895. );
  1896. return true;
  1897. break;
  1898. default:
  1899. $_SESSION['return'][] = array(
  1900. 'type' => 'danger',
  1901. 'log' => array(__FUNCTION__, $username, '*'),
  1902. 'msg' => 'unknown_tfa_method'
  1903. );
  1904. return false;
  1905. break;
  1906. }
  1907. return false;
  1908. } else {
  1909. // delete old keys that used u2f
  1910. $stmt = $pdo->prepare("SELECT * FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username");
  1911. $stmt->execute(array(':username' => $username));
  1912. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1913. if (count($rows) == 0) return false;
  1914. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username");
  1915. $stmt->execute(array(':username' => $username));
  1916. return true;
  1917. }
  1918. }
  1919. function admin_api($access, $action, $data = null) {
  1920. global $pdo;
  1921. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1922. $_SESSION['return'][] = array(
  1923. 'type' => 'danger',
  1924. 'log' => array(__FUNCTION__),
  1925. 'msg' => 'access_denied'
  1926. );
  1927. return false;
  1928. }
  1929. if ($access !== "ro" && $access !== "rw") {
  1930. $_SESSION['return'][] = array(
  1931. 'type' => 'danger',
  1932. 'log' => array(__FUNCTION__),
  1933. 'msg' => 'invalid access type'
  1934. );
  1935. return false;
  1936. }
  1937. if ($action == "edit") {
  1938. $active = (!empty($data['active'])) ? 1 : 0;
  1939. $skip_ip_check = (isset($data['skip_ip_check'])) ? 1 : 0;
  1940. $allow_from = array();
  1941. if (isset($data['allow_from'])) {
  1942. $allow_from = array_map('trim', preg_split( "/( |,|;|\n)/", $data['allow_from']));
  1943. }
  1944. foreach ($allow_from as $key => $val) {
  1945. if (empty($val)) {
  1946. unset($allow_from[$key]);
  1947. continue;
  1948. }
  1949. if (valid_network($val) !== true) {
  1950. $_SESSION['return'][] = array(
  1951. 'type' => 'warning',
  1952. 'log' => array(__FUNCTION__, $data),
  1953. 'msg' => array('ip_invalid', htmlspecialchars($allow_from[$key]))
  1954. );
  1955. unset($allow_from[$key]);
  1956. continue;
  1957. }
  1958. }
  1959. $allow_from = implode(',', array_unique(array_filter($allow_from)));
  1960. if (empty($allow_from) && $skip_ip_check == 0) {
  1961. $_SESSION['return'][] = array(
  1962. 'type' => 'danger',
  1963. 'log' => array(__FUNCTION__, $data),
  1964. 'msg' => 'ip_list_empty'
  1965. );
  1966. return false;
  1967. }
  1968. $api_key = implode('-', array(
  1969. strtoupper(bin2hex(random_bytes(3))),
  1970. strtoupper(bin2hex(random_bytes(3))),
  1971. strtoupper(bin2hex(random_bytes(3))),
  1972. strtoupper(bin2hex(random_bytes(3))),
  1973. strtoupper(bin2hex(random_bytes(3)))
  1974. ));
  1975. $stmt = $pdo->query("SELECT `api_key` FROM `api` WHERE `access` = '" . $access . "'");
  1976. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  1977. if (empty($num_results)) {
  1978. $stmt = $pdo->prepare("INSERT INTO `api` (`api_key`, `skip_ip_check`, `active`, `allow_from`, `access`)
  1979. VALUES (:api_key, :skip_ip_check, :active, :allow_from, :access);");
  1980. $stmt->execute(array(
  1981. ':api_key' => $api_key,
  1982. ':skip_ip_check' => $skip_ip_check,
  1983. ':active' => $active,
  1984. ':allow_from' => $allow_from,
  1985. ':access' => $access
  1986. ));
  1987. }
  1988. else {
  1989. if ($skip_ip_check == 0) {
  1990. $stmt = $pdo->prepare("UPDATE `api` SET `skip_ip_check` = :skip_ip_check,
  1991. `active` = :active,
  1992. `allow_from` = :allow_from
  1993. WHERE `access` = :access;");
  1994. $stmt->execute(array(
  1995. ':active' => $active,
  1996. ':skip_ip_check' => $skip_ip_check,
  1997. ':allow_from' => $allow_from,
  1998. ':access' => $access
  1999. ));
  2000. }
  2001. else {
  2002. $stmt = $pdo->prepare("UPDATE `api` SET `skip_ip_check` = :skip_ip_check,
  2003. `active` = :active
  2004. WHERE `access` = :access;");
  2005. $stmt->execute(array(
  2006. ':active' => $active,
  2007. ':skip_ip_check' => $skip_ip_check,
  2008. ':access' => $access
  2009. ));
  2010. }
  2011. }
  2012. }
  2013. elseif ($action == "regen_key") {
  2014. $api_key = implode('-', array(
  2015. strtoupper(bin2hex(random_bytes(3))),
  2016. strtoupper(bin2hex(random_bytes(3))),
  2017. strtoupper(bin2hex(random_bytes(3))),
  2018. strtoupper(bin2hex(random_bytes(3))),
  2019. strtoupper(bin2hex(random_bytes(3)))
  2020. ));
  2021. $stmt = $pdo->prepare("UPDATE `api` SET `api_key` = :api_key WHERE `access` = :access");
  2022. $stmt->execute(array(
  2023. ':api_key' => $api_key,
  2024. ':access' => $access
  2025. ));
  2026. }
  2027. elseif ($action == "get") {
  2028. $stmt = $pdo->query("SELECT * FROM `api` WHERE `access` = '" . $access . "'");
  2029. $apidata = $stmt->fetch(PDO::FETCH_ASSOC);
  2030. if ($apidata !== false) {
  2031. $apidata['allow_from'] = str_replace(',', PHP_EOL, $apidata['allow_from']);
  2032. }
  2033. return $apidata;
  2034. }
  2035. $_SESSION['return'][] = array(
  2036. 'type' => 'success',
  2037. 'log' => array(__FUNCTION__, $data),
  2038. 'msg' => 'admin_api_modified'
  2039. );
  2040. }
  2041. function license($action, $data = null) {
  2042. global $pdo;
  2043. global $redis;
  2044. global $lang;
  2045. if ($_SESSION['mailcow_cc_role'] != "admin") {
  2046. $_SESSION['return'][] = array(
  2047. 'type' => 'danger',
  2048. 'log' => array(__FUNCTION__),
  2049. 'msg' => 'access_denied'
  2050. );
  2051. return false;
  2052. }
  2053. switch ($action) {
  2054. case "verify":
  2055. // Keep result until revalidate button is pressed or session expired
  2056. $stmt = $pdo->query("SELECT `version` FROM `versions` WHERE `application` = 'GUID'");
  2057. $versions = $stmt->fetch(PDO::FETCH_ASSOC);
  2058. $post = array('guid' => $versions['version']);
  2059. $curl = curl_init('https://verify.mailcow.email');
  2060. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2061. curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
  2062. curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
  2063. $response = curl_exec($curl);
  2064. curl_close($curl);
  2065. $json_return = json_decode($response, true);
  2066. if ($response && $json_return) {
  2067. if ($json_return['response'] === "ok") {
  2068. $_SESSION['gal']['valid'] = "true";
  2069. $_SESSION['gal']['c'] = $json_return['c'];
  2070. $_SESSION['gal']['s'] = $json_return['s'];
  2071. if ($json_return['m'] == 'NoMoore') {
  2072. $_SESSION['gal']['m'] = '🐄';
  2073. }
  2074. else {
  2075. $_SESSION['gal']['m'] = str_repeat('🐄', substr_count($json_return['m'], 'o'));
  2076. }
  2077. }
  2078. elseif ($json_return['response'] === "invalid") {
  2079. $_SESSION['gal']['valid'] = "false";
  2080. $_SESSION['gal']['c'] = $lang['mailbox']['no'];
  2081. $_SESSION['gal']['s'] = $lang['mailbox']['no'];
  2082. $_SESSION['gal']['m'] = $lang['mailbox']['no'];
  2083. }
  2084. }
  2085. else {
  2086. $_SESSION['gal']['valid'] = "false";
  2087. $_SESSION['gal']['c'] = $lang['danger']['temp_error'];
  2088. $_SESSION['gal']['s'] = $lang['danger']['temp_error'];
  2089. $_SESSION['gal']['m'] = $lang['danger']['temp_error'];
  2090. }
  2091. try {
  2092. // json_encode needs "true"/"false" instead of true/false, to not encode it to 0 or 1
  2093. $redis->Set('LICENSE_STATUS_CACHE', json_encode($_SESSION['gal']));
  2094. }
  2095. catch (RedisException $e) {
  2096. $_SESSION['return'][] = array(
  2097. 'type' => 'danger',
  2098. 'log' => array(__FUNCTION__, $_action, $_data_log),
  2099. 'msg' => array('redis_error', $e)
  2100. );
  2101. return false;
  2102. }
  2103. return $_SESSION['gal']['valid'];
  2104. break;
  2105. case "guid":
  2106. $stmt = $pdo->query("SELECT `version` FROM `versions` WHERE `application` = 'GUID'");
  2107. $versions = $stmt->fetch(PDO::FETCH_ASSOC);
  2108. return $versions['version'];
  2109. break;
  2110. }
  2111. }
  2112. function rspamd_ui($action, $data = null) {
  2113. if ($_SESSION['mailcow_cc_role'] != "admin") {
  2114. $_SESSION['return'][] = array(
  2115. 'type' => 'danger',
  2116. 'log' => array(__FUNCTION__),
  2117. 'msg' => 'access_denied'
  2118. );
  2119. return false;
  2120. }
  2121. switch ($action) {
  2122. case "edit":
  2123. $rspamd_ui_pass = $data['rspamd_ui_pass'];
  2124. $rspamd_ui_pass2 = $data['rspamd_ui_pass2'];
  2125. if (empty($rspamd_ui_pass) || empty($rspamd_ui_pass2)) {
  2126. $_SESSION['return'][] = array(
  2127. 'type' => 'danger',
  2128. 'log' => array(__FUNCTION__, '*', '*'),
  2129. 'msg' => 'password_empty'
  2130. );
  2131. return false;
  2132. }
  2133. if ($rspamd_ui_pass != $rspamd_ui_pass2) {
  2134. $_SESSION['return'][] = array(
  2135. 'type' => 'danger',
  2136. 'log' => array(__FUNCTION__, '*', '*'),
  2137. 'msg' => 'password_mismatch'
  2138. );
  2139. return false;
  2140. }
  2141. if (strlen($rspamd_ui_pass) < 6) {
  2142. $_SESSION['return'][] = array(
  2143. 'type' => 'danger',
  2144. 'log' => array(__FUNCTION__, '*', '*'),
  2145. 'msg' => 'rspamd_ui_pw_length'
  2146. );
  2147. return false;
  2148. }
  2149. $docker_return = docker('post', 'rspamd-mailcow', 'exec', array('cmd' => 'rspamd', 'task' => 'worker_password', 'raw' => $rspamd_ui_pass), array('Content-Type: application/json'));
  2150. if ($docker_return_array = json_decode($docker_return, true)) {
  2151. if ($docker_return_array['type'] == 'success') {
  2152. $_SESSION['return'][] = array(
  2153. 'type' => 'success',
  2154. 'log' => array(__FUNCTION__, '*', '*'),
  2155. 'msg' => 'rspamd_ui_pw_set'
  2156. );
  2157. return true;
  2158. }
  2159. else {
  2160. $_SESSION['return'][] = array(
  2161. 'type' => $docker_return_array['type'],
  2162. 'log' => array(__FUNCTION__, '*', '*'),
  2163. 'msg' => $docker_return_array['msg']
  2164. );
  2165. return false;
  2166. }
  2167. }
  2168. else {
  2169. $_SESSION['return'][] = array(
  2170. 'type' => 'danger',
  2171. 'log' => array(__FUNCTION__, '*', '*'),
  2172. 'msg' => 'unknown'
  2173. );
  2174. return false;
  2175. }
  2176. break;
  2177. }
  2178. }
  2179. function cors($action, $data = null) {
  2180. global $redis;
  2181. switch ($action) {
  2182. case "edit":
  2183. if ($_SESSION['mailcow_cc_role'] != "admin") {
  2184. $_SESSION['return'][] = array(
  2185. 'type' => 'danger',
  2186. 'log' => array(__FUNCTION__, $action, $data),
  2187. 'msg' => 'access_denied'
  2188. );
  2189. return false;
  2190. }
  2191. $allowed_origins = isset($data['allowed_origins']) ? $data['allowed_origins'] : array($_SERVER['SERVER_NAME']);
  2192. $allowed_origins = !is_array($allowed_origins) ? array_filter(array_map('trim', explode("\n", $allowed_origins))) : $allowed_origins;
  2193. foreach ($allowed_origins as $origin) {
  2194. if (!filter_var($origin, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) && $origin != '*') {
  2195. $_SESSION['return'][] = array(
  2196. 'type' => 'danger',
  2197. 'log' => array(__FUNCTION__, $action, $data),
  2198. 'msg' => 'cors_invalid_origin'
  2199. );
  2200. return false;
  2201. }
  2202. }
  2203. $allowed_methods = isset($data['allowed_methods']) ? $data['allowed_methods'] : array('GET', 'POST', 'PUT', 'DELETE');
  2204. $allowed_methods = !is_array($allowed_methods) ? array_map('trim', preg_split( "/( |,|;|\n)/", $allowed_methods)) : $allowed_methods;
  2205. $available_methods = array('GET', 'POST', 'PUT', 'DELETE');
  2206. foreach ($allowed_methods as $method) {
  2207. if (!in_array($method, $available_methods)) {
  2208. $_SESSION['return'][] = array(
  2209. 'type' => 'danger',
  2210. 'log' => array(__FUNCTION__, $action, $data),
  2211. 'msg' => 'cors_invalid_method'
  2212. );
  2213. return false;
  2214. }
  2215. }
  2216. try {
  2217. $redis->hMSet('CORS_SETTINGS', array(
  2218. 'allowed_origins' => implode(', ', $allowed_origins),
  2219. 'allowed_methods' => implode(', ', $allowed_methods)
  2220. ));
  2221. } catch (RedisException $e) {
  2222. $_SESSION['return'][] = array(
  2223. 'type' => 'danger',
  2224. 'log' => array(__FUNCTION__, $action, $data),
  2225. 'msg' => array('redis_error', $e)
  2226. );
  2227. return false;
  2228. }
  2229. $_SESSION['return'][] = array(
  2230. 'type' => 'success',
  2231. 'log' => array(__FUNCTION__, $action, $data),
  2232. 'msg' => 'cors_headers_edited'
  2233. );
  2234. return true;
  2235. break;
  2236. case "get":
  2237. try {
  2238. $cors_settings = $redis->hMGet('CORS_SETTINGS', array('allowed_origins', 'allowed_methods'));
  2239. } catch (RedisException $e) {
  2240. $_SESSION['return'][] = array(
  2241. 'type' => 'danger',
  2242. 'log' => array(__FUNCTION__, $action, $data),
  2243. 'msg' => array('redis_error', $e)
  2244. );
  2245. }
  2246. $cors_settings = !$cors_settings ? array('allowed_origins' => $_SERVER['SERVER_NAME'], 'allowed_methods' => 'GET, POST, PUT, DELETE') : $cors_settings;
  2247. $cors_settings['allowed_origins'] = empty($cors_settings['allowed_origins']) ? $_SERVER['SERVER_NAME'] : $cors_settings['allowed_origins'];
  2248. $cors_settings['allowed_methods'] = empty($cors_settings['allowed_methods']) ? 'GET, POST, PUT, DELETE, OPTION' : $cors_settings['allowed_methods'];
  2249. return $cors_settings;
  2250. break;
  2251. case "set_headers":
  2252. $cors_settings = cors('get');
  2253. // check if requested origin is in allowed origins
  2254. $allowed_origins = explode(', ', $cors_settings['allowed_origins']);
  2255. $cors_settings['allowed_origins'] = $allowed_origins[0];
  2256. if (in_array('*', $allowed_origins)){
  2257. $cors_settings['allowed_origins'] = '*';
  2258. } else if (array_key_exists('HTTP_ORIGIN', $_SERVER) && in_array($_SERVER['HTTP_ORIGIN'], $allowed_origins)) {
  2259. $cors_settings['allowed_origins'] = $_SERVER['HTTP_ORIGIN'];
  2260. }
  2261. // always allow OPTIONS for preflight request
  2262. $cors_settings["allowed_methods"] = empty($cors_settings["allowed_methods"]) ? 'OPTIONS' : $cors_settings["allowed_methods"] . ', ' . 'OPTIONS';
  2263. header('Access-Control-Allow-Origin: ' . $cors_settings['allowed_origins']);
  2264. header('Access-Control-Allow-Methods: '. $cors_settings['allowed_methods']);
  2265. header('Access-Control-Allow-Headers: Accept, Content-Type, X-Api-Key, Origin');
  2266. // Access-Control settings requested, this is just a preflight request
  2267. if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS' &&
  2268. isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']) &&
  2269. isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
  2270. $allowed_methods = explode(', ', $cors_settings["allowed_methods"]);
  2271. if (in_array($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'], $allowed_methods, true))
  2272. // method allowed send 200 OK
  2273. http_response_code(200);
  2274. else
  2275. // method not allowed send 405 METHOD NOT ALLOWED
  2276. http_response_code(405);
  2277. exit;
  2278. }
  2279. break;
  2280. }
  2281. }
  2282. function getBaseURL($protocol = null) {
  2283. // Get current server name
  2284. $host = strtolower($_SERVER['SERVER_NAME']);
  2285. // craft allowed server name list
  2286. $mailcow_hostname = strtolower(getenv("MAILCOW_HOSTNAME"));
  2287. $additional_server_names = strtolower(getenv("ADDITIONAL_SERVER_NAMES")) ?: "";
  2288. $additional_server_names = preg_replace('/\s+/', '', $additional_server_names);
  2289. $allowed_server_names = $additional_server_names !== "" ? explode(',', $additional_server_names) : array();
  2290. array_push($allowed_server_names, $mailcow_hostname);
  2291. // Fallback to MAILCOW HOSTNAME if current server name is not in allowed list
  2292. if (!in_array($host, $allowed_server_names)) {
  2293. $host = $mailcow_hostname;
  2294. }
  2295. if (!isset($protocol)) {
  2296. $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
  2297. }
  2298. $base_url = $protocol . '://' . $host;
  2299. return $base_url;
  2300. }
  2301. function uuid4() {
  2302. $data = openssl_random_pseudo_bytes(16);
  2303. $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
  2304. $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
  2305. return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
  2306. }
  2307. function identity_provider($_action = null, $_data = null, $_extra = null) {
  2308. global $pdo;
  2309. global $iam_provider;
  2310. global $iam_settings;
  2311. $data_log = $_data;
  2312. if (isset($data_log['client_secret'])) $data_log['client_secret'] = '*';
  2313. if (isset($data_log['access_token'])) $data_log['access_token'] = '*';
  2314. switch ($_action) {
  2315. case 'get':
  2316. $settings = array();
  2317. $stmt = $pdo->prepare("SELECT * FROM `identity_provider`;");
  2318. $stmt->execute();
  2319. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2320. foreach($rows as $row){
  2321. switch ($row["key"]) {
  2322. case "redirect_url_extra":
  2323. case "mappers":
  2324. case "templates":
  2325. $settings[$row["key"]] = json_decode($row["value"]);
  2326. break;
  2327. case "use_ssl":
  2328. case "use_tls":
  2329. case "login_provisioning":
  2330. case "ignore_ssl_errors":
  2331. $settings[$row["key"]] = boolval($row["value"]);
  2332. break;
  2333. default:
  2334. $settings[$row["key"]] = $row["value"];
  2335. break;
  2336. }
  2337. }
  2338. // set login_provisioning if not exists
  2339. if (!array_key_exists('login_provisioning', $settings)) {
  2340. $settings['login_provisioning'] = 1;
  2341. }
  2342. // return default client_scopes for generic-oidc if none is set
  2343. if ($settings["authsource"] == "generic-oidc" && empty($settings["client_scopes"])){
  2344. $settings["client_scopes"] = "openid profile email mailcow_template";
  2345. }
  2346. if ($_extra['hide_sensitive']){
  2347. $settings['client_secret'] = '';
  2348. $settings['access_token'] = '';
  2349. }
  2350. // return default ldap options
  2351. if ($settings["authsource"] == "ldap"){
  2352. $settings['use_ssl'] = !isset($settings['use_ssl']) ? false : $settings['use_ssl'];
  2353. $settings['use_tls'] = !isset($settings['use_tls']) ? false : $settings['use_tls'];
  2354. $settings['ignore_ssl_errors'] = !isset($settings['ignore_ssl_errors']) ? false : $settings['ignore_ssl_errors'];
  2355. }
  2356. return $settings;
  2357. break;
  2358. case 'edit':
  2359. if ($_SESSION['mailcow_cc_role'] != "admin") {
  2360. $_SESSION['return'][] = array(
  2361. 'type' => 'danger',
  2362. 'log' => array(__FUNCTION__, $_action, $_data),
  2363. 'msg' => 'access_denied'
  2364. );
  2365. return false;
  2366. }
  2367. if (!isset($_data['authsource'])){
  2368. $_SESSION['return'][] = array(
  2369. 'type' => 'danger',
  2370. 'log' => array(__FUNCTION__, $_action, $data_log),
  2371. 'msg' => array('required_data_missing', '')
  2372. );
  2373. return false;
  2374. }
  2375. $available_authsources = array(
  2376. "keycloak",
  2377. "generic-oidc",
  2378. "ldap"
  2379. );
  2380. $_data['authsource'] = strtolower($_data['authsource']);
  2381. if (!in_array($_data['authsource'], $available_authsources)){
  2382. $_SESSION['return'][] = array(
  2383. 'type' => 'danger',
  2384. 'log' => array(__FUNCTION__, $_action, $data_log),
  2385. 'msg' => array('invalid_authsource', $setting)
  2386. );
  2387. return false;
  2388. }
  2389. $stmt = $pdo->prepare("SELECT * FROM `mailbox`
  2390. WHERE `authsource` != 'mailcow'
  2391. AND `authsource` IS NOT NULL
  2392. AND `authsource` != :authsource");
  2393. $stmt->execute(array(':authsource' => $_data['authsource']));
  2394. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2395. if ($rows) {
  2396. $_SESSION['return'][] = array(
  2397. 'type' => 'danger',
  2398. 'log' => array(__FUNCTION__, $_action, $data_log),
  2399. 'msg' => array('authsource_in_use', $setting)
  2400. );
  2401. return false;
  2402. }
  2403. $_data['ignore_ssl_error'] = isset($_data['ignore_ssl_error']) ? boolval($_data['ignore_ssl_error']) : false;
  2404. $_data['login_provisioning'] = isset($_data['login_provisioning']) ? boolval($_data['login_provisioning']) : false;
  2405. switch ($_data['authsource']) {
  2406. case "keycloak":
  2407. $_data['server_url'] = (!empty($_data['server_url'])) ? rtrim($_data['server_url'], '/') : null;
  2408. $_data['mailpassword_flow'] = isset($_data['mailpassword_flow']) ? intval($_data['mailpassword_flow']) : 0;
  2409. $_data['periodic_sync'] = isset($_data['periodic_sync']) ? intval($_data['periodic_sync']) : 0;
  2410. $_data['import_users'] = isset($_data['import_users']) ? intval($_data['import_users']) : 0;
  2411. $_data['sync_interval'] = (!empty($_data['sync_interval'])) ? intval($_data['sync_interval']) : 15;
  2412. $_data['sync_interval'] = $_data['sync_interval'] < 1 ? 1 : $_data['sync_interval'];
  2413. $required_settings = array('authsource', 'server_url', 'realm', 'client_id', 'client_secret', 'redirect_url', 'version', 'mailpassword_flow', 'periodic_sync', 'import_users', 'sync_interval', 'ignore_ssl_error', 'login_provisioning');
  2414. break;
  2415. case "generic-oidc":
  2416. $_data['authorize_url'] = (!empty($_data['authorize_url'])) ? $_data['authorize_url'] : null;
  2417. $_data['token_url'] = (!empty($_data['token_url'])) ? $_data['token_url'] : null;
  2418. $_data['userinfo_url'] = (!empty($_data['userinfo_url'])) ? $_data['userinfo_url'] : null;
  2419. $_data['client_scopes'] = (!empty($_data['client_scopes'])) ? $_data['client_scopes'] : "openid profile email mailcow_template";
  2420. $required_settings = array('authsource', 'authorize_url', 'token_url', 'client_id', 'client_secret', 'redirect_url', 'userinfo_url', 'client_scopes', 'ignore_ssl_error', 'login_provisioning');
  2421. break;
  2422. case "ldap":
  2423. $_data['host'] = (!empty($_data['host'])) ? str_replace(" ", "", $_data['host']) : "";
  2424. $_data['port'] = (!empty($_data['port'])) ? intval($_data['port']) : 389;
  2425. $_data['username_field'] = (!empty($_data['username_field'])) ? strtolower($_data['username_field']) : "mail";
  2426. $_data['attribute_field'] = (!empty($_data['attribute_field'])) ? strtolower($_data['attribute_field']) : "";
  2427. $_data['filter'] = (!empty($_data['filter'])) ? $_data['filter'] : "";
  2428. $_data['periodic_sync'] = isset($_data['periodic_sync']) ? intval($_data['periodic_sync']) : 0;
  2429. $_data['import_users'] = isset($_data['import_users']) ? intval($_data['import_users']) : 0;
  2430. $_data['use_ssl'] = isset($_data['use_ssl']) ? boolval($_data['use_ssl']) : false;
  2431. $_data['use_tls'] = isset($_data['use_tls']) && !$_data['use_ssl'] ? boolval($_data['use_tls']) : false;
  2432. $_data['sync_interval'] = (!empty($_data['sync_interval'])) ? intval($_data['sync_interval']) : 15;
  2433. $_data['sync_interval'] = $_data['sync_interval'] < 1 ? 1 : $_data['sync_interval'];
  2434. $required_settings = array('authsource', 'host', 'port', 'basedn', 'username_field', 'filter', 'attribute_field', 'binddn', 'bindpass', 'periodic_sync', 'import_users', 'sync_interval', 'use_ssl', 'use_tls', 'ignore_ssl_error', 'login_provisioning');
  2435. break;
  2436. }
  2437. $pdo->beginTransaction();
  2438. $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES (:key, :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
  2439. // add connection settings
  2440. foreach($required_settings as $setting){
  2441. if (!isset($_data[$setting])){
  2442. $_SESSION['return'][] = array(
  2443. 'type' => 'danger',
  2444. 'log' => array(__FUNCTION__, $_action, $data_log),
  2445. 'msg' => array('required_data_missing', $setting)
  2446. );
  2447. $pdo->rollback();
  2448. return false;
  2449. }
  2450. $stmt->bindParam(':key', $setting);
  2451. $stmt->bindParam(':value', $_data[$setting]);
  2452. $stmt->execute();
  2453. }
  2454. $pdo->commit();
  2455. // add redirect_url_extra
  2456. if (isset($_data['redirect_url_extra'])){
  2457. $_data['redirect_url_extra'] = (!is_array($_data['redirect_url_extra'])) ? array($_data['redirect_url_extra']) : $_data['redirect_url_extra'];
  2458. $redirect_url_extra = array_filter($_data['redirect_url_extra']);
  2459. $redirect_url_extra = json_encode($redirect_url_extra);
  2460. $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES ('redirect_url_extra', :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
  2461. $stmt->bindParam(':value', $redirect_url_extra);
  2462. $stmt->execute();
  2463. }
  2464. // add default template
  2465. if (isset($_data['default_template'])) {
  2466. $_data['default_template'] = (empty($_data['default_template'])) ? "" : $_data['default_template'];
  2467. $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES ('default_template', :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
  2468. $stmt->bindParam(':value', $_data['default_template']);
  2469. $stmt->execute();
  2470. }
  2471. // add mappers
  2472. if (isset($_data['mappers']) && isset($_data['templates'])){
  2473. $_data['mappers'] = (!is_array($_data['mappers'])) ? array($_data['mappers']) : $_data['mappers'];
  2474. $_data['templates'] = (!is_array($_data['templates'])) ? array($_data['templates']) : $_data['templates'];
  2475. $mappers = array_filter($_data['mappers']);
  2476. $templates = array_filter($_data['templates']);
  2477. if (count($mappers) == count($templates)){
  2478. $mappers = json_encode($mappers);
  2479. $templates = json_encode($templates);
  2480. $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES ('mappers', :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
  2481. $stmt->bindParam(':value', $mappers);
  2482. $stmt->execute();
  2483. $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES ('templates', :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
  2484. $stmt->bindParam(':value', $templates);
  2485. $stmt->execute();
  2486. }
  2487. }
  2488. // delete old access_token
  2489. $stmt = $pdo->query("INSERT INTO identity_provider (`key`, `value`) VALUES ('access_token', '') ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
  2490. $_SESSION['return'][] = array(
  2491. 'type' => 'success',
  2492. 'log' => array(__FUNCTION__, $_action, $data_log),
  2493. 'msg' => array('object_modified', '')
  2494. );
  2495. return true;
  2496. break;
  2497. case 'test':
  2498. if ($_SESSION['mailcow_cc_role'] != "admin") {
  2499. $_SESSION['return'][] = array(
  2500. 'type' => 'danger',
  2501. 'log' => array(__FUNCTION__, $_action, $_data),
  2502. 'msg' => 'access_denied'
  2503. );
  2504. return false;
  2505. }
  2506. switch ($_data['authsource']) {
  2507. case 'keycloak':
  2508. $url = "{$_data['server_url']}/realms/{$_data['realm']}/protocol/openid-connect/token";
  2509. $req = http_build_query(array(
  2510. 'grant_type' => 'client_credentials',
  2511. 'client_id' => $_data['client_id'],
  2512. 'client_secret' => $_data['client_secret']
  2513. ));
  2514. $curl = curl_init();
  2515. curl_setopt($curl, CURLOPT_URL, $url);
  2516. curl_setopt($curl, CURLOPT_TIMEOUT, 7);
  2517. curl_setopt($curl, CURLOPT_POST, 1);
  2518. curl_setopt($curl, CURLOPT_POSTFIELDS, $req);
  2519. curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
  2520. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2521. if ($_data['ignore_ssl_error'] == "1"){
  2522. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  2523. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
  2524. }
  2525. $res = curl_exec($curl);
  2526. $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  2527. curl_close ($curl);
  2528. if ($code != 200) {
  2529. return false;
  2530. }
  2531. break;
  2532. case 'generic-oidc':
  2533. $url = $_data['token_url'];
  2534. $curl = curl_init();
  2535. curl_setopt($curl, CURLOPT_URL, $url);
  2536. curl_setopt($curl, CURLOPT_TIMEOUT, 7);
  2537. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2538. curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "OPTIONS");
  2539. if ($_data['ignore_ssl_error'] == "1"){
  2540. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  2541. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
  2542. }
  2543. $res = curl_exec($curl);
  2544. $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  2545. curl_close ($curl);
  2546. if ($code != 200) {
  2547. return false;
  2548. }
  2549. break;
  2550. case 'ldap':
  2551. if (!$_data['host'] || !$_data['port'] || !$_data['basedn'] ||
  2552. !$_data['binddn'] || !$_data['bindpass']){
  2553. return false;
  2554. }
  2555. $_data['use_ssl'] = isset($_data['use_ssl']) ? boolval($_data['use_ssl']) : false;
  2556. $_data['use_tls'] = isset($_data['use_tls']) && !$_data['use_ssl'] ? boolval($_data['use_tls']) : false;
  2557. $_data['ignore_ssl_error'] = isset($_data['ignore_ssl_error']) ? boolval($_data['ignore_ssl_error']) : false;
  2558. $options = array();
  2559. if ($_data['ignore_ssl_error']) {
  2560. $options[LDAP_OPT_X_TLS_REQUIRE_CERT] = LDAP_OPT_X_TLS_NEVER;
  2561. }
  2562. $provider = new \LdapRecord\Connection([
  2563. 'hosts' => explode(",", $_data['host']),
  2564. 'port' => $_data['port'],
  2565. 'base_dn' => $_data['basedn'],
  2566. 'username' => $_data['binddn'],
  2567. 'password' => $_data['bindpass'],
  2568. 'use_ssl' => $_data['use_ssl'],
  2569. 'use_tls' => $_data['use_tls'],
  2570. 'options' => $options
  2571. ]);
  2572. try {
  2573. $provider->connect();
  2574. } catch (Throwable $e) {
  2575. return false;
  2576. }
  2577. break;
  2578. }
  2579. return true;
  2580. break;
  2581. case "delete":
  2582. if ($_SESSION['mailcow_cc_role'] != "admin") {
  2583. $_SESSION['return'][] = array(
  2584. 'type' => 'danger',
  2585. 'log' => array(__FUNCTION__, $_action, $_data),
  2586. 'msg' => 'access_denied'
  2587. );
  2588. return false;
  2589. }
  2590. $stmt = $pdo->query("SELECT * FROM `mailbox`
  2591. WHERE `authsource` != 'mailcow'
  2592. AND `authsource` IS NOT NULL");
  2593. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2594. if ($rows) {
  2595. $_SESSION['return'][] = array(
  2596. 'type' => 'danger',
  2597. 'log' => array(__FUNCTION__, $_action, $data_log),
  2598. 'msg' => array('authsource_in_use', $setting)
  2599. );
  2600. return false;
  2601. }
  2602. $stmt = $pdo->query("DELETE FROM identity_provider;");
  2603. $_SESSION['return'][] = array(
  2604. 'type' => 'success',
  2605. 'log' => array(__FUNCTION__, $_action, $data_log),
  2606. 'msg' => array('item_deleted', '')
  2607. );
  2608. return true;
  2609. break;
  2610. case "init":
  2611. $settings = identity_provider('get');
  2612. $provider = null;
  2613. switch ($settings['authsource']) {
  2614. case "keycloak":
  2615. if ($settings['server_url'] && $settings['realm'] && $settings['client_id'] &&
  2616. $settings['client_secret'] && $settings['redirect_url'] && $settings['version']){
  2617. $guzzyClient = new GuzzleHttp\Client([
  2618. 'defaults' => [
  2619. \GuzzleHttp\RequestOptions::CONNECT_TIMEOUT => 5,
  2620. \GuzzleHttp\RequestOptions::ALLOW_REDIRECTS => true],
  2621. \GuzzleHttp\RequestOptions::VERIFY => !$settings['ignore_ssl_error'],
  2622. ]
  2623. );
  2624. $provider = new Stevenmaguire\OAuth2\Client\Provider\Keycloak([
  2625. 'authServerUrl' => $settings['server_url'],
  2626. 'realm' => $settings['realm'],
  2627. 'clientId' => $settings['client_id'],
  2628. 'clientSecret' => $settings['client_secret'],
  2629. 'redirectUri' => $settings['redirect_url'],
  2630. 'version' => $settings['version'],
  2631. // 'encryptionAlgorithm' => 'RS256', // optional
  2632. // 'encryptionKeyPath' => '../key.pem' // optional
  2633. // 'encryptionKey' => 'contents_of_key_or_certificate' // optional
  2634. ]);
  2635. $provider->setHttpClient($guzzyClient);
  2636. }
  2637. break;
  2638. case "generic-oidc":
  2639. if ($settings['client_id'] && $settings['client_secret'] && $settings['redirect_url'] &&
  2640. $settings['authorize_url'] && $settings['token_url'] && $settings['userinfo_url']){
  2641. $guzzyClient = new GuzzleHttp\Client([
  2642. 'defaults' => [
  2643. \GuzzleHttp\RequestOptions::CONNECT_TIMEOUT => 5,
  2644. \GuzzleHttp\RequestOptions::ALLOW_REDIRECTS => true],
  2645. \GuzzleHttp\RequestOptions::VERIFY => !$settings['ignore_ssl_error'],
  2646. ]
  2647. );
  2648. $provider = new \League\OAuth2\Client\Provider\GenericProvider([
  2649. 'clientId' => $settings['client_id'],
  2650. 'clientSecret' => $settings['client_secret'],
  2651. 'redirectUri' => $settings['redirect_url'],
  2652. 'urlAuthorize' => $settings['authorize_url'],
  2653. 'urlAccessToken' => $settings['token_url'],
  2654. 'urlResourceOwnerDetails' => $settings['userinfo_url'],
  2655. 'scopes' => $settings['client_scopes']
  2656. ]);
  2657. $provider->setHttpClient($guzzyClient);
  2658. }
  2659. break;
  2660. case "ldap":
  2661. if ($settings['host'] && $settings['port'] && $settings['basedn'] &&
  2662. $settings['binddn'] && $settings['bindpass']){
  2663. $options = array();
  2664. if ($settings['ignore_ssl_error']) {
  2665. $options[LDAP_OPT_X_TLS_REQUIRE_CERT] = LDAP_OPT_X_TLS_NEVER;
  2666. }
  2667. $provider = new \LdapRecord\Connection([
  2668. 'hosts' => explode(",", $settings['host']),
  2669. 'port' => $settings['port'],
  2670. 'base_dn' => $settings['basedn'],
  2671. 'username' => $settings['binddn'],
  2672. 'password' => $settings['bindpass'],
  2673. 'use_ssl' => $settings['use_ssl'],
  2674. 'use_tls' => $settings['use_tls'],
  2675. 'options' => $options
  2676. ]);
  2677. try {
  2678. $provider->connect();
  2679. } catch (Throwable $e) {
  2680. $provider = null;
  2681. }
  2682. }
  2683. break;
  2684. }
  2685. return $provider;
  2686. break;
  2687. case "verify-sso":
  2688. if ($iam_settings['authsource'] != 'keycloak' && $iam_settings['authsource'] != 'generic-oidc'){
  2689. $_SESSION['return'][] = array(
  2690. 'type' => 'danger',
  2691. 'log' => array(__FUNCTION__, "no OIDC provider configured"),
  2692. 'msg' => 'login_failed'
  2693. );
  2694. return false;
  2695. }
  2696. try {
  2697. $token = $iam_provider->getAccessToken('authorization_code', ['code' => $_GET['code']]);
  2698. $plain_token = $token->getToken();
  2699. $plain_refreshtoken = $token->getRefreshToken();
  2700. $info = $iam_provider->getResourceOwner($token)->toArray();
  2701. } catch (Throwable $e) {
  2702. $_SESSION['return'][] = array(
  2703. 'type' => 'danger',
  2704. 'log' => array(__FUNCTION__, $e->getMessage()),
  2705. 'msg' => 'login_failed'
  2706. );
  2707. return false;
  2708. }
  2709. // check if email address is given
  2710. if (empty($info['email'])) {
  2711. $_SESSION['return'][] = array(
  2712. 'type' => 'danger',
  2713. 'log' => array(__FUNCTION__, 'No email address found for user'),
  2714. 'msg' => 'login_failed'
  2715. );
  2716. return false;
  2717. }
  2718. // get mapped template
  2719. $user_template = $info['mailcow_template'];
  2720. $mapper_key = array_search($user_template, $iam_settings['mappers']);
  2721. // token valid, get mailbox
  2722. $stmt = $pdo->prepare("SELECT
  2723. mailbox.*,
  2724. domain.active AS d_active
  2725. FROM `mailbox`
  2726. INNER JOIN domain on mailbox.domain = domain.domain
  2727. WHERE `kind` NOT REGEXP 'location|thing|group'
  2728. AND `username` = :user");
  2729. $stmt->execute(array(':user' => $info['email']));
  2730. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  2731. if ($row){
  2732. if (!in_array($row['authsource'], array("keycloak", "generic-oidc"))) {
  2733. clear_session();
  2734. $_SESSION['return'][] = array(
  2735. 'type' => 'danger',
  2736. 'log' => array(__FUNCTION__, $info['email'], "The user's authentication source is not of type OIDC"),
  2737. 'msg' => 'login_failed'
  2738. );
  2739. return false;
  2740. }
  2741. if ($mapper_key !== false) {
  2742. // update user
  2743. $_SESSION['access_all_exception'] = '1';
  2744. mailbox('edit', 'mailbox_from_template', array(
  2745. 'username' => $info['email'],
  2746. 'name' => $info['name'],
  2747. 'template' => $iam_settings['templates'][$mapper_key]
  2748. ));
  2749. $_SESSION['access_all_exception'] = '0';
  2750. // get updated row
  2751. $stmt = $pdo->prepare("SELECT
  2752. mailbox.*,
  2753. domain.active AS d_active
  2754. FROM `mailbox`
  2755. INNER JOIN domain on mailbox.domain = domain.domain
  2756. WHERE `kind` NOT REGEXP 'location|thing|group'
  2757. AND `username` = :user");
  2758. $stmt->execute(array(':user' => $info['email']));
  2759. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  2760. }
  2761. if ($row['active'] != 1 || $row['d_active'] != 1) {
  2762. clear_session();
  2763. $_SESSION['return'][] = array(
  2764. 'type' => 'danger',
  2765. 'log' => array(__FUNCTION__, $info['email'], 'Domain or mailbox is inactive'),
  2766. 'msg' => 'login_failed'
  2767. );
  2768. return false;
  2769. }
  2770. set_user_loggedin_session($info['email']);
  2771. $_SESSION['iam_token'] = $plain_token;
  2772. $_SESSION['iam_refresh_token'] = $plain_refreshtoken;
  2773. $_SESSION['return'][] = array(
  2774. 'type' => 'success',
  2775. 'log' => array(__FUNCTION__, $_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role']),
  2776. 'msg' => array('logged_in_as', $_SESSION['mailcow_cc_username'])
  2777. );
  2778. return true;
  2779. }
  2780. // user doesn't exist, check if login provisioning is enabled
  2781. if (!$iam_settings['login_provisioning']){
  2782. $_SESSION['return'][] = array(
  2783. 'type' => 'danger',
  2784. 'log' => array(__FUNCTION__, "Auto-create users on login is deactivated"),
  2785. 'msg' => 'login_failed'
  2786. );
  2787. return false;
  2788. }
  2789. if (empty($iam_settings['mappers']) || empty($user_template) || $mapper_key === false){
  2790. if (!empty($iam_settings['default_template'])) {
  2791. $mbox_template = $iam_settings['default_template'];
  2792. } else {
  2793. clear_session();
  2794. $_SESSION['return'][] = array(
  2795. 'type' => 'danger',
  2796. 'log' => array(__FUNCTION__, $info['email'], 'No matching attribute mapping was found'),
  2797. 'msg' => 'login_failed'
  2798. );
  2799. return false;
  2800. }
  2801. } else {
  2802. $mbox_template = $iam_settings['templates'][$mapper_key];
  2803. }
  2804. // create mailbox
  2805. $_SESSION['access_all_exception'] = '1';
  2806. $create_res = mailbox('add', 'mailbox_from_template', array(
  2807. 'domain' => explode('@', $info['email'])[1],
  2808. 'local_part' => explode('@', $info['email'])[0],
  2809. 'name' => $info['name'],
  2810. 'authsource' => $iam_settings['authsource'],
  2811. 'template' => $mbox_template
  2812. ));
  2813. $_SESSION['access_all_exception'] = '0';
  2814. if (!$create_res){
  2815. clear_session();
  2816. $_SESSION['return'][] = array(
  2817. 'type' => 'danger',
  2818. 'log' => array(__FUNCTION__, $info['email'], 'Could not create mailbox on login'),
  2819. 'msg' => 'login_failed'
  2820. );
  2821. return false;
  2822. }
  2823. // double check if mailbox and domain is active
  2824. $stmt = $pdo->prepare("SELECT * FROM `mailbox`
  2825. INNER JOIN domain on mailbox.domain = domain.domain
  2826. WHERE `kind` NOT REGEXP 'location|thing|group'
  2827. AND `mailbox`.`active`='1'
  2828. AND `domain`.`active`='1'
  2829. AND `username` = :user");
  2830. $stmt->execute(array(':user' => $info['email']));
  2831. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  2832. if (empty($row)) {
  2833. clear_session();
  2834. $_SESSION['return'][] = array(
  2835. 'type' => 'danger',
  2836. 'log' => array(__FUNCTION__, $info['email'], 'Domain or mailbox is inactive'),
  2837. 'msg' => 'login_failed'
  2838. );
  2839. return false;
  2840. }
  2841. set_user_loggedin_session($info['email']);
  2842. $_SESSION['iam_token'] = $plain_token;
  2843. $_SESSION['iam_refresh_token'] = $plain_refreshtoken;
  2844. $_SESSION['return'][] = array(
  2845. 'type' => 'success',
  2846. 'log' => array(__FUNCTION__, $_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role']),
  2847. 'msg' => array('logged_in_as', $_SESSION['mailcow_cc_username'])
  2848. );
  2849. return true;
  2850. break;
  2851. case "refresh-token":
  2852. try {
  2853. $token = $iam_provider->getAccessToken('refresh_token', ['refresh_token' => $_SESSION['iam_refresh_token']]);
  2854. $plain_token = $token->getToken();
  2855. $plain_refreshtoken = $token->getRefreshToken();
  2856. $info = $iam_provider->getResourceOwner($token)->toArray();
  2857. } catch (Throwable $e) {
  2858. clear_session();
  2859. $_SESSION['return'][] = array(
  2860. 'type' => 'danger',
  2861. 'log' => array(__FUNCTION__),
  2862. 'msg' => array('refresh_login_failed', $e->getMessage())
  2863. );
  2864. return false;
  2865. }
  2866. if (empty($info['email'])){
  2867. clear_session();
  2868. $_SESSION['return'][] = array(
  2869. 'type' => 'danger',
  2870. 'log' => array(__FUNCTION__, $_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role']),
  2871. 'msg' => 'refresh_login_failed'
  2872. );
  2873. return false;
  2874. }
  2875. set_user_loggedin_session($info['email']);
  2876. $_SESSION['iam_token'] = $plain_token;
  2877. $_SESSION['iam_refresh_token'] = $plain_refreshtoken;
  2878. return true;
  2879. break;
  2880. case "get-redirect":
  2881. if ($iam_settings['authsource'] != 'keycloak' && $iam_settings['authsource'] != 'generic-oidc')
  2882. return false;
  2883. $options = [];
  2884. if (isset($iam_settings['redirect_url_extra'])) {
  2885. // check if the current domain is used in an extra redirect URL
  2886. $targetDomain = strtolower($_SERVER['HTTP_HOST']);
  2887. foreach ($iam_settings['redirect_url_extra'] as $testUrl) {
  2888. $testUrlParsed = parse_url($testUrl);
  2889. if (isset($testUrlParsed['host']) && strtolower($testUrlParsed['host']) == $targetDomain) {
  2890. $options['redirect_uri'] = $testUrl;
  2891. break;
  2892. }
  2893. }
  2894. }
  2895. $authUrl = $iam_provider->getAuthorizationUrl($options);
  2896. $_SESSION['oauth2state'] = $iam_provider->getState();
  2897. return $authUrl;
  2898. break;
  2899. case "get-keycloak-admin-token":
  2900. // get access_token for service account of mailcow client
  2901. if ($iam_settings['authsource'] !== 'keycloak') return false;
  2902. if (isset($iam_settings['access_token'])) {
  2903. // check if access_token is valid
  2904. $url = "{$iam_settings['server_url']}/realms/{$iam_settings['realm']}/protocol/openid-connect/token/introspect";
  2905. $req = http_build_query(array(
  2906. 'token' => $iam_settings['access_token'],
  2907. 'client_id' => $iam_settings['client_id'],
  2908. 'client_secret' => $iam_settings['client_secret']
  2909. ));
  2910. $curl = curl_init();
  2911. curl_setopt($curl, CURLOPT_URL, $url);
  2912. curl_setopt($curl, CURLOPT_TIMEOUT, 7);
  2913. curl_setopt($curl, CURLOPT_POST, 1);
  2914. curl_setopt($curl, CURLOPT_POSTFIELDS, $req);
  2915. curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
  2916. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2917. curl_setopt($curl, CURLOPT_TIMEOUT, 5);
  2918. $res = json_decode(curl_exec($curl), true);
  2919. $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  2920. curl_close ($curl);
  2921. if ($code == 200 && $res['active'] == true) {
  2922. // token is valid
  2923. return $iam_settings['access_token'];
  2924. }
  2925. }
  2926. $url = "{$iam_settings['server_url']}/realms/{$iam_settings['realm']}/protocol/openid-connect/token";
  2927. $req = http_build_query(array(
  2928. 'grant_type' => 'client_credentials',
  2929. 'client_id' => $iam_settings['client_id'],
  2930. 'client_secret' => $iam_settings['client_secret']
  2931. ));
  2932. $curl = curl_init();
  2933. curl_setopt($curl, CURLOPT_URL, $url);
  2934. curl_setopt($curl, CURLOPT_TIMEOUT, 7);
  2935. curl_setopt($curl, CURLOPT_POST, 1);
  2936. curl_setopt($curl, CURLOPT_POSTFIELDS, $req);
  2937. curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
  2938. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2939. curl_setopt($curl, CURLOPT_TIMEOUT, 5);
  2940. $res = json_decode(curl_exec($curl), true);
  2941. $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  2942. curl_close ($curl);
  2943. if ($code != 200) {
  2944. return false;
  2945. }
  2946. $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES (:key, :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
  2947. $stmt->execute(array(
  2948. ':key' => 'access_token',
  2949. ':value' => $res['access_token']
  2950. ));
  2951. return $res['access_token'];
  2952. break;
  2953. }
  2954. }
  2955. function reset_password($action, $data = null) {
  2956. global $pdo;
  2957. global $redis;
  2958. global $mailcow_hostname;
  2959. global $PW_RESET_TOKEN_LIMIT;
  2960. global $PW_RESET_TOKEN_LIFETIME;
  2961. $_data_log = $data;
  2962. if (isset($_data_log['new_password'])) $_data_log['new_password'] = '*';
  2963. if (isset($_data_log['new_password2'])) $_data_log['new_password2'] = '*';
  2964. switch ($action) {
  2965. case 'check':
  2966. $token = $data;
  2967. $stmt = $pdo->prepare("SELECT `t1`.`username` FROM `reset_password` AS `t1` JOIN `mailbox` AS `t2` ON `t1`.`username` = `t2`.`username` WHERE `t1`.`token` = :token AND `t1`.`created` > DATE_SUB(NOW(), INTERVAL :lifetime MINUTE) AND `t2`.`active` = 1 AND `t2`.`authsource` = 'mailcow';");
  2968. $stmt->execute(array(
  2969. ':token' => preg_replace('/[^a-zA-Z0-9-]/', '', $token),
  2970. ':lifetime' => $PW_RESET_TOKEN_LIFETIME
  2971. ));
  2972. $return = $stmt->fetch(PDO::FETCH_ASSOC);
  2973. return empty($return['username']) ? false : $return['username'];
  2974. break;
  2975. case 'issue':
  2976. $username = $data;
  2977. // perform cleanup
  2978. $stmt = $pdo->prepare("DELETE FROM `reset_password` WHERE created < DATE_SUB(NOW(), INTERVAL :lifetime MINUTE);");
  2979. $stmt->execute(array(':lifetime' => $PW_RESET_TOKEN_LIFETIME));
  2980. if (filter_var($username, FILTER_VALIDATE_EMAIL) === false) {
  2981. $_SESSION['return'][] = array(
  2982. 'type' => 'danger',
  2983. 'log' => array(__FUNCTION__, $action, $_data_log),
  2984. 'msg' => 'access_denied'
  2985. );
  2986. return false;
  2987. }
  2988. $pw_reset_notification = reset_password('get_notification', 'raw');
  2989. if (!$pw_reset_notification) return false;
  2990. if (empty($pw_reset_notification['from']) || empty($pw_reset_notification['subject'])) {
  2991. $_SESSION['return'][] = array(
  2992. 'type' => 'danger',
  2993. 'log' => array(__FUNCTION__, $action, $_data_log),
  2994. 'msg' => 'password_reset_na'
  2995. );
  2996. return false;
  2997. }
  2998. $stmt = $pdo->prepare("SELECT * FROM `mailbox`
  2999. WHERE `username` = :username AND authsource = 'mailcow'");
  3000. $stmt->execute(array(':username' => $username));
  3001. $mailbox_data = $stmt->fetch(PDO::FETCH_ASSOC);
  3002. if (empty($mailbox_data)) {
  3003. $_SESSION['return'][] = array(
  3004. 'type' => 'danger',
  3005. 'log' => array(__FUNCTION__, $action, $_data_log),
  3006. 'msg' => 'password_reset_invalid_user'
  3007. );
  3008. return false;
  3009. }
  3010. $mailbox_attr = json_decode($mailbox_data['attributes'], true);
  3011. if (empty($mailbox_attr['recovery_email']) || filter_var($mailbox_attr['recovery_email'], FILTER_VALIDATE_EMAIL) === false) {
  3012. $_SESSION['return'][] = array(
  3013. 'type' => 'danger',
  3014. 'log' => array(__FUNCTION__, $action, $_data_log),
  3015. 'msg' => "password_reset_invalid_user"
  3016. );
  3017. return false;
  3018. }
  3019. $stmt = $pdo->prepare("SELECT * FROM `reset_password`
  3020. WHERE `username` = :username");
  3021. $stmt->execute(array(':username' => $username));
  3022. $generated_token_count = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  3023. if ($generated_token_count >= $PW_RESET_TOKEN_LIMIT) {
  3024. $_SESSION['return'][] = array(
  3025. 'type' => 'danger',
  3026. 'log' => array(__FUNCTION__, $action, $_data_log),
  3027. 'msg' => "reset_token_limit_exceeded"
  3028. );
  3029. return false;
  3030. }
  3031. $token = implode('-', array(
  3032. strtoupper(bin2hex(random_bytes(3))),
  3033. strtoupper(bin2hex(random_bytes(3))),
  3034. strtoupper(bin2hex(random_bytes(3))),
  3035. strtoupper(bin2hex(random_bytes(3))),
  3036. strtoupper(bin2hex(random_bytes(3)))
  3037. ));
  3038. $stmt = $pdo->prepare("INSERT INTO `reset_password` (`username`, `token`)
  3039. VALUES (:username, :token)");
  3040. $stmt->execute(array(
  3041. ':username' => $username,
  3042. ':token' => $token
  3043. ));
  3044. $reset_link = getBaseURL() . "/reset-password?token=" . $token;
  3045. $request_date = new DateTime();
  3046. $locale_date = locale_get_default();
  3047. $date_formatter = new IntlDateFormatter(
  3048. $locale_date,
  3049. IntlDateFormatter::FULL,
  3050. IntlDateFormatter::FULL
  3051. );
  3052. $formatted_request_date = $date_formatter->format($request_date);
  3053. // set template vars
  3054. // subject
  3055. $pw_reset_notification['subject'] = str_replace('{{hostname}}', $mailcow_hostname, $pw_reset_notification['subject']);
  3056. $pw_reset_notification['subject'] = str_replace('{{link}}', $reset_link, $pw_reset_notification['subject']);
  3057. $pw_reset_notification['subject'] = str_replace('{{username}}', $username, $pw_reset_notification['subject']);
  3058. $pw_reset_notification['subject'] = str_replace('{{username2}}', $mailbox_attr['recovery_email'], $pw_reset_notification['subject']);
  3059. $pw_reset_notification['subject'] = str_replace('{{date}}', $formatted_request_date, $pw_reset_notification['subject']);
  3060. $pw_reset_notification['subject'] = str_replace('{{token_lifetime}}', $PW_RESET_TOKEN_LIFETIME, $pw_reset_notification['subject']);
  3061. // text
  3062. $pw_reset_notification['text_tmpl'] = str_replace('{{hostname}}', $mailcow_hostname, $pw_reset_notification['text_tmpl']);
  3063. $pw_reset_notification['text_tmpl'] = str_replace('{{link}}', $reset_link, $pw_reset_notification['text_tmpl']);
  3064. $pw_reset_notification['text_tmpl'] = str_replace('{{username}}', $username, $pw_reset_notification['text_tmpl']);
  3065. $pw_reset_notification['text_tmpl'] = str_replace('{{username2}}', $mailbox_attr['recovery_email'], $pw_reset_notification['text_tmpl']);
  3066. $pw_reset_notification['text_tmpl'] = str_replace('{{date}}', $formatted_request_date, $pw_reset_notification['text_tmpl']);
  3067. $pw_reset_notification['text_tmpl'] = str_replace('{{token_lifetime}}', $PW_RESET_TOKEN_LIFETIME, $pw_reset_notification['text_tmpl']);
  3068. // html
  3069. $pw_reset_notification['html_tmpl'] = str_replace('{{hostname}}', $mailcow_hostname, $pw_reset_notification['html_tmpl']);
  3070. $pw_reset_notification['html_tmpl'] = str_replace('{{link}}', $reset_link, $pw_reset_notification['html_tmpl']);
  3071. $pw_reset_notification['html_tmpl'] = str_replace('{{username}}', $username, $pw_reset_notification['html_tmpl']);
  3072. $pw_reset_notification['html_tmpl'] = str_replace('{{username2}}', $mailbox_attr['recovery_email'], $pw_reset_notification['html_tmpl']);
  3073. $pw_reset_notification['html_tmpl'] = str_replace('{{date}}', $formatted_request_date, $pw_reset_notification['html_tmpl']);
  3074. $pw_reset_notification['html_tmpl'] = str_replace('{{token_lifetime}}', $PW_RESET_TOKEN_LIFETIME, $pw_reset_notification['html_tmpl']);
  3075. $email_sent = reset_password('send_mail', array(
  3076. "from" => $pw_reset_notification['from'],
  3077. "to" => $mailbox_attr['recovery_email'],
  3078. "subject" => $pw_reset_notification['subject'],
  3079. "text" => $pw_reset_notification['text_tmpl'],
  3080. "html" => $pw_reset_notification['html_tmpl']
  3081. ));
  3082. if (!$email_sent){
  3083. $_SESSION['return'][] = array(
  3084. 'type' => 'danger',
  3085. 'log' => array(__FUNCTION__, $action, $_data_log),
  3086. 'msg' => "recovery_email_failed"
  3087. );
  3088. return false;
  3089. }
  3090. list($localPart, $domainPart) = explode('@', $mailbox_attr['recovery_email']);
  3091. if (strlen($localPart) > 1) {
  3092. $maskedLocalPart = $localPart[0] . str_repeat('*', strlen($localPart) - 1);
  3093. } else {
  3094. $maskedLocalPart = "*";
  3095. }
  3096. $_SESSION['return'][] = array(
  3097. 'type' => 'success',
  3098. 'log' => array(__FUNCTION__, $action, $_data_log),
  3099. 'msg' => array("recovery_email_sent", $maskedLocalPart . '@' . $domainPart)
  3100. );
  3101. return array(
  3102. "username" => $username,
  3103. "issue" => "success"
  3104. );
  3105. break;
  3106. case 'reset':
  3107. $token = $data['token'];
  3108. $new_password = $data['new_password'];
  3109. $new_password2 = $data['new_password2'];
  3110. $username = $data['username'];
  3111. $check_tfa = $data['check_tfa'];
  3112. if (!$username || !$token) {
  3113. $_SESSION['return'][] = array(
  3114. 'type' => 'danger',
  3115. 'log' => array(__FUNCTION__, $action, $_data_log),
  3116. 'msg' => 'invalid_reset_token'
  3117. );
  3118. return false;
  3119. }
  3120. # check new password
  3121. if (!password_check($new_password, $new_password2)) {
  3122. return false;
  3123. }
  3124. if ($check_tfa){
  3125. // check for tfa authenticators
  3126. $authenticators = get_tfa($username);
  3127. if (isset($authenticators['additional']) && is_array($authenticators['additional']) && count($authenticators['additional']) > 0) {
  3128. $_SESSION['pending_mailcow_cc_username'] = $username;
  3129. $_SESSION['pending_pw_reset_token'] = $token;
  3130. $_SESSION['pending_pw_new_password'] = $new_password;
  3131. $_SESSION['pending_tfa_methods'] = $authenticators['additional'];
  3132. $_SESSION['return'][] = array(
  3133. 'type' => 'info',
  3134. 'log' => array(__FUNCTION__, $user, '*'),
  3135. 'msg' => 'awaiting_tfa_confirmation'
  3136. );
  3137. return false;
  3138. }
  3139. }
  3140. # set new password
  3141. $password_hashed = hash_password($new_password);
  3142. $stmt = $pdo->prepare("UPDATE `mailbox` SET
  3143. `password` = :password_hashed,
  3144. `attributes` = JSON_SET(`attributes`, '$.passwd_update', NOW())
  3145. WHERE `username` = :username AND authsource = 'mailcow'");
  3146. $stmt->execute(array(
  3147. ':password_hashed' => $password_hashed,
  3148. ':username' => $username
  3149. ));
  3150. // perform cleanup
  3151. $stmt = $pdo->prepare("DELETE FROM `reset_password` WHERE `username` = :username;");
  3152. $stmt->execute(array(
  3153. ':username' => $username
  3154. ));
  3155. update_sogo_static_view($username);
  3156. $_SESSION['return'][] = array(
  3157. 'type' => 'success',
  3158. 'log' => array(__FUNCTION__, $action, $_data_log),
  3159. 'msg' => 'password_changed_success'
  3160. );
  3161. return true;
  3162. break;
  3163. case 'get_notification':
  3164. $type = $data;
  3165. try {
  3166. $settings['from'] = $redis->Get('PW_RESET_FROM');
  3167. $settings['subject'] = $redis->Get('PW_RESET_SUBJ');
  3168. $settings['html_tmpl'] = $redis->Get('PW_RESET_HTML');
  3169. $settings['text_tmpl'] = $redis->Get('PW_RESET_TEXT');
  3170. if (empty($settings['html_tmpl']) && empty($settings['text_tmpl'])) {
  3171. $settings['html_tmpl'] = file_get_contents("/tpls/pw_reset_html.tpl");
  3172. $settings['text_tmpl'] = file_get_contents("/tpls/pw_reset_text.tpl");
  3173. }
  3174. if ($type != "raw") {
  3175. $settings['html_tmpl'] = htmlspecialchars($settings['html_tmpl']);
  3176. $settings['text_tmpl'] = htmlspecialchars($settings['text_tmpl']);
  3177. }
  3178. }
  3179. catch (RedisException $e) {
  3180. $_SESSION['return'][] = array(
  3181. 'type' => 'danger',
  3182. 'log' => array(__FUNCTION__, $action, $_data_log),
  3183. 'msg' => array('redis_error', $e)
  3184. );
  3185. return false;
  3186. }
  3187. return $settings;
  3188. break;
  3189. case 'send_mail':
  3190. $from = $data['from'];
  3191. $to = $data['to'];
  3192. $text = $data['text'];
  3193. $html = $data['html'];
  3194. $subject = $data['subject'];
  3195. if (!filter_var($from, FILTER_VALIDATE_EMAIL)) {
  3196. $_SESSION['return'][] = array(
  3197. 'type' => 'danger',
  3198. 'log' => array(__FUNCTION__, $action, $_data_log),
  3199. 'msg' => 'from_invalid'
  3200. );
  3201. return false;
  3202. }
  3203. if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
  3204. $_SESSION['return'][] = array(
  3205. 'type' => 'danger',
  3206. 'log' => array(__FUNCTION__, $action, $_data_log),
  3207. 'msg' => 'to_invalid'
  3208. );
  3209. return false;
  3210. }
  3211. if (empty($subject)) {
  3212. $_SESSION['return'][] = array(
  3213. 'type' => 'danger',
  3214. 'log' => array(__FUNCTION__, $action, $_data_log),
  3215. 'msg' => 'subject_empty'
  3216. );
  3217. return false;
  3218. }
  3219. if (empty($text)) {
  3220. $_SESSION['return'][] = array(
  3221. 'type' => 'danger',
  3222. 'log' => array(__FUNCTION__, $action, $_data_log),
  3223. 'msg' => 'text_empty'
  3224. );
  3225. return false;
  3226. }
  3227. ini_set('max_execution_time', 0);
  3228. ini_set('max_input_time', 0);
  3229. $mail = new PHPMailer;
  3230. $mail->Timeout = 10;
  3231. $mail->SMTPOptions = array(
  3232. 'ssl' => array(
  3233. 'verify_peer' => false,
  3234. 'verify_peer_name' => false,
  3235. 'allow_self_signed' => true
  3236. )
  3237. );
  3238. $mail->isSMTP();
  3239. $mail->Host = 'postfix-mailcow';
  3240. $mail->SMTPAuth = false;
  3241. $mail->Port = 25;
  3242. $mail->setFrom($from);
  3243. $mail->Subject = $subject;
  3244. $mail->CharSet ="UTF-8";
  3245. if (!empty($html)) {
  3246. $mail->Body = $html;
  3247. $mail->AltBody = $text;
  3248. }
  3249. else {
  3250. $mail->Body = $text;
  3251. }
  3252. $mail->XMailer = 'MooMail';
  3253. $mail->AddAddress($to);
  3254. if (!$mail->send()) {
  3255. return false;
  3256. }
  3257. $mail->ClearAllRecipients();
  3258. return true;
  3259. break;
  3260. }
  3261. if ($_SESSION['mailcow_cc_role'] != "admin") {
  3262. $_SESSION['return'][] = array(
  3263. 'type' => 'danger',
  3264. 'log' => array(__FUNCTION__, $action, $_data_log),
  3265. 'msg' => 'access_denied'
  3266. );
  3267. return false;
  3268. }
  3269. switch ($action) {
  3270. case 'edit_notification':
  3271. $subject = $data['subject'];
  3272. $from = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $data['from']);
  3273. $from = (!filter_var($from, FILTER_VALIDATE_EMAIL)) ? "" : $from;
  3274. $subject = (empty($subject)) ? "" : $subject;
  3275. $text = (empty($data['text_tmpl'])) ? "" : $data['text_tmpl'];
  3276. $html = (empty($data['html_tmpl'])) ? "" : $data['html_tmpl'];
  3277. try {
  3278. $redis->Set('PW_RESET_FROM', $from);
  3279. $redis->Set('PW_RESET_SUBJ', $subject);
  3280. $redis->Set('PW_RESET_HTML', $html);
  3281. $redis->Set('PW_RESET_TEXT', $text);
  3282. }
  3283. catch (RedisException $e) {
  3284. $_SESSION['return'][] = array(
  3285. 'type' => 'danger',
  3286. 'log' => array(__FUNCTION__, $action, $_data_log),
  3287. 'msg' => array('redis_error', $e)
  3288. );
  3289. return false;
  3290. }
  3291. $_SESSION['return'][] = array(
  3292. 'type' => 'success',
  3293. 'log' => array(__FUNCTION__, $action, $_data_log),
  3294. 'msg' => 'saved_settings'
  3295. );
  3296. break;
  3297. }
  3298. }
  3299. function clear_session(){
  3300. session_regenerate_id(true);
  3301. session_unset();
  3302. session_destroy();
  3303. session_write_close();
  3304. }
  3305. function set_user_loggedin_session($user) {
  3306. session_regenerate_id(true);
  3307. $_SESSION['mailcow_cc_username'] = $user;
  3308. $_SESSION['mailcow_cc_role'] = 'user';
  3309. $sogo_sso_pass = file_get_contents("/etc/sogo-sso/sogo-sso.pass");
  3310. $_SESSION['sogo-sso-user-allowed'][] = $user;
  3311. $_SESSION['sogo-sso-pass'] = $sogo_sso_pass;
  3312. unset($_SESSION['pending_mailcow_cc_username']);
  3313. unset($_SESSION['pending_mailcow_cc_role']);
  3314. unset($_SESSION['pending_tfa_methods']);
  3315. }
  3316. function protect_route($allowed_roles = ['admin', 'domainadmin', 'user'], $redirects = []) {
  3317. // Check if user is authenticated
  3318. if (!isset($_SESSION['mailcow_cc_role'])) {
  3319. if (isset($redirects['unauthenticated'])) {
  3320. header('Location: ' . $redirects['unauthenticated']);
  3321. } else {
  3322. header('Location: /');
  3323. }
  3324. exit();
  3325. }
  3326. // Check for pending actions (2FA setup, password update)
  3327. if (!empty($_SESSION['pending_tfa_setup']) || !empty($_SESSION['pending_pw_update'])) {
  3328. $pending_redirect = '/';
  3329. if ($_SESSION['mailcow_cc_role'] === 'admin') {
  3330. $pending_redirect = '/admin';
  3331. } elseif ($_SESSION['mailcow_cc_role'] === 'domainadmin') {
  3332. $pending_redirect = '/domainadmin';
  3333. }
  3334. header('Location: ' . $pending_redirect);
  3335. exit();
  3336. }
  3337. // Check if user's role is in the allowed roles for the route
  3338. if (!in_array($_SESSION['mailcow_cc_role'], $allowed_roles)) {
  3339. if (isset($_SESSION['mailcow_cc_role']) && $_SESSION['mailcow_cc_role'] == 'admin') {
  3340. header('Location: /admin/dashboard');
  3341. exit();
  3342. }
  3343. elseif (isset($_SESSION['mailcow_cc_role']) && $_SESSION['mailcow_cc_role'] == 'domainadmin') {
  3344. header('Location: /domainadmin/mailbox');
  3345. exit();
  3346. }
  3347. elseif (isset($_SESSION['mailcow_cc_role']) && $_SESSION['mailcow_cc_role'] == 'user') {
  3348. header('Location: /user');
  3349. exit();
  3350. }
  3351. else {
  3352. header('Location: /');
  3353. exit();
  3354. }
  3355. }
  3356. }
  3357. function get_logs($application, $lines = false) {
  3358. if ($lines === false) {
  3359. $lines = $GLOBALS['LOG_LINES'] - 1;
  3360. }
  3361. elseif(is_numeric($lines) && $lines >= 1) {
  3362. $lines = abs(intval($lines) - 1);
  3363. }
  3364. else {
  3365. list ($from, $to) = explode('-', $lines);
  3366. $from = intval($from);
  3367. $to = intval($to);
  3368. if ($from < 1 || $to < $from) { return false; }
  3369. }
  3370. global $redis;
  3371. global $pdo;
  3372. if ($_SESSION['mailcow_cc_role'] != "admin") {
  3373. return false;
  3374. }
  3375. // SQL
  3376. if ($application == "mailcow-ui") {
  3377. if (isset($from) && isset($to)) {
  3378. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :from, :to");
  3379. $stmt->execute(array(
  3380. ':from' => $from - 1,
  3381. ':to' => $to
  3382. ));
  3383. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  3384. }
  3385. else {
  3386. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :lines");
  3387. $stmt->execute(array(
  3388. ':lines' => $lines + 1,
  3389. ));
  3390. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  3391. }
  3392. if (is_array($data)) {
  3393. return $data;
  3394. }
  3395. }
  3396. if ($application == "sasl") {
  3397. if (isset($from) && isset($to)) {
  3398. $stmt = $pdo->prepare("SELECT * FROM `sasl_log` ORDER BY `datetime` DESC LIMIT :from, :to");
  3399. $stmt->execute(array(
  3400. ':from' => $from - 1,
  3401. ':to' => $to
  3402. ));
  3403. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  3404. }
  3405. else {
  3406. $stmt = $pdo->prepare("SELECT * FROM `sasl_log` ORDER BY `datetime` DESC LIMIT :lines");
  3407. $stmt->execute(array(
  3408. ':lines' => $lines + 1,
  3409. ));
  3410. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  3411. }
  3412. if (is_array($data)) {
  3413. return $data;
  3414. }
  3415. }
  3416. // Redis
  3417. if ($application == "dovecot-mailcow") {
  3418. if (isset($from) && isset($to)) {
  3419. $data = $redis->lRange('DOVECOT_MAILLOG', $from - 1, $to - 1);
  3420. }
  3421. else {
  3422. $data = $redis->lRange('DOVECOT_MAILLOG', 0, $lines);
  3423. }
  3424. if ($data) {
  3425. foreach ($data as $json_line) {
  3426. $data_array[] = json_decode($json_line, true);
  3427. }
  3428. return $data_array;
  3429. }
  3430. }
  3431. if ($application == "cron-mailcow") {
  3432. if (isset($from) && isset($to)) {
  3433. $data = $redis->lRange('CRON_LOG', $from - 1, $to - 1);
  3434. }
  3435. else {
  3436. $data = $redis->lRange('CRON_LOG', 0, $lines);
  3437. }
  3438. if ($data) {
  3439. foreach ($data as $json_line) {
  3440. $data_array[] = json_decode($json_line, true);
  3441. }
  3442. return $data_array;
  3443. }
  3444. }
  3445. if ($application == "postfix-mailcow") {
  3446. if (isset($from) && isset($to)) {
  3447. $data = $redis->lRange('POSTFIX_MAILLOG', $from - 1, $to - 1);
  3448. }
  3449. else {
  3450. $data = $redis->lRange('POSTFIX_MAILLOG', 0, $lines);
  3451. }
  3452. if ($data) {
  3453. foreach ($data as $json_line) {
  3454. $data_array[] = json_decode($json_line, true);
  3455. }
  3456. return $data_array;
  3457. }
  3458. }
  3459. if ($application == "sogo-mailcow") {
  3460. if (isset($from) && isset($to)) {
  3461. $data = $redis->lRange('SOGO_LOG', $from - 1, $to - 1);
  3462. }
  3463. else {
  3464. $data = $redis->lRange('SOGO_LOG', 0, $lines);
  3465. }
  3466. if ($data) {
  3467. foreach ($data as $json_line) {
  3468. $data_array[] = json_decode($json_line, true);
  3469. }
  3470. return $data_array;
  3471. }
  3472. }
  3473. if ($application == "watchdog-mailcow") {
  3474. if (isset($from) && isset($to)) {
  3475. $data = $redis->lRange('WATCHDOG_LOG', $from - 1, $to - 1);
  3476. }
  3477. else {
  3478. $data = $redis->lRange('WATCHDOG_LOG', 0, $lines);
  3479. }
  3480. if ($data) {
  3481. foreach ($data as $json_line) {
  3482. $data_array[] = json_decode($json_line, true);
  3483. }
  3484. return $data_array;
  3485. }
  3486. }
  3487. if ($application == "acme-mailcow") {
  3488. if (isset($from) && isset($to)) {
  3489. $data = $redis->lRange('ACME_LOG', $from - 1, $to - 1);
  3490. }
  3491. else {
  3492. $data = $redis->lRange('ACME_LOG', 0, $lines);
  3493. }
  3494. if ($data) {
  3495. foreach ($data as $json_line) {
  3496. $data_array[] = json_decode($json_line, true);
  3497. }
  3498. return $data_array;
  3499. }
  3500. }
  3501. if ($application == "ratelimited") {
  3502. if (isset($from) && isset($to)) {
  3503. $data = $redis->lRange('RL_LOG', $from - 1, $to - 1);
  3504. }
  3505. else {
  3506. $data = $redis->lRange('RL_LOG', 0, $lines);
  3507. }
  3508. if ($data) {
  3509. foreach ($data as $json_line) {
  3510. $data_array[] = json_decode($json_line, true);
  3511. }
  3512. return $data_array;
  3513. }
  3514. }
  3515. if ($application == "api-mailcow") {
  3516. if (isset($from) && isset($to)) {
  3517. $data = $redis->lRange('API_LOG', $from - 1, $to - 1);
  3518. }
  3519. else {
  3520. $data = $redis->lRange('API_LOG', 0, $lines);
  3521. }
  3522. if ($data) {
  3523. foreach ($data as $json_line) {
  3524. $data_array[] = json_decode($json_line, true);
  3525. }
  3526. return $data_array;
  3527. }
  3528. }
  3529. if ($application == "netfilter-mailcow") {
  3530. if (isset($from) && isset($to)) {
  3531. $data = $redis->lRange('NETFILTER_LOG', $from - 1, $to - 1);
  3532. }
  3533. else {
  3534. $data = $redis->lRange('NETFILTER_LOG', 0, $lines);
  3535. }
  3536. if ($data) {
  3537. foreach ($data as $json_line) {
  3538. $data_array[] = json_decode($json_line, true);
  3539. }
  3540. return $data_array;
  3541. }
  3542. }
  3543. if ($application == "autodiscover-mailcow") {
  3544. if (isset($from) && isset($to)) {
  3545. $data = $redis->lRange('AUTODISCOVER_LOG', $from - 1, $to - 1);
  3546. }
  3547. else {
  3548. $data = $redis->lRange('AUTODISCOVER_LOG', 0, $lines);
  3549. }
  3550. if ($data) {
  3551. foreach ($data as $json_line) {
  3552. $data_array[] = json_decode($json_line, true);
  3553. }
  3554. return $data_array;
  3555. }
  3556. }
  3557. if ($application == "rspamd-history") {
  3558. $curl = curl_init();
  3559. curl_setopt($curl, CURLOPT_UNIX_SOCKET_PATH, '/var/lib/rspamd/rspamd.sock');
  3560. if (!is_numeric($lines)) {
  3561. list ($from, $to) = explode('-', $lines);
  3562. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?from=" . intval($from) . "&to=" . intval($to));
  3563. }
  3564. else {
  3565. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?to=" . intval($lines));
  3566. }
  3567. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  3568. $history = curl_exec($curl);
  3569. if (!curl_errno($curl)) {
  3570. $data_array = json_decode($history, true);
  3571. curl_close($curl);
  3572. return $data_array['rows'];
  3573. }
  3574. curl_close($curl);
  3575. return false;
  3576. }
  3577. if ($application == "rspamd-stats") {
  3578. $curl = curl_init();
  3579. curl_setopt($curl, CURLOPT_UNIX_SOCKET_PATH, '/var/lib/rspamd/rspamd.sock');
  3580. curl_setopt($curl, CURLOPT_URL,"http://rspamd/stat");
  3581. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  3582. $stats = curl_exec($curl);
  3583. if (!curl_errno($curl)) {
  3584. $data_array = json_decode($stats, true);
  3585. curl_close($curl);
  3586. return $data_array;
  3587. }
  3588. curl_close($curl);
  3589. return false;
  3590. }
  3591. return false;
  3592. }
  3593. function getGUID() {
  3594. if (function_exists('com_create_guid')) {
  3595. return com_create_guid();
  3596. }
  3597. mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
  3598. $charid = strtoupper(md5(uniqid(rand(), true)));
  3599. $hyphen = chr(45);// "-"
  3600. return substr($charid, 0, 8).$hyphen
  3601. .substr($charid, 8, 4).$hyphen
  3602. .substr($charid,12, 4).$hyphen
  3603. .substr($charid,16, 4).$hyphen
  3604. .substr($charid,20,12);
  3605. }
  3606. function cleanupJS($ignore = '', $folder = '/tmp/*.js') {
  3607. $now = time();
  3608. foreach (glob($folder) as $filename) {
  3609. if(strpos($filename, $ignore) !== false) {
  3610. continue;
  3611. }
  3612. if (is_file($filename)) {
  3613. if ($now - filemtime($filename) >= 60 * 60) {
  3614. unlink($filename);
  3615. }
  3616. }
  3617. }
  3618. }
  3619. function cleanupCSS($ignore = '', $folder = '/tmp/*.css') {
  3620. $now = time();
  3621. foreach (glob($folder) as $filename) {
  3622. if(strpos($filename, $ignore) !== false) {
  3623. continue;
  3624. }
  3625. if (is_file($filename)) {
  3626. if ($now - filemtime($filename) >= 60 * 60) {
  3627. unlink($filename);
  3628. }
  3629. }
  3630. }
  3631. }
  3632. ?>