functions.inc.php 136 KB

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