functions.inc.php 137 KB

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