functions.inc.php 125 KB

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