functions.inc.php 127 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410
  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. $_data_log = $_data;
  1205. // Not logging registration data, only actions
  1206. // Silent errors for "get" requests
  1207. switch ($_data["action"]) {
  1208. case "register":
  1209. $username = $_SESSION['mailcow_cc_username'];
  1210. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1211. $_SESSION['return'][] = array(
  1212. 'type' => 'danger',
  1213. 'log' => array(__FUNCTION__, $_data["action"]),
  1214. 'msg' => 'access_denied'
  1215. );
  1216. return false;
  1217. }
  1218. $stmt = $pdo->prepare("INSERT INTO `fido2` (`username`, `rpId`, `credentialPublicKey`, `certificateChain`, `certificate`, `certificateIssuer`, `certificateSubject`, `signatureCounter`, `AAGUID`, `credentialId`)
  1219. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
  1220. $stmt->execute(array(
  1221. $username,
  1222. $_data['registration']->rpId,
  1223. $_data['registration']->credentialPublicKey,
  1224. $_data['registration']->certificateChain,
  1225. $_data['registration']->certificate,
  1226. $_data['registration']->certificateIssuer,
  1227. $_data['registration']->certificateSubject,
  1228. $_data['registration']->signatureCounter,
  1229. $_data['registration']->AAGUID,
  1230. $_data['registration']->credentialId)
  1231. );
  1232. $_SESSION['return'][] = array(
  1233. 'type' => 'success',
  1234. 'log' => array(__FUNCTION__, $_data["action"]),
  1235. 'msg' => array('object_modified', $username)
  1236. );
  1237. break;
  1238. case "get_user_cids":
  1239. // Used to exclude existing CredentialIds while registering
  1240. $username = $_SESSION['mailcow_cc_username'];
  1241. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1242. return false;
  1243. }
  1244. $stmt = $pdo->prepare("SELECT `credentialId` FROM `fido2` WHERE `username` = :username");
  1245. $stmt->execute(array(':username' => $username));
  1246. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1247. while($row = array_shift($rows)) {
  1248. $cids[] = $row['credentialId'];
  1249. }
  1250. return $cids;
  1251. break;
  1252. case "get_all_cids":
  1253. // Only needed when using fido2 with username
  1254. $stmt = $pdo->query("SELECT `credentialId` FROM `fido2`");
  1255. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1256. while($row = array_shift($rows)) {
  1257. $cids[] = $row['credentialId'];
  1258. }
  1259. return $cids;
  1260. break;
  1261. case "get_by_b64cid":
  1262. if (!isset($_data['cid']) || empty($_data['cid'])) {
  1263. return false;
  1264. }
  1265. $stmt = $pdo->prepare("SELECT `certificateSubject`, `username`, `credentialPublicKey`, SHA2(`credentialId`, 256) AS `cid` FROM `fido2` WHERE `credentialId` = :cid");
  1266. $stmt->execute(array(':cid' => base64_decode($_data['cid'])));
  1267. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1268. if (empty($row) || empty($row['credentialPublicKey']) || empty($row['username'])) {
  1269. return false;
  1270. }
  1271. $data['pub_key'] = $row['credentialPublicKey'];
  1272. $data['username'] = $row['username'];
  1273. $data['subject'] = $row['certificateSubject'];
  1274. $data['cid'] = $row['cid'];
  1275. return $data;
  1276. break;
  1277. case "get_friendly_names":
  1278. $username = $_SESSION['mailcow_cc_username'];
  1279. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1280. return false;
  1281. }
  1282. $stmt = $pdo->prepare("SELECT SHA2(`credentialId`, 256) AS `cid`, `created`, `certificateSubject`, `friendlyName` FROM `fido2` WHERE `username` = :username");
  1283. $stmt->execute(array(':username' => $username));
  1284. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1285. while($row = array_shift($rows)) {
  1286. $fns[] = array(
  1287. "subject" => (empty($row['certificateSubject']) ? 'Unknown (' . $row['created'] . ')' : $row['certificateSubject']),
  1288. "fn" => $row['friendlyName'],
  1289. "cid" => $row['cid']
  1290. );
  1291. }
  1292. return $fns;
  1293. break;
  1294. case "unset_fido2_key":
  1295. $username = $_SESSION['mailcow_cc_username'];
  1296. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1297. $_SESSION['return'][] = array(
  1298. 'type' => 'danger',
  1299. 'log' => array(__FUNCTION__, $_data["action"]),
  1300. 'msg' => 'access_denied'
  1301. );
  1302. return false;
  1303. }
  1304. $stmt = $pdo->prepare("DELETE FROM `fido2` WHERE `username` = :username AND SHA2(`credentialId`, 256) = :cid");
  1305. $stmt->execute(array(
  1306. ':username' => $username,
  1307. ':cid' => $_data['post_data']['unset_fido2_key']
  1308. ));
  1309. $_SESSION['return'][] = array(
  1310. 'type' => 'success',
  1311. 'log' => array(__FUNCTION__, $_data_log),
  1312. 'msg' => array('object_modified', htmlspecialchars($username))
  1313. );
  1314. break;
  1315. case "edit_fn":
  1316. $username = $_SESSION['mailcow_cc_username'];
  1317. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1318. $_SESSION['return'][] = array(
  1319. 'type' => 'danger',
  1320. 'log' => array(__FUNCTION__, $_data["action"]),
  1321. 'msg' => 'access_denied'
  1322. );
  1323. return false;
  1324. }
  1325. $stmt = $pdo->prepare("UPDATE `fido2` SET `friendlyName` = :friendlyName WHERE SHA2(`credentialId`, 256) = :cid AND `username` = :username");
  1326. $stmt->execute(array(
  1327. ':username' => $username,
  1328. ':friendlyName' => $_data['fido2_attrs']['fido2_fn'],
  1329. ':cid' => $_data['fido2_attrs']['fido2_cid']
  1330. ));
  1331. $_SESSION['return'][] = array(
  1332. 'type' => 'success',
  1333. 'log' => array(__FUNCTION__, $_data_log),
  1334. 'msg' => array('object_modified', htmlspecialchars($username))
  1335. );
  1336. break;
  1337. }
  1338. }
  1339. function unset_tfa_key($_data) {
  1340. // Can only unset own keys
  1341. // Needs at least one key left
  1342. global $pdo;
  1343. global $lang;
  1344. $_data_log = $_data;
  1345. $access_denied = null;
  1346. $id = intval($_data['unset_tfa_key']);
  1347. $username = $_SESSION['mailcow_cc_username'];
  1348. // check for empty user and role
  1349. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) $access_denied = true;
  1350. try {
  1351. if (!is_numeric($id)) $access_denied = true;
  1352. // set access_denied error
  1353. if ($access_denied){
  1354. $_SESSION['return'][] = array(
  1355. 'type' => 'danger',
  1356. 'log' => array(__FUNCTION__, $_data_log),
  1357. 'msg' => 'access_denied'
  1358. );
  1359. return false;
  1360. }
  1361. // check if it's last key
  1362. $stmt = $pdo->prepare("SELECT COUNT(*) AS `keys` FROM `tfa`
  1363. WHERE `username` = :username AND `active` = '1'");
  1364. $stmt->execute(array(':username' => $username));
  1365. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1366. if ($row['keys'] == "1") {
  1367. $_SESSION['return'][] = array(
  1368. 'type' => 'danger',
  1369. 'log' => array(__FUNCTION__, $_data_log),
  1370. 'msg' => 'last_key'
  1371. );
  1372. return false;
  1373. }
  1374. // delete key
  1375. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username AND `id` = :id");
  1376. $stmt->execute(array(':username' => $username, ':id' => $id));
  1377. $_SESSION['return'][] = array(
  1378. 'type' => 'success',
  1379. 'log' => array(__FUNCTION__, $_data_log),
  1380. 'msg' => array('object_modified', $username)
  1381. );
  1382. }
  1383. catch (PDOException $e) {
  1384. $_SESSION['return'][] = array(
  1385. 'type' => 'danger',
  1386. 'log' => array(__FUNCTION__, $_data_log),
  1387. 'msg' => array('mysql_error', $e)
  1388. );
  1389. return false;
  1390. }
  1391. }
  1392. function get_tfa($username = null, $id = null) {
  1393. global $pdo;
  1394. if (empty($username) && isset($_SESSION['mailcow_cc_username'])) {
  1395. $username = $_SESSION['mailcow_cc_username'];
  1396. }
  1397. elseif (empty($username)) {
  1398. return false;
  1399. }
  1400. if (!isset($id)){
  1401. // fetch all tfa methods - just get information about possible authenticators
  1402. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `authmech` FROM `tfa`
  1403. WHERE `username` = :username AND `active` = '1'");
  1404. $stmt->execute(array(':username' => $username));
  1405. $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1406. // no tfa methods found
  1407. if (count($results) == 0) {
  1408. $data['name'] = 'none';
  1409. $data['pretty'] = "-";
  1410. $data['additional'] = array();
  1411. return $data;
  1412. }
  1413. $data['additional'] = $results;
  1414. return $data;
  1415. } else {
  1416. // fetch specific authenticator details by id
  1417. $stmt = $pdo->prepare("SELECT * FROM `tfa`
  1418. WHERE `username` = :username AND `id` = :id AND `active` = '1'");
  1419. $stmt->execute(array(':username' => $username, ':id' => $id));
  1420. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1421. if (isset($row["authmech"])) {
  1422. switch ($row["authmech"]) {
  1423. case "yubi_otp":
  1424. $data['name'] = "yubi_otp";
  1425. $data['pretty'] = "Yubico OTP";
  1426. $stmt = $pdo->prepare("SELECT `id`, `key_id`, RIGHT(`secret`, 12) AS 'modhex' FROM `tfa` WHERE `authmech` = 'yubi_otp' AND `username` = :username AND `id` = :id");
  1427. $stmt->execute(array(
  1428. ':username' => $username,
  1429. ':id' => $id
  1430. ));
  1431. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1432. while($row = array_shift($rows)) {
  1433. $data['additional'][] = $row;
  1434. }
  1435. return $data;
  1436. break;
  1437. // u2f - deprecated, should be removed
  1438. case "u2f":
  1439. $data['name'] = "u2f";
  1440. $data['pretty'] = "Fido U2F";
  1441. $stmt = $pdo->prepare("SELECT `id`, `key_id` FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username AND `id` = :id");
  1442. $stmt->execute(array(
  1443. ':username' => $username,
  1444. ':id' => $id
  1445. ));
  1446. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1447. while($row = array_shift($rows)) {
  1448. $data['additional'][] = $row;
  1449. }
  1450. return $data;
  1451. break;
  1452. case "hotp":
  1453. $data['name'] = "hotp";
  1454. $data['pretty'] = "HMAC-based OTP";
  1455. return $data;
  1456. break;
  1457. case "totp":
  1458. $data['name'] = "totp";
  1459. $data['pretty'] = "Time-based OTP";
  1460. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `secret` FROM `tfa` WHERE `authmech` = 'totp' AND `username` = :username AND `id` = :id");
  1461. $stmt->execute(array(
  1462. ':username' => $username,
  1463. ':id' => $id
  1464. ));
  1465. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1466. while($row = array_shift($rows)) {
  1467. $data['additional'][] = $row;
  1468. }
  1469. return $data;
  1470. break;
  1471. case "webauthn":
  1472. $data['name'] = "webauthn";
  1473. $data['pretty'] = "WebAuthn";
  1474. $stmt = $pdo->prepare("SELECT `id`, `key_id` FROM `tfa` WHERE `authmech` = 'webauthn' AND `username` = :username AND `id` = :id");
  1475. $stmt->execute(array(
  1476. ':username' => $username,
  1477. ':id' => $id
  1478. ));
  1479. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1480. while($row = array_shift($rows)) {
  1481. $data['additional'][] = $row;
  1482. }
  1483. return $data;
  1484. break;
  1485. default:
  1486. $data['name'] = 'none';
  1487. $data['pretty'] = "-";
  1488. return $data;
  1489. break;
  1490. }
  1491. }
  1492. else {
  1493. $data['name'] = 'none';
  1494. $data['pretty'] = "-";
  1495. return $data;
  1496. }
  1497. }
  1498. }
  1499. function verify_tfa_login($username, $_data) {
  1500. global $pdo;
  1501. global $yubi;
  1502. global $u2f;
  1503. global $tfa;
  1504. global $WebAuthn;
  1505. if ($_data['tfa_method'] != 'u2f'){
  1506. switch ($_data["tfa_method"]) {
  1507. case "yubi_otp":
  1508. if (!ctype_alnum($_data['token']) || strlen($_data['token']) != 44) {
  1509. $_SESSION['return'][] = array(
  1510. 'type' => 'danger',
  1511. 'log' => array(__FUNCTION__, $username, '*'),
  1512. 'msg' => array('yotp_verification_failed', 'token length error')
  1513. );
  1514. return false;
  1515. }
  1516. $yubico_modhex_id = substr($_data['token'], 0, 12);
  1517. $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
  1518. WHERE `username` = :username
  1519. AND `authmech` = 'yubi_otp'
  1520. AND `active` = '1'
  1521. AND `secret` LIKE :modhex");
  1522. $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id));
  1523. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1524. $yubico_auth = explode(':', $row['secret']);
  1525. $yubi = new Auth_Yubico($yubico_auth[0], $yubico_auth[1]);
  1526. $yauth = $yubi->verify($_data['token']);
  1527. if (PEAR::isError($yauth)) {
  1528. $_SESSION['return'][] = array(
  1529. 'type' => 'danger',
  1530. 'log' => array(__FUNCTION__, $username, '*'),
  1531. 'msg' => array('yotp_verification_failed', $yauth->getMessage())
  1532. );
  1533. return false;
  1534. }
  1535. else {
  1536. $_SESSION['tfa_id'] = $row['id'];
  1537. $_SESSION['return'][] = array(
  1538. 'type' => 'success',
  1539. 'log' => array(__FUNCTION__, $username, '*'),
  1540. 'msg' => 'verified_yotp_login'
  1541. );
  1542. return true;
  1543. }
  1544. $_SESSION['return'][] = array(
  1545. 'type' => 'danger',
  1546. 'log' => array(__FUNCTION__, $username, '*'),
  1547. 'msg' => array('yotp_verification_failed', 'unknown')
  1548. );
  1549. return false;
  1550. break;
  1551. case "hotp":
  1552. return false;
  1553. break;
  1554. case "totp":
  1555. try {
  1556. $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
  1557. WHERE `username` = :username
  1558. AND `authmech` = 'totp'
  1559. AND `id` = :id
  1560. AND `active`='1'");
  1561. $stmt->execute(array(':username' => $username, ':id' => $_data['id']));
  1562. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1563. foreach ($rows as $row) {
  1564. if ($tfa->verifyCode($row['secret'], $_data['token']) === true) {
  1565. $_SESSION['tfa_id'] = $row['id'];
  1566. $_SESSION['return'][] = array(
  1567. 'type' => 'success',
  1568. 'log' => array(__FUNCTION__, $username, '*'),
  1569. 'msg' => 'verified_totp_login'
  1570. );
  1571. return true;
  1572. }
  1573. }
  1574. $_SESSION['return'][] = array(
  1575. 'type' => 'danger',
  1576. 'log' => array(__FUNCTION__, $username, '*'),
  1577. 'msg' => 'totp_verification_failed'
  1578. );
  1579. return false;
  1580. }
  1581. catch (PDOException $e) {
  1582. $_SESSION['return'][] = array(
  1583. 'type' => 'danger',
  1584. 'log' => array(__FUNCTION__, $username, '*'),
  1585. 'msg' => array('mysql_error', $e)
  1586. );
  1587. return false;
  1588. }
  1589. break;
  1590. case "webauthn":
  1591. $tokenData = json_decode($_data['token']);
  1592. $clientDataJSON = base64_decode($tokenData->clientDataJSON);
  1593. $authenticatorData = base64_decode($tokenData->authenticatorData);
  1594. $signature = base64_decode($tokenData->signature);
  1595. $id = base64_decode($tokenData->id);
  1596. $challenge = $_SESSION['challenge'];
  1597. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `keyHandle`, `username`, `publicKey` FROM `tfa` WHERE `id` = :id AND `active`='1'");
  1598. $stmt->execute(array(':id' => $_data['id']));
  1599. $process_webauthn = $stmt->fetch(PDO::FETCH_ASSOC);
  1600. if (empty($process_webauthn)){
  1601. $_SESSION['return'][] = array(
  1602. 'type' => 'danger',
  1603. 'log' => array(__FUNCTION__, $username, '*'),
  1604. 'msg' => array('webauthn_authenticator_failed')
  1605. );
  1606. return false;
  1607. }
  1608. if (empty($process_webauthn['publicKey']) || $process_webauthn['publicKey'] === false) {
  1609. $_SESSION['return'][] = array(
  1610. 'type' => 'danger',
  1611. 'log' => array(__FUNCTION__, $username, '*'),
  1612. 'msg' => array('webauthn_publickey_failed')
  1613. );
  1614. return false;
  1615. }
  1616. if ($process_webauthn['username'] != $_SESSION['pending_mailcow_cc_username']){
  1617. $_SESSION['return'][] = array(
  1618. 'type' => 'danger',
  1619. 'log' => array(__FUNCTION__, $username, '*'),
  1620. 'msg' => array('webauthn_username_failed')
  1621. );
  1622. return false;
  1623. }
  1624. try {
  1625. $WebAuthn->processGet($clientDataJSON, $authenticatorData, $signature, $process_webauthn['publicKey'], $challenge, null, $GLOBALS['WEBAUTHN_UV_FLAG_LOGIN'], $GLOBALS['WEBAUTHN_USER_PRESENT_FLAG']);
  1626. }
  1627. catch (Throwable $ex) {
  1628. $_SESSION['return'][] = array(
  1629. 'type' => 'danger',
  1630. 'log' => array(__FUNCTION__, $username, '*'),
  1631. 'msg' => array('webauthn_verification_failed', $ex->getMessage())
  1632. );
  1633. return false;
  1634. }
  1635. $stmt = $pdo->prepare("SELECT `superadmin` FROM `admin` WHERE `username` = :username");
  1636. $stmt->execute(array(':username' => $process_webauthn['username']));
  1637. $obj_props = $stmt->fetch(PDO::FETCH_ASSOC);
  1638. if ($obj_props['superadmin'] === 1) {
  1639. $_SESSION["mailcow_cc_role"] = "admin";
  1640. }
  1641. elseif ($obj_props['superadmin'] === 0) {
  1642. $_SESSION["mailcow_cc_role"] = "domainadmin";
  1643. }
  1644. else {
  1645. $stmt = $pdo->prepare("SELECT `username` FROM `mailbox` WHERE `username` = :username");
  1646. $stmt->execute(array(':username' => $process_webauthn['username']));
  1647. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1648. if (!empty($row['username'])) {
  1649. $_SESSION["mailcow_cc_role"] = "user";
  1650. } else {
  1651. $_SESSION['return'][] = array(
  1652. 'type' => 'danger',
  1653. 'log' => array(__FUNCTION__, $username, '*'),
  1654. 'msg' => array('webauthn_role_failed')
  1655. );
  1656. return false;
  1657. }
  1658. }
  1659. $_SESSION["mailcow_cc_username"] = $process_webauthn['username'];
  1660. $_SESSION['tfa_id'] = $process_webauthn['id'];
  1661. $_SESSION['authReq'] = null;
  1662. unset($_SESSION["challenge"]);
  1663. $_SESSION['return'][] = array(
  1664. 'type' => 'success',
  1665. 'log' => array("webauthn_login"),
  1666. 'msg' => array('logged_in_as', $process_webauthn['username'])
  1667. );
  1668. return true;
  1669. break;
  1670. default:
  1671. $_SESSION['return'][] = array(
  1672. 'type' => 'danger',
  1673. 'log' => array(__FUNCTION__, $username, '*'),
  1674. 'msg' => 'unknown_tfa_method'
  1675. );
  1676. return false;
  1677. break;
  1678. }
  1679. return false;
  1680. } else {
  1681. // delete old keys that used u2f
  1682. $stmt = $pdo->prepare("SELECT * FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username");
  1683. $stmt->execute(array(':username' => $username));
  1684. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1685. if (count($rows) == 0) return false;
  1686. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username");
  1687. $stmt->execute(array(':username' => $username));
  1688. return true;
  1689. }
  1690. }
  1691. function admin_api($access, $action, $data = null) {
  1692. global $pdo;
  1693. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1694. $_SESSION['return'][] = array(
  1695. 'type' => 'danger',
  1696. 'log' => array(__FUNCTION__),
  1697. 'msg' => 'access_denied'
  1698. );
  1699. return false;
  1700. }
  1701. if ($access !== "ro" && $access !== "rw") {
  1702. $_SESSION['return'][] = array(
  1703. 'type' => 'danger',
  1704. 'log' => array(__FUNCTION__),
  1705. 'msg' => 'invalid access type'
  1706. );
  1707. return false;
  1708. }
  1709. if ($action == "edit") {
  1710. $active = (!empty($data['active'])) ? 1 : 0;
  1711. $skip_ip_check = (isset($data['skip_ip_check'])) ? 1 : 0;
  1712. $allow_from = array();
  1713. if (isset($data['allow_from'])) {
  1714. $allow_from = array_map('trim', preg_split( "/( |,|;|\n)/", $data['allow_from']));
  1715. }
  1716. foreach ($allow_from as $key => $val) {
  1717. if (empty($val)) {
  1718. unset($allow_from[$key]);
  1719. continue;
  1720. }
  1721. if (valid_network($val) !== true) {
  1722. $_SESSION['return'][] = array(
  1723. 'type' => 'warning',
  1724. 'log' => array(__FUNCTION__, $data),
  1725. 'msg' => array('ip_invalid', htmlspecialchars($allow_from[$key]))
  1726. );
  1727. unset($allow_from[$key]);
  1728. continue;
  1729. }
  1730. }
  1731. $allow_from = implode(',', array_unique(array_filter($allow_from)));
  1732. if (empty($allow_from) && $skip_ip_check == 0) {
  1733. $_SESSION['return'][] = array(
  1734. 'type' => 'danger',
  1735. 'log' => array(__FUNCTION__, $data),
  1736. 'msg' => 'ip_list_empty'
  1737. );
  1738. return false;
  1739. }
  1740. $api_key = implode('-', array(
  1741. strtoupper(bin2hex(random_bytes(3))),
  1742. strtoupper(bin2hex(random_bytes(3))),
  1743. strtoupper(bin2hex(random_bytes(3))),
  1744. strtoupper(bin2hex(random_bytes(3))),
  1745. strtoupper(bin2hex(random_bytes(3)))
  1746. ));
  1747. $stmt = $pdo->query("SELECT `api_key` FROM `api` WHERE `access` = '" . $access . "'");
  1748. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  1749. if (empty($num_results)) {
  1750. $stmt = $pdo->prepare("INSERT INTO `api` (`api_key`, `skip_ip_check`, `active`, `allow_from`, `access`)
  1751. VALUES (:api_key, :skip_ip_check, :active, :allow_from, :access);");
  1752. $stmt->execute(array(
  1753. ':api_key' => $api_key,
  1754. ':skip_ip_check' => $skip_ip_check,
  1755. ':active' => $active,
  1756. ':allow_from' => $allow_from,
  1757. ':access' => $access
  1758. ));
  1759. }
  1760. else {
  1761. if ($skip_ip_check == 0) {
  1762. $stmt = $pdo->prepare("UPDATE `api` SET `skip_ip_check` = :skip_ip_check,
  1763. `active` = :active,
  1764. `allow_from` = :allow_from
  1765. WHERE `access` = :access;");
  1766. $stmt->execute(array(
  1767. ':active' => $active,
  1768. ':skip_ip_check' => $skip_ip_check,
  1769. ':allow_from' => $allow_from,
  1770. ':access' => $access
  1771. ));
  1772. }
  1773. else {
  1774. $stmt = $pdo->prepare("UPDATE `api` SET `skip_ip_check` = :skip_ip_check,
  1775. `active` = :active
  1776. WHERE `access` = :access;");
  1777. $stmt->execute(array(
  1778. ':active' => $active,
  1779. ':skip_ip_check' => $skip_ip_check,
  1780. ':access' => $access
  1781. ));
  1782. }
  1783. }
  1784. }
  1785. elseif ($action == "regen_key") {
  1786. $api_key = implode('-', array(
  1787. strtoupper(bin2hex(random_bytes(3))),
  1788. strtoupper(bin2hex(random_bytes(3))),
  1789. strtoupper(bin2hex(random_bytes(3))),
  1790. strtoupper(bin2hex(random_bytes(3))),
  1791. strtoupper(bin2hex(random_bytes(3)))
  1792. ));
  1793. $stmt = $pdo->prepare("UPDATE `api` SET `api_key` = :api_key WHERE `access` = :access");
  1794. $stmt->execute(array(
  1795. ':api_key' => $api_key,
  1796. ':access' => $access
  1797. ));
  1798. }
  1799. elseif ($action == "get") {
  1800. $stmt = $pdo->query("SELECT * FROM `api` WHERE `access` = '" . $access . "'");
  1801. $apidata = $stmt->fetch(PDO::FETCH_ASSOC);
  1802. if ($apidata !== false) {
  1803. $apidata['allow_from'] = str_replace(',', PHP_EOL, $apidata['allow_from']);
  1804. }
  1805. return $apidata;
  1806. }
  1807. $_SESSION['return'][] = array(
  1808. 'type' => 'success',
  1809. 'log' => array(__FUNCTION__, $data),
  1810. 'msg' => 'admin_api_modified'
  1811. );
  1812. }
  1813. function license($action, $data = null) {
  1814. global $pdo;
  1815. global $redis;
  1816. global $lang;
  1817. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1818. $_SESSION['return'][] = array(
  1819. 'type' => 'danger',
  1820. 'log' => array(__FUNCTION__),
  1821. 'msg' => 'access_denied'
  1822. );
  1823. return false;
  1824. }
  1825. switch ($action) {
  1826. case "verify":
  1827. // Keep result until revalidate button is pressed or session expired
  1828. $stmt = $pdo->query("SELECT `version` FROM `versions` WHERE `application` = 'GUID'");
  1829. $versions = $stmt->fetch(PDO::FETCH_ASSOC);
  1830. $post = array('guid' => $versions['version']);
  1831. $curl = curl_init('https://verify.mailcow.email');
  1832. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  1833. curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
  1834. curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
  1835. $response = curl_exec($curl);
  1836. curl_close($curl);
  1837. $json_return = json_decode($response, true);
  1838. if ($response && $json_return) {
  1839. if ($json_return['response'] === "ok") {
  1840. $_SESSION['gal']['valid'] = "true";
  1841. $_SESSION['gal']['c'] = $json_return['c'];
  1842. $_SESSION['gal']['s'] = $json_return['s'];
  1843. if ($json_return['m'] == 'NoMoore') {
  1844. $_SESSION['gal']['m'] = '🐄';
  1845. }
  1846. else {
  1847. $_SESSION['gal']['m'] = str_repeat('🐄', substr_count($json_return['m'], 'o'));
  1848. }
  1849. }
  1850. elseif ($json_return['response'] === "invalid") {
  1851. $_SESSION['gal']['valid'] = "false";
  1852. $_SESSION['gal']['c'] = $lang['mailbox']['no'];
  1853. $_SESSION['gal']['s'] = $lang['mailbox']['no'];
  1854. $_SESSION['gal']['m'] = $lang['mailbox']['no'];
  1855. }
  1856. }
  1857. else {
  1858. $_SESSION['gal']['valid'] = "false";
  1859. $_SESSION['gal']['c'] = $lang['danger']['temp_error'];
  1860. $_SESSION['gal']['s'] = $lang['danger']['temp_error'];
  1861. $_SESSION['gal']['m'] = $lang['danger']['temp_error'];
  1862. }
  1863. try {
  1864. // json_encode needs "true"/"false" instead of true/false, to not encode it to 0 or 1
  1865. $redis->Set('LICENSE_STATUS_CACHE', json_encode($_SESSION['gal']));
  1866. }
  1867. catch (RedisException $e) {
  1868. $_SESSION['return'][] = array(
  1869. 'type' => 'danger',
  1870. 'log' => array(__FUNCTION__, $_action, $_data_log),
  1871. 'msg' => array('redis_error', $e)
  1872. );
  1873. return false;
  1874. }
  1875. return $_SESSION['gal']['valid'];
  1876. break;
  1877. case "guid":
  1878. $stmt = $pdo->query("SELECT `version` FROM `versions` WHERE `application` = 'GUID'");
  1879. $versions = $stmt->fetch(PDO::FETCH_ASSOC);
  1880. return $versions['version'];
  1881. break;
  1882. }
  1883. }
  1884. function rspamd_ui($action, $data = null) {
  1885. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1886. $_SESSION['return'][] = array(
  1887. 'type' => 'danger',
  1888. 'log' => array(__FUNCTION__),
  1889. 'msg' => 'access_denied'
  1890. );
  1891. return false;
  1892. }
  1893. switch ($action) {
  1894. case "edit":
  1895. $rspamd_ui_pass = $data['rspamd_ui_pass'];
  1896. $rspamd_ui_pass2 = $data['rspamd_ui_pass2'];
  1897. if (empty($rspamd_ui_pass) || empty($rspamd_ui_pass2)) {
  1898. $_SESSION['return'][] = array(
  1899. 'type' => 'danger',
  1900. 'log' => array(__FUNCTION__, '*', '*'),
  1901. 'msg' => 'password_empty'
  1902. );
  1903. return false;
  1904. }
  1905. if ($rspamd_ui_pass != $rspamd_ui_pass2) {
  1906. $_SESSION['return'][] = array(
  1907. 'type' => 'danger',
  1908. 'log' => array(__FUNCTION__, '*', '*'),
  1909. 'msg' => 'password_mismatch'
  1910. );
  1911. return false;
  1912. }
  1913. if (strlen($rspamd_ui_pass) < 6) {
  1914. $_SESSION['return'][] = array(
  1915. 'type' => 'danger',
  1916. 'log' => array(__FUNCTION__, '*', '*'),
  1917. 'msg' => 'rspamd_ui_pw_length'
  1918. );
  1919. return false;
  1920. }
  1921. $docker_return = docker('post', 'rspamd-mailcow', 'exec', array('cmd' => 'rspamd', 'task' => 'worker_password', 'raw' => $rspamd_ui_pass), array('Content-Type: application/json'));
  1922. if ($docker_return_array = json_decode($docker_return, true)) {
  1923. if ($docker_return_array['type'] == 'success') {
  1924. $_SESSION['return'][] = array(
  1925. 'type' => 'success',
  1926. 'log' => array(__FUNCTION__, '*', '*'),
  1927. 'msg' => 'rspamd_ui_pw_set'
  1928. );
  1929. return true;
  1930. }
  1931. else {
  1932. $_SESSION['return'][] = array(
  1933. 'type' => $docker_return_array['type'],
  1934. 'log' => array(__FUNCTION__, '*', '*'),
  1935. 'msg' => $docker_return_array['msg']
  1936. );
  1937. return false;
  1938. }
  1939. }
  1940. else {
  1941. $_SESSION['return'][] = array(
  1942. 'type' => 'danger',
  1943. 'log' => array(__FUNCTION__, '*', '*'),
  1944. 'msg' => 'unknown'
  1945. );
  1946. return false;
  1947. }
  1948. break;
  1949. }
  1950. }
  1951. function cors($action, $data = null) {
  1952. global $redis;
  1953. switch ($action) {
  1954. case "edit":
  1955. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1956. $_SESSION['return'][] = array(
  1957. 'type' => 'danger',
  1958. 'log' => array(__FUNCTION__, $action, $data),
  1959. 'msg' => 'access_denied'
  1960. );
  1961. return false;
  1962. }
  1963. $allowed_origins = isset($data['allowed_origins']) ? $data['allowed_origins'] : array($_SERVER['SERVER_NAME']);
  1964. $allowed_origins = !is_array($allowed_origins) ? array_filter(array_map('trim', explode("\n", $allowed_origins))) : $allowed_origins;
  1965. foreach ($allowed_origins as $origin) {
  1966. if (!filter_var($origin, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) && $origin != '*') {
  1967. $_SESSION['return'][] = array(
  1968. 'type' => 'danger',
  1969. 'log' => array(__FUNCTION__, $action, $data),
  1970. 'msg' => 'cors_invalid_origin'
  1971. );
  1972. return false;
  1973. }
  1974. }
  1975. $allowed_methods = isset($data['allowed_methods']) ? $data['allowed_methods'] : array('GET', 'POST', 'PUT', 'DELETE');
  1976. $allowed_methods = !is_array($allowed_methods) ? array_map('trim', preg_split( "/( |,|;|\n)/", $allowed_methods)) : $allowed_methods;
  1977. $available_methods = array('GET', 'POST', 'PUT', 'DELETE');
  1978. foreach ($allowed_methods as $method) {
  1979. if (!in_array($method, $available_methods)) {
  1980. $_SESSION['return'][] = array(
  1981. 'type' => 'danger',
  1982. 'log' => array(__FUNCTION__, $action, $data),
  1983. 'msg' => 'cors_invalid_method'
  1984. );
  1985. return false;
  1986. }
  1987. }
  1988. try {
  1989. $redis->hMSet('CORS_SETTINGS', array(
  1990. 'allowed_origins' => implode(', ', $allowed_origins),
  1991. 'allowed_methods' => implode(', ', $allowed_methods)
  1992. ));
  1993. } catch (RedisException $e) {
  1994. $_SESSION['return'][] = array(
  1995. 'type' => 'danger',
  1996. 'log' => array(__FUNCTION__, $action, $data),
  1997. 'msg' => array('redis_error', $e)
  1998. );
  1999. return false;
  2000. }
  2001. $_SESSION['return'][] = array(
  2002. 'type' => 'success',
  2003. 'log' => array(__FUNCTION__, $action, $data),
  2004. 'msg' => 'cors_headers_edited'
  2005. );
  2006. return true;
  2007. break;
  2008. case "get":
  2009. try {
  2010. $cors_settings = $redis->hMGet('CORS_SETTINGS', array('allowed_origins', 'allowed_methods'));
  2011. } catch (RedisException $e) {
  2012. $_SESSION['return'][] = array(
  2013. 'type' => 'danger',
  2014. 'log' => array(__FUNCTION__, $action, $data),
  2015. 'msg' => array('redis_error', $e)
  2016. );
  2017. }
  2018. $cors_settings = !$cors_settings ? array('allowed_origins' => $_SERVER['SERVER_NAME'], 'allowed_methods' => 'GET, POST, PUT, DELETE') : $cors_settings;
  2019. $cors_settings['allowed_origins'] = empty($cors_settings['allowed_origins']) ? $_SERVER['SERVER_NAME'] : $cors_settings['allowed_origins'];
  2020. $cors_settings['allowed_methods'] = empty($cors_settings['allowed_methods']) ? 'GET, POST, PUT, DELETE, OPTION' : $cors_settings['allowed_methods'];
  2021. return $cors_settings;
  2022. break;
  2023. case "set_headers":
  2024. $cors_settings = cors('get');
  2025. // check if requested origin is in allowed origins
  2026. $allowed_origins = explode(', ', $cors_settings['allowed_origins']);
  2027. $cors_settings['allowed_origins'] = $allowed_origins[0];
  2028. if (in_array('*', $allowed_origins)){
  2029. $cors_settings['allowed_origins'] = '*';
  2030. } else if (in_array($_SERVER['HTTP_ORIGIN'], $allowed_origins)) {
  2031. $cors_settings['allowed_origins'] = $_SERVER['HTTP_ORIGIN'];
  2032. }
  2033. // always allow OPTIONS for preflight request
  2034. $cors_settings["allowed_methods"] = empty($cors_settings["allowed_methods"]) ? 'OPTIONS' : $cors_settings["allowed_methods"] . ', ' . 'OPTIONS';
  2035. header('Access-Control-Allow-Origin: ' . $cors_settings['allowed_origins']);
  2036. header('Access-Control-Allow-Methods: '. $cors_settings['allowed_methods']);
  2037. header('Access-Control-Allow-Headers: Accept, Content-Type, X-Api-Key, Origin');
  2038. // Access-Control settings requested, this is just a preflight request
  2039. if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS' &&
  2040. isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']) &&
  2041. isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
  2042. $allowed_methods = explode(', ', $cors_settings["allowed_methods"]);
  2043. if (in_array($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'], $allowed_methods, true))
  2044. // method allowed send 200 OK
  2045. http_response_code(200);
  2046. else
  2047. // method not allowed send 405 METHOD NOT ALLOWED
  2048. http_response_code(405);
  2049. exit;
  2050. }
  2051. break;
  2052. }
  2053. }
  2054. function getBaseURL() {
  2055. $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
  2056. $host = $_SERVER['HTTP_HOST'];
  2057. $base_url = $protocol . '://' . $host;
  2058. return $base_url;
  2059. }
  2060. function uuid4() {
  2061. $data = openssl_random_pseudo_bytes(16);
  2062. $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
  2063. $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
  2064. return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
  2065. }
  2066. function identity_provider($_action = null, $_data = null, $_extra = null) {
  2067. global $pdo;
  2068. global $iam_provider;
  2069. global $iam_settings;
  2070. $data_log = $_data;
  2071. if (isset($data_log['client_secret'])) $data_log['client_secret'] = '*';
  2072. if (isset($data_log['access_token'])) $data_log['access_token'] = '*';
  2073. switch ($_action) {
  2074. case 'get':
  2075. $settings = array();
  2076. $stmt = $pdo->prepare("SELECT * FROM `identity_provider`;");
  2077. $stmt->execute();
  2078. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2079. foreach($rows as $row){
  2080. switch ($row["key"]) {
  2081. case "mappers":
  2082. case "templates":
  2083. $settings[$row["key"]] = json_decode($row["value"]);
  2084. break;
  2085. case "use_ssl":
  2086. case "use_tls":
  2087. case "ignore_ssl_errors":
  2088. $settings[$row["key"]] = boolval($row["value"]);
  2089. break;
  2090. default:
  2091. $settings[$row["key"]] = $row["value"];
  2092. break;
  2093. }
  2094. }
  2095. // return default client_scopes for generic-oidc if none is set
  2096. if ($settings["authsource"] == "generic-oidc" && empty($settings["client_scopes"])){
  2097. $settings["client_scopes"] = "openid profile email";
  2098. }
  2099. if ($_extra['hide_sensitive']){
  2100. $settings['client_secret'] = '';
  2101. $settings['access_token'] = '';
  2102. }
  2103. // return default ldap options
  2104. if ($settings["authsource"] == "ldap"){
  2105. $settings['use_ssl'] = !isset($settings['use_ssl']) ? false : $settings['use_ssl'];
  2106. $settings['use_tls'] = !isset($settings['use_tls']) ? false : $settings['use_tls'];
  2107. $settings['ignore_ssl_errors'] = !isset($settings['ignore_ssl_errors']) ? false : $settings['ignore_ssl_errors'];
  2108. }
  2109. return $settings;
  2110. break;
  2111. case 'edit':
  2112. if ($_SESSION['mailcow_cc_role'] != "admin") {
  2113. $_SESSION['return'][] = array(
  2114. 'type' => 'danger',
  2115. 'log' => array(__FUNCTION__, $_action, $_data),
  2116. 'msg' => 'access_denied'
  2117. );
  2118. return false;
  2119. }
  2120. if (!isset($_data['authsource'])){
  2121. $_SESSION['return'][] = array(
  2122. 'type' => 'danger',
  2123. 'log' => array(__FUNCTION__, $_action, $data_log),
  2124. 'msg' => array('required_data_missing', '')
  2125. );
  2126. return false;
  2127. }
  2128. $available_authsources = array(
  2129. "keycloak",
  2130. "generic-oidc",
  2131. "ldap"
  2132. );
  2133. $_data['authsource'] = strtolower($_data['authsource']);
  2134. if (!in_array($_data['authsource'], $available_authsources)){
  2135. $_SESSION['return'][] = array(
  2136. 'type' => 'danger',
  2137. 'log' => array(__FUNCTION__, $_action, $data_log),
  2138. 'msg' => array('invalid_authsource', $setting)
  2139. );
  2140. return false;
  2141. }
  2142. $stmt = $pdo->prepare("SELECT * FROM `mailbox`
  2143. WHERE `authsource` != 'mailcow'
  2144. AND `authsource` IS NOT NULL
  2145. AND `authsource` != :authsource");
  2146. $stmt->execute(array(':authsource' => $_data['authsource']));
  2147. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2148. if ($rows) {
  2149. $_SESSION['return'][] = array(
  2150. 'type' => 'danger',
  2151. 'log' => array(__FUNCTION__, $_action, $data_log),
  2152. 'msg' => array('authsource_in_use', $setting)
  2153. );
  2154. return false;
  2155. }
  2156. $_data['ignore_ssl_error'] = isset($_data['ignore_ssl_error']) ? boolval($_data['ignore_ssl_error']) : false;
  2157. switch ($_data['authsource']) {
  2158. case "keycloak":
  2159. $_data['server_url'] = (!empty($_data['server_url'])) ? rtrim($_data['server_url'], '/') : null;
  2160. $_data['mailpassword_flow'] = isset($_data['mailpassword_flow']) ? intval($_data['mailpassword_flow']) : 0;
  2161. $_data['periodic_sync'] = isset($_data['periodic_sync']) ? intval($_data['periodic_sync']) : 0;
  2162. $_data['import_users'] = isset($_data['import_users']) ? intval($_data['import_users']) : 0;
  2163. $_data['sync_interval'] = (!empty($_data['sync_interval'])) ? intval($_data['sync_interval']) : 15;
  2164. $_data['sync_interval'] = $_data['sync_interval'] < 1 ? 1 : $_data['sync_interval'];
  2165. $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');
  2166. break;
  2167. case "generic-oidc":
  2168. $_data['authorize_url'] = (!empty($_data['authorize_url'])) ? $_data['authorize_url'] : null;
  2169. $_data['token_url'] = (!empty($_data['token_url'])) ? $_data['token_url'] : null;
  2170. $_data['userinfo_url'] = (!empty($_data['userinfo_url'])) ? $_data['userinfo_url'] : null;
  2171. $_data['client_scopes'] = (!empty($_data['client_scopes'])) ? $_data['client_scopes'] : "openid profile email";
  2172. $required_settings = array('authsource', 'authorize_url', 'token_url', 'client_id', 'client_secret', 'redirect_url', 'userinfo_url', 'client_scopes', 'ignore_ssl_error');
  2173. break;
  2174. case "ldap":
  2175. $_data['host'] = (!empty($_data['host'])) ? str_replace(" ", "", $_data['host']) : "";
  2176. $_data['port'] = (!empty($_data['port'])) ? intval($_data['port']) : 389;
  2177. $_data['username_field'] = (!empty($_data['username_field'])) ? strtolower($_data['username_field']) : "mail";
  2178. $_data['attribute_field'] = (!empty($_data['attribute_field'])) ? strtolower($_data['attribute_field']) : "";
  2179. $_data['filter'] = (!empty($_data['filter'])) ? $_data['filter'] : "";
  2180. $_data['periodic_sync'] = isset($_data['periodic_sync']) ? intval($_data['periodic_sync']) : 0;
  2181. $_data['import_users'] = isset($_data['import_users']) ? intval($_data['import_users']) : 0;
  2182. $_data['use_ssl'] = isset($_data['use_ssl']) ? boolval($_data['use_ssl']) : false;
  2183. $_data['use_tls'] = isset($_data['use_tls']) && !$_data['use_ssl'] ? boolval($_data['use_tls']) : false;
  2184. $_data['sync_interval'] = (!empty($_data['sync_interval'])) ? intval($_data['sync_interval']) : 15;
  2185. $_data['sync_interval'] = $_data['sync_interval'] < 1 ? 1 : $_data['sync_interval'];
  2186. $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');
  2187. break;
  2188. }
  2189. $pdo->beginTransaction();
  2190. $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES (:key, :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
  2191. // add connection settings
  2192. foreach($required_settings as $setting){
  2193. if (!isset($_data[$setting])){
  2194. $_SESSION['return'][] = array(
  2195. 'type' => 'danger',
  2196. 'log' => array(__FUNCTION__, $_action, $data_log),
  2197. 'msg' => array('required_data_missing', $setting)
  2198. );
  2199. $pdo->rollback();
  2200. return false;
  2201. }
  2202. $stmt->bindParam(':key', $setting);
  2203. $stmt->bindParam(':value', $_data[$setting]);
  2204. $stmt->execute();
  2205. }
  2206. $pdo->commit();
  2207. // add mappers
  2208. if ($_data['mappers'] && $_data['templates']){
  2209. $_data['mappers'] = (!is_array($_data['mappers'])) ? array($_data['mappers']) : $_data['mappers'];
  2210. $_data['templates'] = (!is_array($_data['templates'])) ? array($_data['templates']) : $_data['templates'];
  2211. $mappers = array_filter($_data['mappers']);
  2212. $templates = array_filter($_data['templates']);
  2213. if (count($mappers) == count($templates)){
  2214. $mappers = json_encode($mappers);
  2215. $templates = json_encode($templates);
  2216. $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES ('mappers', :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
  2217. $stmt->bindParam(':value', $mappers);
  2218. $stmt->execute();
  2219. $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES ('templates', :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
  2220. $stmt->bindParam(':value', $templates);
  2221. $stmt->execute();
  2222. }
  2223. }
  2224. // delete old access_token
  2225. $stmt = $pdo->query("INSERT INTO identity_provider (`key`, `value`) VALUES ('access_token', '') ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
  2226. $_SESSION['return'][] = array(
  2227. 'type' => 'success',
  2228. 'log' => array(__FUNCTION__, $_action, $data_log),
  2229. 'msg' => array('object_modified', '')
  2230. );
  2231. return true;
  2232. break;
  2233. case 'test':
  2234. if ($_SESSION['mailcow_cc_role'] != "admin") {
  2235. $_SESSION['return'][] = array(
  2236. 'type' => 'danger',
  2237. 'log' => array(__FUNCTION__, $_action, $_data),
  2238. 'msg' => 'access_denied'
  2239. );
  2240. return false;
  2241. }
  2242. switch ($_data['authsource']) {
  2243. case 'keycloak':
  2244. $url = "{$_data['server_url']}/realms/{$_data['realm']}/protocol/openid-connect/token";
  2245. $req = http_build_query(array(
  2246. 'grant_type' => 'client_credentials',
  2247. 'client_id' => $_data['client_id'],
  2248. 'client_secret' => $_data['client_secret']
  2249. ));
  2250. $curl = curl_init();
  2251. curl_setopt($curl, CURLOPT_URL, $url);
  2252. curl_setopt($curl, CURLOPT_TIMEOUT, 7);
  2253. curl_setopt($curl, CURLOPT_POST, 1);
  2254. curl_setopt($curl, CURLOPT_POSTFIELDS, $req);
  2255. curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
  2256. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2257. if ($_data['ignore_ssl_error'] == "1"){
  2258. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  2259. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
  2260. }
  2261. $res = curl_exec($curl);
  2262. $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  2263. curl_close ($curl);
  2264. if ($code != 200) {
  2265. return false;
  2266. }
  2267. break;
  2268. case 'generic-oidc':
  2269. $url = $_data['token_url'];
  2270. $curl = curl_init();
  2271. curl_setopt($curl, CURLOPT_URL, $url);
  2272. curl_setopt($curl, CURLOPT_TIMEOUT, 7);
  2273. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2274. curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "OPTIONS");
  2275. if ($_data['ignore_ssl_error'] == "1"){
  2276. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  2277. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
  2278. }
  2279. $res = curl_exec($curl);
  2280. $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  2281. curl_close ($curl);
  2282. if ($code != 200) {
  2283. return false;
  2284. }
  2285. break;
  2286. case 'ldap':
  2287. if (!$_data['host'] || !$_data['port'] || !$_data['basedn'] ||
  2288. !$_data['binddn'] || !$_data['bindpass']){
  2289. return false;
  2290. }
  2291. $_data['use_ssl'] = isset($_data['use_ssl']) ? boolval($_data['use_ssl']) : false;
  2292. $_data['use_tls'] = isset($_data['use_tls']) && !$_data['use_ssl'] ? boolval($_data['use_tls']) : false;
  2293. $_data['ignore_ssl_error'] = isset($_data['ignore_ssl_error']) ? boolval($_data['ignore_ssl_error']) : false;
  2294. $options = array();
  2295. if ($_data['ignore_ssl_error']) {
  2296. $options[LDAP_OPT_X_TLS_REQUIRE_CERT] = LDAP_OPT_X_TLS_NEVER;
  2297. }
  2298. $provider = new \LdapRecord\Connection([
  2299. 'hosts' => explode(",", $_data['host']),
  2300. 'port' => $_data['port'],
  2301. 'base_dn' => $_data['basedn'],
  2302. 'username' => $_data['binddn'],
  2303. 'password' => $_data['bindpass'],
  2304. 'use_ssl' => $_data['use_ssl'],
  2305. 'use_tls' => $_data['use_tls'],
  2306. 'options' => $options
  2307. ]);
  2308. try {
  2309. $provider->connect();
  2310. } catch (Throwable $e) {
  2311. return false;
  2312. }
  2313. break;
  2314. }
  2315. return true;
  2316. break;
  2317. case "delete":
  2318. if ($_SESSION['mailcow_cc_role'] != "admin") {
  2319. $_SESSION['return'][] = array(
  2320. 'type' => 'danger',
  2321. 'log' => array(__FUNCTION__, $_action, $_data),
  2322. 'msg' => 'access_denied'
  2323. );
  2324. return false;
  2325. }
  2326. $stmt = $pdo->query("SELECT * FROM `mailbox`
  2327. WHERE `authsource` != 'mailcow'
  2328. AND `authsource` IS NOT NULL");
  2329. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2330. if ($rows) {
  2331. $_SESSION['return'][] = array(
  2332. 'type' => 'danger',
  2333. 'log' => array(__FUNCTION__, $_action, $data_log),
  2334. 'msg' => array('authsource_in_use', $setting)
  2335. );
  2336. return false;
  2337. }
  2338. $stmt = $pdo->query("DELETE FROM identity_provider;");
  2339. $_SESSION['return'][] = array(
  2340. 'type' => 'success',
  2341. 'log' => array(__FUNCTION__, $_action, $data_log),
  2342. 'msg' => array('item_deleted', '')
  2343. );
  2344. return true;
  2345. break;
  2346. case "init":
  2347. $settings = identity_provider('get');
  2348. $provider = null;
  2349. switch ($settings['authsource']) {
  2350. case "keycloak":
  2351. if ($settings['server_url'] && $settings['realm'] && $settings['client_id'] &&
  2352. $settings['client_secret'] && $settings['redirect_url'] && $settings['version']){
  2353. $guzzyClient = new GuzzleHttp\Client([
  2354. 'defaults' => [
  2355. \GuzzleHttp\RequestOptions::CONNECT_TIMEOUT => 5,
  2356. \GuzzleHttp\RequestOptions::ALLOW_REDIRECTS => true],
  2357. \GuzzleHttp\RequestOptions::VERIFY => !$settings['ignore_ssl_error'],
  2358. ]
  2359. );
  2360. $provider = new Stevenmaguire\OAuth2\Client\Provider\Keycloak([
  2361. 'authServerUrl' => $settings['server_url'],
  2362. 'realm' => $settings['realm'],
  2363. 'clientId' => $settings['client_id'],
  2364. 'clientSecret' => $settings['client_secret'],
  2365. 'redirectUri' => $settings['redirect_url'],
  2366. 'version' => $settings['version'],
  2367. // 'encryptionAlgorithm' => 'RS256', // optional
  2368. // 'encryptionKeyPath' => '../key.pem' // optional
  2369. // 'encryptionKey' => 'contents_of_key_or_certificate' // optional
  2370. ]);
  2371. $provider->setHttpClient($guzzyClient);
  2372. }
  2373. break;
  2374. case "generic-oidc":
  2375. if ($settings['client_id'] && $settings['client_secret'] && $settings['redirect_url'] &&
  2376. $settings['authorize_url'] && $settings['token_url'] && $settings['userinfo_url']){
  2377. $guzzyClient = new GuzzleHttp\Client([
  2378. 'defaults' => [
  2379. \GuzzleHttp\RequestOptions::CONNECT_TIMEOUT => 5,
  2380. \GuzzleHttp\RequestOptions::ALLOW_REDIRECTS => true],
  2381. \GuzzleHttp\RequestOptions::VERIFY => !$settings['ignore_ssl_error'],
  2382. ]
  2383. );
  2384. $provider = new \League\OAuth2\Client\Provider\GenericProvider([
  2385. 'clientId' => $settings['client_id'],
  2386. 'clientSecret' => $settings['client_secret'],
  2387. 'redirectUri' => $settings['redirect_url'],
  2388. 'urlAuthorize' => $settings['authorize_url'],
  2389. 'urlAccessToken' => $settings['token_url'],
  2390. 'urlResourceOwnerDetails' => $settings['userinfo_url'],
  2391. 'scopes' => $settings['client_scopes']
  2392. ]);
  2393. $provider->setHttpClient($guzzyClient);
  2394. }
  2395. break;
  2396. case "ldap":
  2397. if ($settings['host'] && $settings['port'] && $settings['basedn'] &&
  2398. $settings['binddn'] && $settings['bindpass']){
  2399. $options = array();
  2400. if ($settings['ignore_ssl_error']) {
  2401. $options[LDAP_OPT_X_TLS_REQUIRE_CERT] = LDAP_OPT_X_TLS_NEVER;
  2402. }
  2403. $provider = new \LdapRecord\Connection([
  2404. 'hosts' => explode(",", $settings['host']),
  2405. 'port' => $settings['port'],
  2406. 'base_dn' => $settings['basedn'],
  2407. 'username' => $settings['binddn'],
  2408. 'password' => $settings['bindpass'],
  2409. 'use_ssl' => $settings['use_ssl'],
  2410. 'use_tls' => $settings['use_tls'],
  2411. 'options' => $options
  2412. ]);
  2413. try {
  2414. $provider->connect();
  2415. } catch (Throwable $e) {
  2416. $provider = null;
  2417. }
  2418. }
  2419. break;
  2420. }
  2421. return $provider;
  2422. break;
  2423. case "verify-sso":
  2424. if ($iam_settings['authsource'] != 'keycloak' && $iam_settings['authsource'] != 'generic-oidc'){
  2425. $_SESSION['return'][] = array(
  2426. 'type' => 'danger',
  2427. 'log' => array(__FUNCTION__),
  2428. 'msg' => array('login_failed', "no OIDC provider configured")
  2429. );
  2430. return false;
  2431. }
  2432. try {
  2433. $token = $iam_provider->getAccessToken('authorization_code', ['code' => $_GET['code']]);
  2434. $plain_token = $token->getToken();
  2435. $plain_refreshtoken = $token->getRefreshToken();
  2436. $info = $iam_provider->getResourceOwner($token)->toArray();
  2437. } catch (Throwable $e) {
  2438. $_SESSION['return'][] = array(
  2439. 'type' => 'danger',
  2440. 'log' => array(__FUNCTION__),
  2441. 'msg' => array('login_failed', $e->getMessage())
  2442. );
  2443. return false;
  2444. }
  2445. // check if email address is given
  2446. if (empty($info['email'])) return false;
  2447. // get mapped template
  2448. $user_template = $info['mailcow_template'];
  2449. $mapper_key = array_search($user_template, $iam_settings['mappers']);
  2450. // token valid, get mailbox
  2451. $stmt = $pdo->prepare("SELECT * FROM `mailbox`
  2452. INNER JOIN domain on mailbox.domain = domain.domain
  2453. WHERE `kind` NOT REGEXP 'location|thing|group'
  2454. AND `mailbox`.`active`='1'
  2455. AND `domain`.`active`='1'
  2456. AND `username` = :user
  2457. AND (`authsource`='keycloak' OR `authsource`='generic-oidc')");
  2458. $stmt->execute(array(':user' => $info['email']));
  2459. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  2460. if ($row){
  2461. // success
  2462. if ($mapper_key !== false) {
  2463. // update user
  2464. $_SESSION['access_all_exception'] = '1';
  2465. mailbox('edit', 'mailbox_from_template', array(
  2466. 'username' => $info['email'],
  2467. 'name' => $info['name'],
  2468. 'template' => $iam_settings['templates'][$mapper_key]
  2469. ));
  2470. $_SESSION['access_all_exception'] = '0';
  2471. }
  2472. set_user_loggedin_session($info['email']);
  2473. $_SESSION['iam_token'] = $plain_token;
  2474. $_SESSION['iam_refresh_token'] = $plain_refreshtoken;
  2475. $_SESSION['return'][] = array(
  2476. 'type' => 'success',
  2477. 'log' => array(__FUNCTION__, $_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role']),
  2478. 'msg' => array('logged_in_as', $_SESSION['mailcow_cc_username'])
  2479. );
  2480. return true;
  2481. }
  2482. if (empty($iam_settings['mappers']) || empty($user_template)){
  2483. clear_session();
  2484. $_SESSION['return'][] = array(
  2485. 'type' => 'danger',
  2486. 'log' => array(__FUNCTION__, $info['email']),
  2487. 'msg' => array('login_failed', 'empty attribute mapping or missing template attribute')
  2488. );
  2489. return false;
  2490. }
  2491. if ($mapper_key === false) {
  2492. clear_session();
  2493. $_SESSION['return'][] = array(
  2494. 'type' => 'danger',
  2495. 'log' => array(__FUNCTION__, $info['email']),
  2496. 'msg' => array('login_failed', 'specified template not found')
  2497. );
  2498. return false;
  2499. }
  2500. // create mailbox
  2501. $_SESSION['access_all_exception'] = '1';
  2502. $create_res = mailbox('add', 'mailbox_from_template', array(
  2503. 'domain' => explode('@', $info['email'])[1],
  2504. 'local_part' => explode('@', $info['email'])[0],
  2505. 'name' => $info['name'],
  2506. 'authsource' => $iam_settings['authsource'],
  2507. 'template' => $iam_settings['templates'][$mapper_key]
  2508. ));
  2509. $_SESSION['access_all_exception'] = '0';
  2510. if (!$create_res){
  2511. clear_session();
  2512. $_SESSION['return'][] = array(
  2513. 'type' => 'danger',
  2514. 'log' => array(__FUNCTION__, $info['email']),
  2515. 'msg' => array('login_failed', 'mailbox creation failed')
  2516. );
  2517. return false;
  2518. }
  2519. set_user_loggedin_session($info['email']);
  2520. $_SESSION['iam_token'] = $plain_token;
  2521. $_SESSION['iam_refresh_token'] = $plain_refreshtoken;
  2522. $_SESSION['return'][] = array(
  2523. 'type' => 'success',
  2524. 'log' => array(__FUNCTION__, $_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role']),
  2525. 'msg' => array('logged_in_as', $_SESSION['mailcow_cc_username'])
  2526. );
  2527. return true;
  2528. break;
  2529. case "refresh-token":
  2530. try {
  2531. $token = $iam_provider->getAccessToken('refresh_token', ['refresh_token' => $_SESSION['iam_refresh_token']]);
  2532. $plain_token = $token->getToken();
  2533. $plain_refreshtoken = $token->getRefreshToken();
  2534. $info = $iam_provider->getResourceOwner($token)->toArray();
  2535. } catch (Throwable $e) {
  2536. clear_session();
  2537. $_SESSION['return'][] = array(
  2538. 'type' => 'danger',
  2539. 'log' => array(__FUNCTION__),
  2540. 'msg' => array('refresh_login_failed', $e->getMessage())
  2541. );
  2542. return false;
  2543. }
  2544. if (empty($info['email'])){
  2545. clear_session();
  2546. $_SESSION['return'][] = array(
  2547. 'type' => 'danger',
  2548. 'log' => array(__FUNCTION__, $_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role']),
  2549. 'msg' => 'refresh_login_failed'
  2550. );
  2551. return false;
  2552. }
  2553. set_user_loggedin_session($info['email']);
  2554. $_SESSION['iam_token'] = $plain_token;
  2555. $_SESSION['iam_refresh_token'] = $plain_refreshtoken;
  2556. return true;
  2557. break;
  2558. case "get-redirect":
  2559. if ($iam_settings['authsource'] != 'keycloak' && $iam_settings['authsource'] != 'generic-oidc')
  2560. return false;
  2561. $authUrl = $iam_provider->getAuthorizationUrl();
  2562. $_SESSION['oauth2state'] = $iam_provider->getState();
  2563. return $authUrl;
  2564. break;
  2565. case "get-keycloak-admin-token":
  2566. // get access_token for service account of mailcow client
  2567. if ($iam_settings['authsource'] !== 'keycloak') return false;
  2568. if (isset($iam_settings['access_token'])) {
  2569. // check if access_token is valid
  2570. $url = "{$iam_settings['server_url']}/realms/{$iam_settings['realm']}/protocol/openid-connect/token/introspect";
  2571. $req = http_build_query(array(
  2572. 'token' => $iam_settings['access_token'],
  2573. 'client_id' => $iam_settings['client_id'],
  2574. 'client_secret' => $iam_settings['client_secret']
  2575. ));
  2576. $curl = curl_init();
  2577. curl_setopt($curl, CURLOPT_URL, $url);
  2578. curl_setopt($curl, CURLOPT_TIMEOUT, 7);
  2579. curl_setopt($curl, CURLOPT_POST, 1);
  2580. curl_setopt($curl, CURLOPT_POSTFIELDS, $req);
  2581. curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
  2582. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2583. curl_setopt($curl, CURLOPT_TIMEOUT, 5);
  2584. $res = json_decode(curl_exec($curl), true);
  2585. $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  2586. curl_close ($curl);
  2587. if ($code == 200 && $res['active'] == true) {
  2588. // token is valid
  2589. return $iam_settings['access_token'];
  2590. }
  2591. }
  2592. $url = "{$iam_settings['server_url']}/realms/{$iam_settings['realm']}/protocol/openid-connect/token";
  2593. $req = http_build_query(array(
  2594. 'grant_type' => 'client_credentials',
  2595. 'client_id' => $iam_settings['client_id'],
  2596. 'client_secret' => $iam_settings['client_secret']
  2597. ));
  2598. $curl = curl_init();
  2599. curl_setopt($curl, CURLOPT_URL, $url);
  2600. curl_setopt($curl, CURLOPT_TIMEOUT, 7);
  2601. curl_setopt($curl, CURLOPT_POST, 1);
  2602. curl_setopt($curl, CURLOPT_POSTFIELDS, $req);
  2603. curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
  2604. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2605. curl_setopt($curl, CURLOPT_TIMEOUT, 5);
  2606. $res = json_decode(curl_exec($curl), true);
  2607. $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  2608. curl_close ($curl);
  2609. if ($code != 200) {
  2610. return false;
  2611. }
  2612. $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES (:key, :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
  2613. $stmt->execute(array(
  2614. ':key' => 'access_token',
  2615. ':value' => $res['access_token']
  2616. ));
  2617. return $res['access_token'];
  2618. break;
  2619. }
  2620. }
  2621. function reset_password($action, $data = null) {
  2622. global $pdo;
  2623. global $redis;
  2624. global $mailcow_hostname;
  2625. global $PW_RESET_TOKEN_LIMIT;
  2626. global $PW_RESET_TOKEN_LIFETIME;
  2627. $_data_log = $data;
  2628. if (isset($_data_log['new_password'])) $_data_log['new_password'] = '*';
  2629. if (isset($_data_log['new_password2'])) $_data_log['new_password2'] = '*';
  2630. switch ($action) {
  2631. case 'check':
  2632. $token = $data;
  2633. $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';");
  2634. $stmt->execute(array(
  2635. ':token' => preg_replace('/[^a-zA-Z0-9-]/', '', $token),
  2636. ':lifetime' => $PW_RESET_TOKEN_LIFETIME
  2637. ));
  2638. $return = $stmt->fetch(PDO::FETCH_ASSOC);
  2639. return empty($return['username']) ? false : $return['username'];
  2640. break;
  2641. case 'issue':
  2642. $username = $data;
  2643. // perform cleanup
  2644. $stmt = $pdo->prepare("DELETE FROM `reset_password` WHERE created < DATE_SUB(NOW(), INTERVAL :lifetime MINUTE);");
  2645. $stmt->execute(array(':lifetime' => $PW_RESET_TOKEN_LIFETIME));
  2646. if (filter_var($username, FILTER_VALIDATE_EMAIL) === false) {
  2647. $_SESSION['return'][] = array(
  2648. 'type' => 'danger',
  2649. 'log' => array(__FUNCTION__, $action, $_data_log),
  2650. 'msg' => 'access_denied'
  2651. );
  2652. return false;
  2653. }
  2654. $pw_reset_notification = reset_password('get_notification', 'raw');
  2655. if (!$pw_reset_notification) return false;
  2656. if (empty($pw_reset_notification['from']) || empty($pw_reset_notification['subject'])) {
  2657. $_SESSION['return'][] = array(
  2658. 'type' => 'danger',
  2659. 'log' => array(__FUNCTION__, $action, $_data_log),
  2660. 'msg' => 'password_reset_na'
  2661. );
  2662. return false;
  2663. }
  2664. $stmt = $pdo->prepare("SELECT * FROM `mailbox`
  2665. WHERE `username` = :username AND authsource = 'mailcow'");
  2666. $stmt->execute(array(':username' => $username));
  2667. $mailbox_data = $stmt->fetch(PDO::FETCH_ASSOC);
  2668. if (empty($mailbox_data)) {
  2669. $_SESSION['return'][] = array(
  2670. 'type' => 'danger',
  2671. 'log' => array(__FUNCTION__, $action, $_data_log),
  2672. 'msg' => 'password_reset_invalid_user'
  2673. );
  2674. return false;
  2675. }
  2676. $mailbox_attr = json_decode($mailbox_data['attributes'], true);
  2677. if (empty($mailbox_attr['recovery_email']) || filter_var($mailbox_attr['recovery_email'], FILTER_VALIDATE_EMAIL) === false) {
  2678. $_SESSION['return'][] = array(
  2679. 'type' => 'danger',
  2680. 'log' => array(__FUNCTION__, $action, $_data_log),
  2681. 'msg' => "password_reset_invalid_user"
  2682. );
  2683. return false;
  2684. }
  2685. $stmt = $pdo->prepare("SELECT * FROM `reset_password`
  2686. WHERE `username` = :username");
  2687. $stmt->execute(array(':username' => $username));
  2688. $generated_token_count = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  2689. if ($generated_token_count >= $PW_RESET_TOKEN_LIMIT) {
  2690. $_SESSION['return'][] = array(
  2691. 'type' => 'danger',
  2692. 'log' => array(__FUNCTION__, $action, $_data_log),
  2693. 'msg' => "reset_token_limit_exceeded"
  2694. );
  2695. return false;
  2696. }
  2697. $token = implode('-', array(
  2698. strtoupper(bin2hex(random_bytes(3))),
  2699. strtoupper(bin2hex(random_bytes(3))),
  2700. strtoupper(bin2hex(random_bytes(3))),
  2701. strtoupper(bin2hex(random_bytes(3))),
  2702. strtoupper(bin2hex(random_bytes(3)))
  2703. ));
  2704. $stmt = $pdo->prepare("INSERT INTO `reset_password` (`username`, `token`)
  2705. VALUES (:username, :token)");
  2706. $stmt->execute(array(
  2707. ':username' => $username,
  2708. ':token' => $token
  2709. ));
  2710. $reset_link = getBaseURL() . "/reset-password?token=" . $token;
  2711. $request_date = new DateTime();
  2712. $locale_date = locale_get_default();
  2713. $date_formatter = new IntlDateFormatter(
  2714. $locale_date,
  2715. IntlDateFormatter::FULL,
  2716. IntlDateFormatter::FULL
  2717. );
  2718. $formatted_request_date = $date_formatter->format($request_date);
  2719. // set template vars
  2720. // subject
  2721. $pw_reset_notification['subject'] = str_replace('{{hostname}}', $mailcow_hostname, $pw_reset_notification['subject']);
  2722. $pw_reset_notification['subject'] = str_replace('{{link}}', $reset_link, $pw_reset_notification['subject']);
  2723. $pw_reset_notification['subject'] = str_replace('{{username}}', $username, $pw_reset_notification['subject']);
  2724. $pw_reset_notification['subject'] = str_replace('{{username2}}', $mailbox_attr['recovery_email'], $pw_reset_notification['subject']);
  2725. $pw_reset_notification['subject'] = str_replace('{{date}}', $formatted_request_date, $pw_reset_notification['subject']);
  2726. $pw_reset_notification['subject'] = str_replace('{{token_lifetime}}', $PW_RESET_TOKEN_LIFETIME, $pw_reset_notification['subject']);
  2727. // text
  2728. $pw_reset_notification['text_tmpl'] = str_replace('{{hostname}}', $mailcow_hostname, $pw_reset_notification['text_tmpl']);
  2729. $pw_reset_notification['text_tmpl'] = str_replace('{{link}}', $reset_link, $pw_reset_notification['text_tmpl']);
  2730. $pw_reset_notification['text_tmpl'] = str_replace('{{username}}', $username, $pw_reset_notification['text_tmpl']);
  2731. $pw_reset_notification['text_tmpl'] = str_replace('{{username2}}', $mailbox_attr['recovery_email'], $pw_reset_notification['text_tmpl']);
  2732. $pw_reset_notification['text_tmpl'] = str_replace('{{date}}', $formatted_request_date, $pw_reset_notification['text_tmpl']);
  2733. $pw_reset_notification['text_tmpl'] = str_replace('{{token_lifetime}}', $PW_RESET_TOKEN_LIFETIME, $pw_reset_notification['text_tmpl']);
  2734. // html
  2735. $pw_reset_notification['html_tmpl'] = str_replace('{{hostname}}', $mailcow_hostname, $pw_reset_notification['html_tmpl']);
  2736. $pw_reset_notification['html_tmpl'] = str_replace('{{link}}', $reset_link, $pw_reset_notification['html_tmpl']);
  2737. $pw_reset_notification['html_tmpl'] = str_replace('{{username}}', $username, $pw_reset_notification['html_tmpl']);
  2738. $pw_reset_notification['html_tmpl'] = str_replace('{{username2}}', $mailbox_attr['recovery_email'], $pw_reset_notification['html_tmpl']);
  2739. $pw_reset_notification['html_tmpl'] = str_replace('{{date}}', $formatted_request_date, $pw_reset_notification['html_tmpl']);
  2740. $pw_reset_notification['html_tmpl'] = str_replace('{{token_lifetime}}', $PW_RESET_TOKEN_LIFETIME, $pw_reset_notification['html_tmpl']);
  2741. $email_sent = reset_password('send_mail', array(
  2742. "from" => $pw_reset_notification['from'],
  2743. "to" => $mailbox_attr['recovery_email'],
  2744. "subject" => $pw_reset_notification['subject'],
  2745. "text" => $pw_reset_notification['text_tmpl'],
  2746. "html" => $pw_reset_notification['html_tmpl']
  2747. ));
  2748. if (!$email_sent){
  2749. $_SESSION['return'][] = array(
  2750. 'type' => 'danger',
  2751. 'log' => array(__FUNCTION__, $action, $_data_log),
  2752. 'msg' => "recovery_email_failed"
  2753. );
  2754. return false;
  2755. }
  2756. list($localPart, $domainPart) = explode('@', $mailbox_attr['recovery_email']);
  2757. if (strlen($localPart) > 1) {
  2758. $maskedLocalPart = $localPart[0] . str_repeat('*', strlen($localPart) - 1);
  2759. } else {
  2760. $maskedLocalPart = "*";
  2761. }
  2762. $_SESSION['return'][] = array(
  2763. 'type' => 'success',
  2764. 'log' => array(__FUNCTION__, $action, $_data_log),
  2765. 'msg' => array("recovery_email_sent", $maskedLocalPart . '@' . $domainPart)
  2766. );
  2767. return array(
  2768. "username" => $username,
  2769. "issue" => "success"
  2770. );
  2771. break;
  2772. case 'reset':
  2773. $token = $data['token'];
  2774. $new_password = $data['new_password'];
  2775. $new_password2 = $data['new_password2'];
  2776. $username = $data['username'];
  2777. $check_tfa = $data['check_tfa'];
  2778. if (!$username || !$token) {
  2779. $_SESSION['return'][] = array(
  2780. 'type' => 'danger',
  2781. 'log' => array(__FUNCTION__, $action, $_data_log),
  2782. 'msg' => 'invalid_reset_token'
  2783. );
  2784. return false;
  2785. }
  2786. # check new password
  2787. if (!password_check($new_password, $new_password2)) {
  2788. return false;
  2789. }
  2790. if ($check_tfa){
  2791. // check for tfa authenticators
  2792. $authenticators = get_tfa($username);
  2793. if (isset($authenticators['additional']) && is_array($authenticators['additional']) && count($authenticators['additional']) > 0) {
  2794. $_SESSION['pending_mailcow_cc_username'] = $username;
  2795. $_SESSION['pending_pw_reset_token'] = $token;
  2796. $_SESSION['pending_pw_new_password'] = $new_password;
  2797. $_SESSION['pending_tfa_methods'] = $authenticators['additional'];
  2798. $_SESSION['return'][] = array(
  2799. 'type' => 'info',
  2800. 'log' => array(__FUNCTION__, $user, '*'),
  2801. 'msg' => 'awaiting_tfa_confirmation'
  2802. );
  2803. return false;
  2804. }
  2805. }
  2806. # set new password
  2807. $password_hashed = hash_password($new_password);
  2808. $stmt = $pdo->prepare("UPDATE `mailbox` SET
  2809. `password` = :password_hashed,
  2810. `attributes` = JSON_SET(`attributes`, '$.passwd_update', NOW())
  2811. WHERE `username` = :username AND authsource = 'mailcow'");
  2812. $stmt->execute(array(
  2813. ':password_hashed' => $password_hashed,
  2814. ':username' => $username
  2815. ));
  2816. // perform cleanup
  2817. $stmt = $pdo->prepare("DELETE FROM `reset_password` WHERE `username` = :username;");
  2818. $stmt->execute(array(
  2819. ':username' => $username
  2820. ));
  2821. update_sogo_static_view($username);
  2822. $_SESSION['return'][] = array(
  2823. 'type' => 'success',
  2824. 'log' => array(__FUNCTION__, $action, $_data_log),
  2825. 'msg' => 'password_changed_success'
  2826. );
  2827. return true;
  2828. break;
  2829. case 'get_notification':
  2830. $type = $data;
  2831. try {
  2832. $settings['from'] = $redis->Get('PW_RESET_FROM');
  2833. $settings['subject'] = $redis->Get('PW_RESET_SUBJ');
  2834. $settings['html_tmpl'] = $redis->Get('PW_RESET_HTML');
  2835. $settings['text_tmpl'] = $redis->Get('PW_RESET_TEXT');
  2836. if (empty($settings['html_tmpl']) && empty($settings['text_tmpl'])) {
  2837. $settings['html_tmpl'] = file_get_contents("/tpls/pw_reset_html.tpl");
  2838. $settings['text_tmpl'] = file_get_contents("/tpls/pw_reset_text.tpl");
  2839. }
  2840. if ($type != "raw") {
  2841. $settings['html_tmpl'] = htmlspecialchars($settings['html_tmpl']);
  2842. $settings['text_tmpl'] = htmlspecialchars($settings['text_tmpl']);
  2843. }
  2844. }
  2845. catch (RedisException $e) {
  2846. $_SESSION['return'][] = array(
  2847. 'type' => 'danger',
  2848. 'log' => array(__FUNCTION__, $action, $_data_log),
  2849. 'msg' => array('redis_error', $e)
  2850. );
  2851. return false;
  2852. }
  2853. return $settings;
  2854. break;
  2855. case 'send_mail':
  2856. $from = $data['from'];
  2857. $to = $data['to'];
  2858. $text = $data['text'];
  2859. $html = $data['html'];
  2860. $subject = $data['subject'];
  2861. if (!filter_var($from, FILTER_VALIDATE_EMAIL)) {
  2862. $_SESSION['return'][] = array(
  2863. 'type' => 'danger',
  2864. 'log' => array(__FUNCTION__, $action, $_data_log),
  2865. 'msg' => 'from_invalid'
  2866. );
  2867. return false;
  2868. }
  2869. if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
  2870. $_SESSION['return'][] = array(
  2871. 'type' => 'danger',
  2872. 'log' => array(__FUNCTION__, $action, $_data_log),
  2873. 'msg' => 'to_invalid'
  2874. );
  2875. return false;
  2876. }
  2877. if (empty($subject)) {
  2878. $_SESSION['return'][] = array(
  2879. 'type' => 'danger',
  2880. 'log' => array(__FUNCTION__, $action, $_data_log),
  2881. 'msg' => 'subject_empty'
  2882. );
  2883. return false;
  2884. }
  2885. if (empty($text)) {
  2886. $_SESSION['return'][] = array(
  2887. 'type' => 'danger',
  2888. 'log' => array(__FUNCTION__, $action, $_data_log),
  2889. 'msg' => 'text_empty'
  2890. );
  2891. return false;
  2892. }
  2893. ini_set('max_execution_time', 0);
  2894. ini_set('max_input_time', 0);
  2895. $mail = new PHPMailer;
  2896. $mail->Timeout = 10;
  2897. $mail->SMTPOptions = array(
  2898. 'ssl' => array(
  2899. 'verify_peer' => false,
  2900. 'verify_peer_name' => false,
  2901. 'allow_self_signed' => true
  2902. )
  2903. );
  2904. $mail->isSMTP();
  2905. $mail->Host = 'postfix-mailcow';
  2906. $mail->SMTPAuth = false;
  2907. $mail->Port = 25;
  2908. $mail->setFrom($from);
  2909. $mail->Subject = $subject;
  2910. $mail->CharSet ="UTF-8";
  2911. if (!empty($html)) {
  2912. $mail->Body = $html;
  2913. $mail->AltBody = $text;
  2914. }
  2915. else {
  2916. $mail->Body = $text;
  2917. }
  2918. $mail->XMailer = 'MooMail';
  2919. $mail->AddAddress($to);
  2920. if (!$mail->send()) {
  2921. return false;
  2922. }
  2923. $mail->ClearAllRecipients();
  2924. return true;
  2925. break;
  2926. }
  2927. if ($_SESSION['mailcow_cc_role'] != "admin") {
  2928. $_SESSION['return'][] = array(
  2929. 'type' => 'danger',
  2930. 'log' => array(__FUNCTION__, $action, $_data_log),
  2931. 'msg' => 'access_denied'
  2932. );
  2933. return false;
  2934. }
  2935. switch ($action) {
  2936. case 'edit_notification':
  2937. $subject = $data['subject'];
  2938. $from = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $data['from']);
  2939. $from = (!filter_var($from, FILTER_VALIDATE_EMAIL)) ? "" : $from;
  2940. $subject = (empty($subject)) ? "" : $subject;
  2941. $text = (empty($data['text_tmpl'])) ? "" : $data['text_tmpl'];
  2942. $html = (empty($data['html_tmpl'])) ? "" : $data['html_tmpl'];
  2943. try {
  2944. $redis->Set('PW_RESET_FROM', $from);
  2945. $redis->Set('PW_RESET_SUBJ', $subject);
  2946. $redis->Set('PW_RESET_HTML', $html);
  2947. $redis->Set('PW_RESET_TEXT', $text);
  2948. }
  2949. catch (RedisException $e) {
  2950. $_SESSION['return'][] = array(
  2951. 'type' => 'danger',
  2952. 'log' => array(__FUNCTION__, $action, $_data_log),
  2953. 'msg' => array('redis_error', $e)
  2954. );
  2955. return false;
  2956. }
  2957. $_SESSION['return'][] = array(
  2958. 'type' => 'success',
  2959. 'log' => array(__FUNCTION__, $action, $_data_log),
  2960. 'msg' => 'saved_settings'
  2961. );
  2962. break;
  2963. }
  2964. }
  2965. function clear_session(){
  2966. session_regenerate_id(true);
  2967. session_unset();
  2968. session_destroy();
  2969. session_write_close();
  2970. }
  2971. function set_user_loggedin_session($user) {
  2972. session_regenerate_id(true);
  2973. $_SESSION['mailcow_cc_username'] = $user;
  2974. $_SESSION['mailcow_cc_role'] = 'user';
  2975. $sogo_sso_pass = file_get_contents("/etc/sogo-sso/sogo-sso.pass");
  2976. $_SESSION['sogo-sso-user-allowed'][] = $user;
  2977. $_SESSION['sogo-sso-pass'] = $sogo_sso_pass;
  2978. unset($_SESSION['pending_mailcow_cc_username']);
  2979. unset($_SESSION['pending_mailcow_cc_role']);
  2980. unset($_SESSION['pending_tfa_methods']);
  2981. }
  2982. function get_logs($application, $lines = false) {
  2983. if ($lines === false) {
  2984. $lines = $GLOBALS['LOG_LINES'] - 1;
  2985. }
  2986. elseif(is_numeric($lines) && $lines >= 1) {
  2987. $lines = abs(intval($lines) - 1);
  2988. }
  2989. else {
  2990. list ($from, $to) = explode('-', $lines);
  2991. $from = intval($from);
  2992. $to = intval($to);
  2993. if ($from < 1 || $to < $from) { return false; }
  2994. }
  2995. global $redis;
  2996. global $pdo;
  2997. if ($_SESSION['mailcow_cc_role'] != "admin") {
  2998. return false;
  2999. }
  3000. // SQL
  3001. if ($application == "mailcow-ui") {
  3002. if (isset($from) && isset($to)) {
  3003. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :from, :to");
  3004. $stmt->execute(array(
  3005. ':from' => $from - 1,
  3006. ':to' => $to
  3007. ));
  3008. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  3009. }
  3010. else {
  3011. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :lines");
  3012. $stmt->execute(array(
  3013. ':lines' => $lines + 1,
  3014. ));
  3015. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  3016. }
  3017. if (is_array($data)) {
  3018. return $data;
  3019. }
  3020. }
  3021. if ($application == "sasl") {
  3022. if (isset($from) && isset($to)) {
  3023. $stmt = $pdo->prepare("SELECT * FROM `sasl_log` ORDER BY `datetime` DESC LIMIT :from, :to");
  3024. $stmt->execute(array(
  3025. ':from' => $from - 1,
  3026. ':to' => $to
  3027. ));
  3028. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  3029. }
  3030. else {
  3031. $stmt = $pdo->prepare("SELECT * FROM `sasl_log` ORDER BY `datetime` DESC LIMIT :lines");
  3032. $stmt->execute(array(
  3033. ':lines' => $lines + 1,
  3034. ));
  3035. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  3036. }
  3037. if (is_array($data)) {
  3038. return $data;
  3039. }
  3040. }
  3041. // Redis
  3042. if ($application == "dovecot-mailcow") {
  3043. if (isset($from) && isset($to)) {
  3044. $data = $redis->lRange('DOVECOT_MAILLOG', $from - 1, $to - 1);
  3045. }
  3046. else {
  3047. $data = $redis->lRange('DOVECOT_MAILLOG', 0, $lines);
  3048. }
  3049. if ($data) {
  3050. foreach ($data as $json_line) {
  3051. $data_array[] = json_decode($json_line, true);
  3052. }
  3053. return $data_array;
  3054. }
  3055. }
  3056. if ($application == "cron-mailcow") {
  3057. if (isset($from) && isset($to)) {
  3058. $data = $redis->lRange('CRON_LOG', $from - 1, $to - 1);
  3059. }
  3060. else {
  3061. $data = $redis->lRange('CRON_LOG', 0, $lines);
  3062. }
  3063. if ($data) {
  3064. foreach ($data as $json_line) {
  3065. $data_array[] = json_decode($json_line, true);
  3066. }
  3067. return $data_array;
  3068. }
  3069. }
  3070. if ($application == "postfix-mailcow") {
  3071. if (isset($from) && isset($to)) {
  3072. $data = $redis->lRange('POSTFIX_MAILLOG', $from - 1, $to - 1);
  3073. }
  3074. else {
  3075. $data = $redis->lRange('POSTFIX_MAILLOG', 0, $lines);
  3076. }
  3077. if ($data) {
  3078. foreach ($data as $json_line) {
  3079. $data_array[] = json_decode($json_line, true);
  3080. }
  3081. return $data_array;
  3082. }
  3083. }
  3084. if ($application == "sogo-mailcow") {
  3085. if (isset($from) && isset($to)) {
  3086. $data = $redis->lRange('SOGO_LOG', $from - 1, $to - 1);
  3087. }
  3088. else {
  3089. $data = $redis->lRange('SOGO_LOG', 0, $lines);
  3090. }
  3091. if ($data) {
  3092. foreach ($data as $json_line) {
  3093. $data_array[] = json_decode($json_line, true);
  3094. }
  3095. return $data_array;
  3096. }
  3097. }
  3098. if ($application == "watchdog-mailcow") {
  3099. if (isset($from) && isset($to)) {
  3100. $data = $redis->lRange('WATCHDOG_LOG', $from - 1, $to - 1);
  3101. }
  3102. else {
  3103. $data = $redis->lRange('WATCHDOG_LOG', 0, $lines);
  3104. }
  3105. if ($data) {
  3106. foreach ($data as $json_line) {
  3107. $data_array[] = json_decode($json_line, true);
  3108. }
  3109. return $data_array;
  3110. }
  3111. }
  3112. if ($application == "acme-mailcow") {
  3113. if (isset($from) && isset($to)) {
  3114. $data = $redis->lRange('ACME_LOG', $from - 1, $to - 1);
  3115. }
  3116. else {
  3117. $data = $redis->lRange('ACME_LOG', 0, $lines);
  3118. }
  3119. if ($data) {
  3120. foreach ($data as $json_line) {
  3121. $data_array[] = json_decode($json_line, true);
  3122. }
  3123. return $data_array;
  3124. }
  3125. }
  3126. if ($application == "ratelimited") {
  3127. if (isset($from) && isset($to)) {
  3128. $data = $redis->lRange('RL_LOG', $from - 1, $to - 1);
  3129. }
  3130. else {
  3131. $data = $redis->lRange('RL_LOG', 0, $lines);
  3132. }
  3133. if ($data) {
  3134. foreach ($data as $json_line) {
  3135. $data_array[] = json_decode($json_line, true);
  3136. }
  3137. return $data_array;
  3138. }
  3139. }
  3140. if ($application == "api-mailcow") {
  3141. if (isset($from) && isset($to)) {
  3142. $data = $redis->lRange('API_LOG', $from - 1, $to - 1);
  3143. }
  3144. else {
  3145. $data = $redis->lRange('API_LOG', 0, $lines);
  3146. }
  3147. if ($data) {
  3148. foreach ($data as $json_line) {
  3149. $data_array[] = json_decode($json_line, true);
  3150. }
  3151. return $data_array;
  3152. }
  3153. }
  3154. if ($application == "netfilter-mailcow") {
  3155. if (isset($from) && isset($to)) {
  3156. $data = $redis->lRange('NETFILTER_LOG', $from - 1, $to - 1);
  3157. }
  3158. else {
  3159. $data = $redis->lRange('NETFILTER_LOG', 0, $lines);
  3160. }
  3161. if ($data) {
  3162. foreach ($data as $json_line) {
  3163. $data_array[] = json_decode($json_line, true);
  3164. }
  3165. return $data_array;
  3166. }
  3167. }
  3168. if ($application == "autodiscover-mailcow") {
  3169. if (isset($from) && isset($to)) {
  3170. $data = $redis->lRange('AUTODISCOVER_LOG', $from - 1, $to - 1);
  3171. }
  3172. else {
  3173. $data = $redis->lRange('AUTODISCOVER_LOG', 0, $lines);
  3174. }
  3175. if ($data) {
  3176. foreach ($data as $json_line) {
  3177. $data_array[] = json_decode($json_line, true);
  3178. }
  3179. return $data_array;
  3180. }
  3181. }
  3182. if ($application == "rspamd-history") {
  3183. $curl = curl_init();
  3184. curl_setopt($curl, CURLOPT_UNIX_SOCKET_PATH, '/var/lib/rspamd/rspamd.sock');
  3185. if (!is_numeric($lines)) {
  3186. list ($from, $to) = explode('-', $lines);
  3187. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?from=" . intval($from) . "&to=" . intval($to));
  3188. }
  3189. else {
  3190. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?to=" . intval($lines));
  3191. }
  3192. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  3193. $history = curl_exec($curl);
  3194. if (!curl_errno($curl)) {
  3195. $data_array = json_decode($history, true);
  3196. curl_close($curl);
  3197. return $data_array['rows'];
  3198. }
  3199. curl_close($curl);
  3200. return false;
  3201. }
  3202. if ($application == "rspamd-stats") {
  3203. $curl = curl_init();
  3204. curl_setopt($curl, CURLOPT_UNIX_SOCKET_PATH, '/var/lib/rspamd/rspamd.sock');
  3205. curl_setopt($curl, CURLOPT_URL,"http://rspamd/stat");
  3206. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  3207. $stats = curl_exec($curl);
  3208. if (!curl_errno($curl)) {
  3209. $data_array = json_decode($stats, true);
  3210. curl_close($curl);
  3211. return $data_array;
  3212. }
  3213. curl_close($curl);
  3214. return false;
  3215. }
  3216. return false;
  3217. }
  3218. function getGUID() {
  3219. if (function_exists('com_create_guid')) {
  3220. return com_create_guid();
  3221. }
  3222. mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
  3223. $charid = strtoupper(md5(uniqid(rand(), true)));
  3224. $hyphen = chr(45);// "-"
  3225. return substr($charid, 0, 8).$hyphen
  3226. .substr($charid, 8, 4).$hyphen
  3227. .substr($charid,12, 4).$hyphen
  3228. .substr($charid,16, 4).$hyphen
  3229. .substr($charid,20,12);
  3230. }
  3231. function cleanupJS($ignore = '', $folder = '/tmp/*.js') {
  3232. $now = time();
  3233. foreach (glob($folder) as $filename) {
  3234. if(strpos($filename, $ignore) !== false) {
  3235. continue;
  3236. }
  3237. if (is_file($filename)) {
  3238. if ($now - filemtime($filename) >= 60 * 60) {
  3239. unlink($filename);
  3240. }
  3241. }
  3242. }
  3243. }
  3244. function cleanupCSS($ignore = '', $folder = '/tmp/*.css') {
  3245. $now = time();
  3246. foreach (glob($folder) as $filename) {
  3247. if(strpos($filename, $ignore) !== false) {
  3248. continue;
  3249. }
  3250. if (is_file($filename)) {
  3251. if ($now - filemtime($filename) >= 60 * 60) {
  3252. unlink($filename);
  3253. }
  3254. }
  3255. }
  3256. }
  3257. ?>