functions.inc.php 131 KB

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