functions.inc.php 137 KB

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