functions.inc.php 126 KB

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