functions.inc.php 138 KB

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