functions.inc.php 136 KB

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