functions.inc.php 131 KB

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