functions.inc.php 136 KB

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