functions.inc.php 134 KB

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