functions.inc.php 139 KB

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