functions.inc.php 136 KB

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