functions.inc.php 111 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989
  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 (!filter_var($username, FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $username))) {
  532. return false;
  533. }
  534. if (empty($domain) || !is_valid_domain_name($domain)) {
  535. return false;
  536. }
  537. if ($role != 'admin' && $role != 'domainadmin') {
  538. return false;
  539. }
  540. if ($role == 'admin') {
  541. $stmt = $pdo->prepare("SELECT `domain` FROM `domain`
  542. WHERE `domain` = :domain");
  543. $stmt->execute(array(':domain' => $domain));
  544. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  545. $stmt = $pdo->prepare("SELECT `alias_domain` FROM `alias_domain`
  546. WHERE `alias_domain` = :domain");
  547. $stmt->execute(array(':domain' => $domain));
  548. $num_results = $num_results + count($stmt->fetchAll(PDO::FETCH_ASSOC));
  549. if ($num_results != 0) {
  550. return true;
  551. }
  552. }
  553. elseif ($role == 'domainadmin') {
  554. $stmt = $pdo->prepare("SELECT `domain` FROM `domain_admins`
  555. WHERE (
  556. `active`='1'
  557. AND `username` = :username
  558. AND (`domain` = :domain1 OR `domain` = (SELECT `target_domain` FROM `alias_domain` WHERE `alias_domain` = :domain2))
  559. )");
  560. $stmt->execute(array(':username' => $username, ':domain1' => $domain, ':domain2' => $domain));
  561. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  562. if (!empty($num_results)) {
  563. return true;
  564. }
  565. }
  566. return false;
  567. }
  568. function hasMailboxObjectAccess($username, $role, $object) {
  569. global $pdo;
  570. if (empty($username) || empty($role) || empty($object)) {
  571. return false;
  572. }
  573. if (!filter_var(html_entity_decode(rawurldecode($username)), FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $username))) {
  574. return false;
  575. }
  576. if ($role != 'admin' && $role != 'domainadmin' && $role != 'user') {
  577. return false;
  578. }
  579. if ($username == $object) {
  580. return true;
  581. }
  582. $stmt = $pdo->prepare("SELECT `domain` FROM `mailbox` WHERE `username` = :object");
  583. $stmt->execute(array(':object' => $object));
  584. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  585. if (isset($row['domain']) && hasDomainAccess($username, $role, $row['domain'])) {
  586. return true;
  587. }
  588. return false;
  589. }
  590. // does also verify mailboxes as a mailbox is a alias == goto
  591. function hasAliasObjectAccess($username, $role, $object) {
  592. global $pdo;
  593. if (empty($username) || empty($role) || empty($object)) {
  594. return false;
  595. }
  596. if (!filter_var(html_entity_decode(rawurldecode($username)), FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $username))) {
  597. return false;
  598. }
  599. if ($role != 'admin' && $role != 'domainadmin' && $role != 'user') {
  600. return false;
  601. }
  602. $stmt = $pdo->prepare("SELECT `domain` FROM `alias` WHERE `address` = :object");
  603. $stmt->execute(array(':object' => $object));
  604. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  605. if (isset($row['domain']) && hasDomainAccess($username, $role, $row['domain'])) {
  606. return true;
  607. }
  608. return false;
  609. }
  610. function pem_to_der($pem_key) {
  611. // Need to remove BEGIN/END PUBLIC KEY
  612. $lines = explode("\n", trim($pem_key));
  613. unset($lines[count($lines)-1]);
  614. unset($lines[0]);
  615. return base64_decode(implode('', $lines));
  616. }
  617. function expand_ipv6($ip) {
  618. $hex = unpack("H*hex", inet_pton($ip));
  619. $ip = substr(preg_replace("/([A-f0-9]{4})/", "$1:", $hex['hex']), 0, -1);
  620. return $ip;
  621. }
  622. function generate_tlsa_digest($hostname, $port, $starttls = null) {
  623. if (!is_valid_domain_name($hostname)) {
  624. return "Not a valid hostname";
  625. }
  626. if (empty($starttls)) {
  627. $context = stream_context_create(array("ssl" => array("capture_peer_cert" => true, 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true)));
  628. $stream = stream_socket_client('ssl://' . $hostname . ':' . $port, $error_nr, $error_msg, 5, STREAM_CLIENT_CONNECT, $context);
  629. if (!$stream) {
  630. $error_msg = isset($error_msg) ? $error_msg : '-';
  631. return $error_nr . ': ' . $error_msg;
  632. }
  633. }
  634. else {
  635. $stream = stream_socket_client('tcp://' . $hostname . ':' . $port, $error_nr, $error_msg, 5);
  636. if (!$stream) {
  637. return $error_nr . ': ' . $error_msg;
  638. }
  639. $banner = fread($stream, 512 );
  640. if (preg_match("/^220/i", $banner)) { // SMTP
  641. fwrite($stream,"HELO tlsa.generator.local\r\n");
  642. fread($stream, 512);
  643. fwrite($stream,"STARTTLS\r\n");
  644. fread($stream, 512);
  645. }
  646. elseif (preg_match("/imap.+starttls/i", $banner)) { // IMAP
  647. fwrite($stream,"A1 STARTTLS\r\n");
  648. fread($stream, 512);
  649. }
  650. elseif (preg_match("/^\+OK/", $banner)) { // POP3
  651. fwrite($stream,"STLS\r\n");
  652. fread($stream, 512);
  653. }
  654. elseif (preg_match("/^OK/m", $banner)) { // Sieve
  655. fwrite($stream,"STARTTLS\r\n");
  656. fread($stream, 512);
  657. }
  658. else {
  659. return 'Unknown banner: "' . htmlspecialchars(trim($banner)) . '"';
  660. }
  661. // Upgrade connection
  662. stream_set_blocking($stream, true);
  663. stream_context_set_option($stream, 'ssl', 'capture_peer_cert', true);
  664. stream_context_set_option($stream, 'ssl', 'verify_peer', false);
  665. stream_context_set_option($stream, 'ssl', 'verify_peer_name', false);
  666. stream_context_set_option($stream, 'ssl', 'allow_self_signed', true);
  667. stream_socket_enable_crypto($stream, true, STREAM_CRYPTO_METHOD_ANY_CLIENT);
  668. stream_set_blocking($stream, false);
  669. }
  670. $params = stream_context_get_params($stream);
  671. if (!empty($params['options']['ssl']['peer_certificate'])) {
  672. $key_resource = openssl_pkey_get_public($params['options']['ssl']['peer_certificate']);
  673. // We cannot get ['rsa']['n'], the binary data would contain BEGIN/END PUBLIC KEY
  674. $key_data = openssl_pkey_get_details($key_resource)['key'];
  675. return '3 1 1 ' . openssl_digest(pem_to_der($key_data), 'sha256');
  676. }
  677. else {
  678. return 'Error: Cannot read peer certificate';
  679. }
  680. }
  681. function alertbox_log_parser($_data) {
  682. global $lang;
  683. if (isset($_data['return'])) {
  684. foreach ($_data['return'] as $return) {
  685. // Get type
  686. $type = $return['type'];
  687. // If a lang[type][msg] string exists, use it as message
  688. if (isset($return['type']) && isset($return['msg']) && !is_array($return['msg'])) {
  689. if (isset($lang[$return['type']][$return['msg']])) {
  690. $msg = $lang[$return['type']][$return['msg']];
  691. }
  692. else {
  693. $msg = $return['msg'];
  694. }
  695. }
  696. // If msg is an array, use first element as language string and run printf on it with remaining array elements
  697. elseif (is_array($return['msg'])) {
  698. $msg = array_shift($return['msg']);
  699. $msg = vsprintf(
  700. $lang[$return['type']][$msg],
  701. $return['msg']
  702. );
  703. }
  704. else {
  705. $msg = '-';
  706. }
  707. $log_array[] = array('msg' => $msg, 'type' => json_encode($type));
  708. }
  709. if (!empty($log_array)) {
  710. return $log_array;
  711. }
  712. }
  713. return false;
  714. }
  715. function verify_salted_hash($hash, $password, $algo, $salt_length) {
  716. // Decode hash
  717. $dhash = base64_decode($hash);
  718. // Get first n bytes of binary which equals a SSHA hash
  719. $ohash = substr($dhash, 0, $salt_length);
  720. // Remove SSHA hash from decoded hash to get original salt string
  721. $osalt = str_replace($ohash, '', $dhash);
  722. // Check single salted SSHA hash against extracted hash
  723. if (hash_equals(hash($algo, $password . $osalt, true), $ohash)) {
  724. return true;
  725. }
  726. return false;
  727. }
  728. function verify_hash($hash, $password) {
  729. if (preg_match('/^{(.+)}(.+)/i', $hash, $hash_array)) {
  730. $scheme = strtoupper($hash_array[1]);
  731. $hash = $hash_array[2];
  732. switch ($scheme) {
  733. case "ARGON2I":
  734. case "ARGON2ID":
  735. case "BLF-CRYPT":
  736. case "CRYPT":
  737. case "DES-CRYPT":
  738. case "MD5-CRYPT":
  739. case "MD5":
  740. case "SHA256-CRYPT":
  741. case "SHA512-CRYPT":
  742. return password_verify($password, $hash);
  743. case "CLEAR":
  744. case "CLEARTEXT":
  745. case "PLAIN":
  746. return $password == $hash;
  747. case "LDAP-MD5":
  748. $hash = base64_decode($hash);
  749. return hash_equals(hash('md5', $password, true), $hash);
  750. case "PBKDF2":
  751. $components = explode('$', $hash);
  752. $salt = $components[2];
  753. $rounds = $components[3];
  754. $hash = $components[4];
  755. return hash_equals(hash_pbkdf2('sha1', $password, $salt, $rounds), $hash);
  756. case "PLAIN-MD4":
  757. return hash_equals(hash('md4', $password), $hash);
  758. case "PLAIN-MD5":
  759. return md5($password) == $hash;
  760. case "PLAIN-TRUNC":
  761. $components = explode('-', $hash);
  762. if (count($components) > 1) {
  763. $trunc_len = $components[0];
  764. $trunc_password = $components[1];
  765. return substr($password, 0, $trunc_len) == $trunc_password;
  766. } else {
  767. return $password == $hash;
  768. }
  769. case "SHA":
  770. case "SHA1":
  771. case "SHA256":
  772. case "SHA512":
  773. // SHA is an alias for SHA1
  774. $scheme = $scheme == "SHA" ? "sha1" : strtolower($scheme);
  775. $hash = base64_decode($hash);
  776. return hash_equals(hash($scheme, $password, true), $hash);
  777. case "SMD5":
  778. return verify_salted_hash($hash, $password, 'md5', 16);
  779. case "SSHA":
  780. return verify_salted_hash($hash, $password, 'sha1', 20);
  781. case "SSHA256":
  782. return verify_salted_hash($hash, $password, 'sha256', 32);
  783. case "SSHA512":
  784. return verify_salted_hash($hash, $password, 'sha512', 64);
  785. default:
  786. return false;
  787. }
  788. }
  789. return false;
  790. }
  791. function formatBytes($size, $precision = 2) {
  792. if(!is_numeric($size)) {
  793. return "0";
  794. }
  795. $base = log($size, 1024);
  796. $suffixes = array(' Byte', ' KiB', ' MiB', ' GiB', ' TiB');
  797. if ($size == "0") {
  798. return "0";
  799. }
  800. return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
  801. }
  802. function update_sogo_static_view($mailbox = null) {
  803. if (getenv('SKIP_SOGO') == "y") {
  804. return true;
  805. }
  806. global $pdo;
  807. global $lang;
  808. $mailbox_exists = false;
  809. if ($mailbox !== null) {
  810. // Check if the mailbox exists
  811. $stmt = $pdo->prepare("SELECT username FROM mailbox WHERE username = :mailbox AND active = '1'");
  812. $stmt->execute(array(':mailbox' => $mailbox));
  813. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  814. if ($row){
  815. $mailbox_exists = true;
  816. }
  817. }
  818. // generate random password for sogo to deny direct login
  819. $random_password = base64_encode(openssl_random_pseudo_bytes(24));
  820. $random_salt = base64_encode(openssl_random_pseudo_bytes(16));
  821. $random_hash = '{SSHA256}' . base64_encode(hash('sha256', base64_decode($password) . $salt, true) . $salt);
  822. $subquery = "GROUP BY mailbox.username";
  823. if ($mailbox_exists) {
  824. $subquery = "AND mailbox.username = :mailbox";
  825. }
  826. $query = "INSERT INTO _sogo_static_view (`c_uid`, `domain`, `c_name`, `c_password`, `c_cn`, `mail`, `aliases`, `ad_aliases`, `ext_acl`, `kind`, `multiple_bookings`)
  827. SELECT
  828. mailbox.username,
  829. mailbox.domain,
  830. mailbox.username,
  831. :random_hash,
  832. mailbox.name,
  833. mailbox.username,
  834. IFNULL(GROUP_CONCAT(ga.aliases ORDER BY ga.aliases SEPARATOR ' '), ''),
  835. IFNULL(gda.ad_alias, ''),
  836. IFNULL(external_acl.send_as_acl, ''),
  837. mailbox.kind,
  838. mailbox.multiple_bookings
  839. FROM
  840. mailbox
  841. LEFT OUTER JOIN grouped_mail_aliases ga ON ga.username REGEXP CONCAT('(^|,)', mailbox.username, '($|,)')
  842. LEFT OUTER JOIN grouped_domain_alias_address gda ON gda.username = mailbox.username
  843. LEFT OUTER JOIN grouped_sender_acl_external external_acl ON external_acl.username = mailbox.username
  844. WHERE
  845. mailbox.active = '1'
  846. $subquery
  847. ON DUPLICATE KEY UPDATE
  848. `domain` = VALUES(`domain`),
  849. `c_name` = VALUES(`c_name`),
  850. `c_password` = VALUES(`c_password`),
  851. `c_cn` = VALUES(`c_cn`),
  852. `mail` = VALUES(`mail`),
  853. `aliases` = VALUES(`aliases`),
  854. `ad_aliases` = VALUES(`ad_aliases`),
  855. `ext_acl` = VALUES(`ext_acl`),
  856. `kind` = VALUES(`kind`),
  857. `multiple_bookings` = VALUES(`multiple_bookings`)";
  858. if ($mailbox_exists) {
  859. $stmt = $pdo->prepare($query);
  860. $stmt->execute(array(
  861. ':random_hash' => $random_hash,
  862. ':mailbox' => $mailbox
  863. ));
  864. } else {
  865. $stmt = $pdo->prepare($query);
  866. $stmt->execute(array(
  867. ':random_hash' => $random_hash
  868. ));
  869. }
  870. $stmt = $pdo->query("DELETE FROM _sogo_static_view WHERE `c_uid` NOT IN (SELECT `username` FROM `mailbox` WHERE `active` = '1');");
  871. flush_memcached();
  872. }
  873. function edit_user_account($_data) {
  874. global $lang;
  875. global $pdo;
  876. $_data_log = $_data;
  877. !isset($_data_log['user_new_pass']) ?: $_data_log['user_new_pass'] = '*';
  878. !isset($_data_log['user_new_pass2']) ?: $_data_log['user_new_pass2'] = '*';
  879. !isset($_data_log['user_old_pass']) ?: $_data_log['user_old_pass'] = '*';
  880. $username = $_SESSION['mailcow_cc_username'];
  881. $role = $_SESSION['mailcow_cc_role'];
  882. $password_old = $_data['user_old_pass'];
  883. if (filter_var($username, FILTER_VALIDATE_EMAIL === false) || $role != 'user') {
  884. $_SESSION['return'][] = array(
  885. 'type' => 'danger',
  886. 'log' => array(__FUNCTION__, $_data_log),
  887. 'msg' => 'access_denied'
  888. );
  889. return false;
  890. }
  891. $stmt = $pdo->prepare("SELECT `password` FROM `mailbox`
  892. WHERE `kind` NOT REGEXP 'location|thing|group'
  893. AND `username` = :user AND authsource = 'mailcow'");
  894. $stmt->execute(array(':user' => $username));
  895. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  896. if (!verify_hash($row['password'], $password_old)) {
  897. $_SESSION['return'][] = array(
  898. 'type' => 'danger',
  899. 'log' => array(__FUNCTION__, $_data_log),
  900. 'msg' => 'access_denied'
  901. );
  902. return false;
  903. }
  904. if (!empty($_data['user_new_pass']) && !empty($_data['user_new_pass2'])) {
  905. $password_new = $_data['user_new_pass'];
  906. $password_new2 = $_data['user_new_pass2'];
  907. if (password_check($password_new, $password_new2) !== true) {
  908. return false;
  909. }
  910. $password_hashed = hash_password($password_new);
  911. $stmt = $pdo->prepare("UPDATE `mailbox` SET `password` = :password_hashed,
  912. `attributes` = JSON_SET(`attributes`, '$.force_pw_update', '0'),
  913. `attributes` = JSON_SET(`attributes`, '$.passwd_update', NOW())
  914. WHERE `username` = :username AND authsource = 'mailcow'");
  915. $stmt->execute(array(
  916. ':password_hashed' => $password_hashed,
  917. ':username' => $username
  918. ));
  919. }
  920. update_sogo_static_view();
  921. $_SESSION['return'][] = array(
  922. 'type' => 'success',
  923. 'log' => array(__FUNCTION__, $_data_log),
  924. 'msg' => array('mailbox_modified', htmlspecialchars($username))
  925. );
  926. }
  927. function user_get_alias_details($username) {
  928. global $pdo;
  929. global $lang;
  930. $data['direct_aliases'] = array();
  931. $data['shared_aliases'] = array();
  932. if ($_SESSION['mailcow_cc_role'] == "user") {
  933. $username = $_SESSION['mailcow_cc_username'];
  934. }
  935. if (!filter_var($username, FILTER_VALIDATE_EMAIL)) {
  936. return false;
  937. }
  938. if (!hasMailboxObjectAccess($username, $_SESSION['mailcow_cc_role'], $username)) {
  939. return false;
  940. }
  941. $data['address'] = $username;
  942. $stmt = $pdo->prepare("SELECT `address` AS `shared_aliases`, `public_comment` FROM `alias`
  943. WHERE `goto` REGEXP :username_goto
  944. AND `address` NOT LIKE '@%'
  945. AND `goto` != :username_goto2
  946. AND `address` != :username_address");
  947. $stmt->execute(array(
  948. ':username_goto' => '(^|,)'.$username.'($|,)',
  949. ':username_goto2' => $username,
  950. ':username_address' => $username
  951. ));
  952. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  953. while ($row = array_shift($run)) {
  954. $data['shared_aliases'][$row['shared_aliases']]['public_comment'] = htmlspecialchars($row['public_comment']);
  955. //$data['shared_aliases'][] = $row['shared_aliases'];
  956. }
  957. $stmt = $pdo->prepare("SELECT `address` AS `direct_aliases`, `public_comment` FROM `alias`
  958. WHERE `goto` = :username_goto
  959. AND `address` NOT LIKE '@%'
  960. AND `address` != :username_address");
  961. $stmt->execute(
  962. array(
  963. ':username_goto' => $username,
  964. ':username_address' => $username
  965. ));
  966. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  967. while ($row = array_shift($run)) {
  968. $data['direct_aliases'][$row['direct_aliases']]['public_comment'] = htmlspecialchars($row['public_comment']);
  969. }
  970. $stmt = $pdo->prepare("SELECT CONCAT(local_part, '@', alias_domain) AS `ad_alias`, `alias_domain` FROM `mailbox`
  971. LEFT OUTER JOIN `alias_domain` on `target_domain` = `domain`
  972. WHERE `username` = :username ;");
  973. $stmt->execute(array(':username' => $username));
  974. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  975. while ($row = array_shift($run)) {
  976. if (empty($row['ad_alias'])) {
  977. continue;
  978. }
  979. $data['direct_aliases'][$row['ad_alias']]['public_comment'] = $lang['add']['alias_domain'];
  980. $data['alias_domains'][] = $row['alias_domain'];
  981. }
  982. $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 '@%';");
  983. $stmt->execute(array(':username' => $username));
  984. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  985. while ($row = array_shift($run)) {
  986. $data['aliases_also_send_as'] = $row['send_as'];
  987. }
  988. $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 '@%';");
  989. $stmt->execute(array(':username' => $username));
  990. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  991. while ($row = array_shift($run)) {
  992. $data['aliases_send_as_all'] = $row['send_as'];
  993. }
  994. $stmt = $pdo->prepare("SELECT IFNULL(GROUP_CONCAT(`address` SEPARATOR ', '), '') as `address` FROM `alias` WHERE `goto` REGEXP :username AND `address` LIKE '@%';");
  995. $stmt->execute(array(':username' => '(^|,)'.$username.'($|,)'));
  996. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  997. while ($row = array_shift($run)) {
  998. $data['is_catch_all'] = $row['address'];
  999. }
  1000. return $data;
  1001. }
  1002. function is_valid_domain_name($domain_name) {
  1003. if (empty($domain_name)) {
  1004. return false;
  1005. }
  1006. $domain_name = idn_to_ascii($domain_name, 0, INTL_IDNA_VARIANT_UTS46);
  1007. return (preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $domain_name)
  1008. && preg_match("/^.{1,253}$/", $domain_name)
  1009. && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $domain_name));
  1010. }
  1011. function set_tfa($_data) {
  1012. global $pdo;
  1013. global $yubi;
  1014. global $tfa;
  1015. $_data_log = $_data;
  1016. $access_denied = null;
  1017. !isset($_data_log['confirm_password']) ?: $_data_log['confirm_password'] = '*';
  1018. $username = $_SESSION['mailcow_cc_username'];
  1019. // check for empty user and role
  1020. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) $access_denied = true;
  1021. // check admin confirm password
  1022. if ($access_denied === null) {
  1023. $stmt = $pdo->prepare("SELECT `password` FROM `admin`
  1024. WHERE `username` = :username");
  1025. $stmt->execute(array(':username' => $username));
  1026. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1027. if ($row) {
  1028. if (!verify_hash($row['password'], $_data["confirm_password"])) $access_denied = true;
  1029. else $access_denied = false;
  1030. }
  1031. }
  1032. // check mailbox confirm password
  1033. if ($access_denied === null) {
  1034. $stmt = $pdo->prepare("SELECT `password`, `authsource` FROM `mailbox`
  1035. WHERE `username` = :username");
  1036. $stmt->execute(array(':username' => $username));
  1037. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1038. if ($row) {
  1039. if ($row['authsource'] == 'ldap'){
  1040. $iam_settings = identity_provider('get');
  1041. if (!ldap_mbox_login($username, $_data["confirm_password"], $iam_settings)) $access_denied = true;
  1042. else $access_denied = false;
  1043. } else {
  1044. if (!verify_hash($row['password'], $_data["confirm_password"])) $access_denied = true;
  1045. else $access_denied = false;
  1046. }
  1047. }
  1048. }
  1049. // set access_denied error
  1050. if ($access_denied){
  1051. $_SESSION['return'][] = array(
  1052. 'type' => 'danger',
  1053. 'log' => array(__FUNCTION__, $_data_log),
  1054. 'msg' => 'access_denied'
  1055. );
  1056. return false;
  1057. }
  1058. switch ($_data["tfa_method"]) {
  1059. case "yubi_otp":
  1060. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  1061. $yubico_id = $_data['yubico_id'];
  1062. $yubico_key = $_data['yubico_key'];
  1063. $yubi = new Auth_Yubico($yubico_id, $yubico_key);
  1064. if (!$yubi) {
  1065. $_SESSION['return'][] = array(
  1066. 'type' => 'danger',
  1067. 'log' => array(__FUNCTION__, $_data_log),
  1068. 'msg' => 'access_denied'
  1069. );
  1070. return false;
  1071. }
  1072. if (!ctype_alnum($_data["otp_token"]) || strlen($_data["otp_token"]) != 44) {
  1073. $_SESSION['return'][] = array(
  1074. 'type' => 'danger',
  1075. 'log' => array(__FUNCTION__, $_data_log),
  1076. 'msg' => 'tfa_token_invalid'
  1077. );
  1078. return false;
  1079. }
  1080. $yauth = $yubi->verify($_data["otp_token"]);
  1081. if (PEAR::isError($yauth)) {
  1082. $_SESSION['return'][] = array(
  1083. 'type' => 'danger',
  1084. 'log' => array(__FUNCTION__, $_data_log),
  1085. 'msg' => array('yotp_verification_failed', $yauth->getMessage())
  1086. );
  1087. return false;
  1088. }
  1089. try {
  1090. // We could also do a modhex translation here
  1091. $yubico_modhex_id = substr($_data["otp_token"], 0, 12);
  1092. $stmt = $pdo->prepare("DELETE FROM `tfa`
  1093. WHERE `username` = :username
  1094. AND (`authmech` = 'yubi_otp' AND `secret` LIKE :modhex)");
  1095. $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id));
  1096. $stmt = $pdo->prepare("INSERT INTO `tfa` (`key_id`, `username`, `authmech`, `active`, `secret`) VALUES
  1097. (:key_id, :username, 'yubi_otp', '1', :secret)");
  1098. $stmt->execute(array(':key_id' => $key_id, ':username' => $username, ':secret' => $yubico_id . ':' . $yubico_key . ':' . $yubico_modhex_id));
  1099. }
  1100. catch (PDOException $e) {
  1101. $_SESSION['return'][] = array(
  1102. 'type' => 'danger',
  1103. 'log' => array(__FUNCTION__, $_data_log),
  1104. 'msg' => array('mysql_error', $e)
  1105. );
  1106. return false;
  1107. }
  1108. $_SESSION['return'][] = array(
  1109. 'type' => 'success',
  1110. 'log' => array(__FUNCTION__, $_data_log),
  1111. 'msg' => array('object_modified', htmlspecialchars($username))
  1112. );
  1113. break;
  1114. case "totp":
  1115. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  1116. if ($tfa->verifyCode($_POST['totp_secret'], $_POST['totp_confirm_token']) === true) {
  1117. //$stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
  1118. //$stmt->execute(array(':username' => $username));
  1119. $stmt = $pdo->prepare("INSERT INTO `tfa` (`username`, `key_id`, `authmech`, `secret`, `active`) VALUES (?, ?, 'totp', ?, '1')");
  1120. $stmt->execute(array($username, $key_id, $_POST['totp_secret']));
  1121. $_SESSION['return'][] = array(
  1122. 'type' => 'success',
  1123. 'log' => array(__FUNCTION__, $_data_log),
  1124. 'msg' => array('object_modified', $username)
  1125. );
  1126. }
  1127. else {
  1128. $_SESSION['return'][] = array(
  1129. 'type' => 'danger',
  1130. 'log' => array(__FUNCTION__, $_data_log),
  1131. 'msg' => 'totp_verification_failed'
  1132. );
  1133. }
  1134. break;
  1135. case "webauthn":
  1136. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  1137. $stmt = $pdo->prepare("INSERT INTO `tfa` (`username`, `key_id`, `authmech`, `keyHandle`, `publicKey`, `certificate`, `counter`, `active`)
  1138. VALUES (?, ?, 'webauthn', ?, ?, ?, ?, '1')");
  1139. $stmt->execute(array(
  1140. $username,
  1141. $key_id,
  1142. base64_encode($_data['registration']->credentialId),
  1143. $_data['registration']->credentialPublicKey,
  1144. $_data['registration']->certificate,
  1145. 0
  1146. ));
  1147. $_SESSION['return'][] = array(
  1148. 'type' => 'success',
  1149. 'log' => array(__FUNCTION__, $_data_log),
  1150. 'msg' => array('object_modified', $username)
  1151. );
  1152. break;
  1153. case "none":
  1154. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
  1155. $stmt->execute(array(':username' => $username));
  1156. $_SESSION['return'][] = array(
  1157. 'type' => 'success',
  1158. 'log' => array(__FUNCTION__, $_data_log),
  1159. 'msg' => array('object_modified', htmlspecialchars($username))
  1160. );
  1161. break;
  1162. }
  1163. }
  1164. function fido2($_data) {
  1165. global $pdo;
  1166. $_data_log = $_data;
  1167. // Not logging registration data, only actions
  1168. // Silent errors for "get" requests
  1169. switch ($_data["action"]) {
  1170. case "register":
  1171. $username = $_SESSION['mailcow_cc_username'];
  1172. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1173. $_SESSION['return'][] = array(
  1174. 'type' => 'danger',
  1175. 'log' => array(__FUNCTION__, $_data["action"]),
  1176. 'msg' => 'access_denied'
  1177. );
  1178. return false;
  1179. }
  1180. $stmt = $pdo->prepare("INSERT INTO `fido2` (`username`, `rpId`, `credentialPublicKey`, `certificateChain`, `certificate`, `certificateIssuer`, `certificateSubject`, `signatureCounter`, `AAGUID`, `credentialId`)
  1181. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
  1182. $stmt->execute(array(
  1183. $username,
  1184. $_data['registration']->rpId,
  1185. $_data['registration']->credentialPublicKey,
  1186. $_data['registration']->certificateChain,
  1187. $_data['registration']->certificate,
  1188. $_data['registration']->certificateIssuer,
  1189. $_data['registration']->certificateSubject,
  1190. $_data['registration']->signatureCounter,
  1191. $_data['registration']->AAGUID,
  1192. $_data['registration']->credentialId)
  1193. );
  1194. $_SESSION['return'][] = array(
  1195. 'type' => 'success',
  1196. 'log' => array(__FUNCTION__, $_data["action"]),
  1197. 'msg' => array('object_modified', $username)
  1198. );
  1199. break;
  1200. case "get_user_cids":
  1201. // Used to exclude existing CredentialIds while registering
  1202. $username = $_SESSION['mailcow_cc_username'];
  1203. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1204. return false;
  1205. }
  1206. $stmt = $pdo->prepare("SELECT `credentialId` FROM `fido2` WHERE `username` = :username");
  1207. $stmt->execute(array(':username' => $username));
  1208. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1209. while($row = array_shift($rows)) {
  1210. $cids[] = $row['credentialId'];
  1211. }
  1212. return $cids;
  1213. break;
  1214. case "get_all_cids":
  1215. // Only needed when using fido2 with username
  1216. $stmt = $pdo->query("SELECT `credentialId` FROM `fido2`");
  1217. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1218. while($row = array_shift($rows)) {
  1219. $cids[] = $row['credentialId'];
  1220. }
  1221. return $cids;
  1222. break;
  1223. case "get_by_b64cid":
  1224. if (!isset($_data['cid']) || empty($_data['cid'])) {
  1225. return false;
  1226. }
  1227. $stmt = $pdo->prepare("SELECT `certificateSubject`, `username`, `credentialPublicKey`, SHA2(`credentialId`, 256) AS `cid` FROM `fido2` WHERE `credentialId` = :cid");
  1228. $stmt->execute(array(':cid' => base64_decode($_data['cid'])));
  1229. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1230. if (empty($row) || empty($row['credentialPublicKey']) || empty($row['username'])) {
  1231. return false;
  1232. }
  1233. $data['pub_key'] = $row['credentialPublicKey'];
  1234. $data['username'] = $row['username'];
  1235. $data['subject'] = $row['certificateSubject'];
  1236. $data['cid'] = $row['cid'];
  1237. return $data;
  1238. break;
  1239. case "get_friendly_names":
  1240. $username = $_SESSION['mailcow_cc_username'];
  1241. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1242. return false;
  1243. }
  1244. $stmt = $pdo->prepare("SELECT SHA2(`credentialId`, 256) AS `cid`, `created`, `certificateSubject`, `friendlyName` FROM `fido2` WHERE `username` = :username");
  1245. $stmt->execute(array(':username' => $username));
  1246. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1247. while($row = array_shift($rows)) {
  1248. $fns[] = array(
  1249. "subject" => (empty($row['certificateSubject']) ? 'Unknown (' . $row['created'] . ')' : $row['certificateSubject']),
  1250. "fn" => $row['friendlyName'],
  1251. "cid" => $row['cid']
  1252. );
  1253. }
  1254. return $fns;
  1255. break;
  1256. case "unset_fido2_key":
  1257. $username = $_SESSION['mailcow_cc_username'];
  1258. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1259. $_SESSION['return'][] = array(
  1260. 'type' => 'danger',
  1261. 'log' => array(__FUNCTION__, $_data["action"]),
  1262. 'msg' => 'access_denied'
  1263. );
  1264. return false;
  1265. }
  1266. $stmt = $pdo->prepare("DELETE FROM `fido2` WHERE `username` = :username AND SHA2(`credentialId`, 256) = :cid");
  1267. $stmt->execute(array(
  1268. ':username' => $username,
  1269. ':cid' => $_data['post_data']['unset_fido2_key']
  1270. ));
  1271. $_SESSION['return'][] = array(
  1272. 'type' => 'success',
  1273. 'log' => array(__FUNCTION__, $_data_log),
  1274. 'msg' => array('object_modified', htmlspecialchars($username))
  1275. );
  1276. break;
  1277. case "edit_fn":
  1278. $username = $_SESSION['mailcow_cc_username'];
  1279. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1280. $_SESSION['return'][] = array(
  1281. 'type' => 'danger',
  1282. 'log' => array(__FUNCTION__, $_data["action"]),
  1283. 'msg' => 'access_denied'
  1284. );
  1285. return false;
  1286. }
  1287. $stmt = $pdo->prepare("UPDATE `fido2` SET `friendlyName` = :friendlyName WHERE SHA2(`credentialId`, 256) = :cid AND `username` = :username");
  1288. $stmt->execute(array(
  1289. ':username' => $username,
  1290. ':friendlyName' => $_data['fido2_attrs']['fido2_fn'],
  1291. ':cid' => $_data['fido2_attrs']['fido2_cid']
  1292. ));
  1293. $_SESSION['return'][] = array(
  1294. 'type' => 'success',
  1295. 'log' => array(__FUNCTION__, $_data_log),
  1296. 'msg' => array('object_modified', htmlspecialchars($username))
  1297. );
  1298. break;
  1299. }
  1300. }
  1301. function unset_tfa_key($_data) {
  1302. // Can only unset own keys
  1303. // Needs at least one key left
  1304. global $pdo;
  1305. global $lang;
  1306. $_data_log = $_data;
  1307. $access_denied = null;
  1308. $id = intval($_data['unset_tfa_key']);
  1309. $username = $_SESSION['mailcow_cc_username'];
  1310. // check for empty user and role
  1311. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) $access_denied = true;
  1312. try {
  1313. if (!is_numeric($id)) $access_denied = true;
  1314. // set access_denied error
  1315. if ($access_denied){
  1316. $_SESSION['return'][] = array(
  1317. 'type' => 'danger',
  1318. 'log' => array(__FUNCTION__, $_data_log),
  1319. 'msg' => 'access_denied'
  1320. );
  1321. return false;
  1322. }
  1323. // check if it's last key
  1324. $stmt = $pdo->prepare("SELECT COUNT(*) AS `keys` FROM `tfa`
  1325. WHERE `username` = :username AND `active` = '1'");
  1326. $stmt->execute(array(':username' => $username));
  1327. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1328. if ($row['keys'] == "1") {
  1329. $_SESSION['return'][] = array(
  1330. 'type' => 'danger',
  1331. 'log' => array(__FUNCTION__, $_data_log),
  1332. 'msg' => 'last_key'
  1333. );
  1334. return false;
  1335. }
  1336. // delete key
  1337. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username AND `id` = :id");
  1338. $stmt->execute(array(':username' => $username, ':id' => $id));
  1339. $_SESSION['return'][] = array(
  1340. 'type' => 'success',
  1341. 'log' => array(__FUNCTION__, $_data_log),
  1342. 'msg' => array('object_modified', $username)
  1343. );
  1344. }
  1345. catch (PDOException $e) {
  1346. $_SESSION['return'][] = array(
  1347. 'type' => 'danger',
  1348. 'log' => array(__FUNCTION__, $_data_log),
  1349. 'msg' => array('mysql_error', $e)
  1350. );
  1351. return false;
  1352. }
  1353. }
  1354. function get_tfa($username = null, $id = null) {
  1355. global $pdo;
  1356. if (empty($username) && isset($_SESSION['mailcow_cc_username'])) {
  1357. $username = $_SESSION['mailcow_cc_username'];
  1358. }
  1359. elseif (empty($username)) {
  1360. return false;
  1361. }
  1362. if (!isset($id)){
  1363. // fetch all tfa methods - just get information about possible authenticators
  1364. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `authmech` FROM `tfa`
  1365. WHERE `username` = :username AND `active` = '1'");
  1366. $stmt->execute(array(':username' => $username));
  1367. $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1368. // no tfa methods found
  1369. if (count($results) == 0) {
  1370. $data['name'] = 'none';
  1371. $data['pretty'] = "-";
  1372. $data['additional'] = array();
  1373. return $data;
  1374. }
  1375. $data['additional'] = $results;
  1376. return $data;
  1377. } else {
  1378. // fetch specific authenticator details by id
  1379. $stmt = $pdo->prepare("SELECT * FROM `tfa`
  1380. WHERE `username` = :username AND `id` = :id AND `active` = '1'");
  1381. $stmt->execute(array(':username' => $username, ':id' => $id));
  1382. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1383. if (isset($row["authmech"])) {
  1384. switch ($row["authmech"]) {
  1385. case "yubi_otp":
  1386. $data['name'] = "yubi_otp";
  1387. $data['pretty'] = "Yubico OTP";
  1388. $stmt = $pdo->prepare("SELECT `id`, `key_id`, RIGHT(`secret`, 12) AS 'modhex' FROM `tfa` WHERE `authmech` = 'yubi_otp' AND `username` = :username AND `id` = :id");
  1389. $stmt->execute(array(
  1390. ':username' => $username,
  1391. ':id' => $id
  1392. ));
  1393. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1394. while($row = array_shift($rows)) {
  1395. $data['additional'][] = $row;
  1396. }
  1397. return $data;
  1398. break;
  1399. // u2f - deprecated, should be removed
  1400. case "u2f":
  1401. $data['name'] = "u2f";
  1402. $data['pretty'] = "Fido U2F";
  1403. $stmt = $pdo->prepare("SELECT `id`, `key_id` FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username AND `id` = :id");
  1404. $stmt->execute(array(
  1405. ':username' => $username,
  1406. ':id' => $id
  1407. ));
  1408. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1409. while($row = array_shift($rows)) {
  1410. $data['additional'][] = $row;
  1411. }
  1412. return $data;
  1413. break;
  1414. case "hotp":
  1415. $data['name'] = "hotp";
  1416. $data['pretty'] = "HMAC-based OTP";
  1417. return $data;
  1418. break;
  1419. case "totp":
  1420. $data['name'] = "totp";
  1421. $data['pretty'] = "Time-based OTP";
  1422. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `secret` FROM `tfa` WHERE `authmech` = 'totp' AND `username` = :username AND `id` = :id");
  1423. $stmt->execute(array(
  1424. ':username' => $username,
  1425. ':id' => $id
  1426. ));
  1427. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1428. while($row = array_shift($rows)) {
  1429. $data['additional'][] = $row;
  1430. }
  1431. return $data;
  1432. break;
  1433. case "webauthn":
  1434. $data['name'] = "webauthn";
  1435. $data['pretty'] = "WebAuthn";
  1436. $stmt = $pdo->prepare("SELECT `id`, `key_id` FROM `tfa` WHERE `authmech` = 'webauthn' AND `username` = :username AND `id` = :id");
  1437. $stmt->execute(array(
  1438. ':username' => $username,
  1439. ':id' => $id
  1440. ));
  1441. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1442. while($row = array_shift($rows)) {
  1443. $data['additional'][] = $row;
  1444. }
  1445. return $data;
  1446. break;
  1447. default:
  1448. $data['name'] = 'none';
  1449. $data['pretty'] = "-";
  1450. return $data;
  1451. break;
  1452. }
  1453. }
  1454. else {
  1455. $data['name'] = 'none';
  1456. $data['pretty'] = "-";
  1457. return $data;
  1458. }
  1459. }
  1460. }
  1461. function verify_tfa_login($username, $_data) {
  1462. global $pdo;
  1463. global $yubi;
  1464. global $u2f;
  1465. global $tfa;
  1466. global $WebAuthn;
  1467. if ($_data['tfa_method'] != 'u2f'){
  1468. switch ($_data["tfa_method"]) {
  1469. case "yubi_otp":
  1470. if (!ctype_alnum($_data['token']) || strlen($_data['token']) != 44) {
  1471. $_SESSION['return'][] = array(
  1472. 'type' => 'danger',
  1473. 'log' => array(__FUNCTION__, $username, '*'),
  1474. 'msg' => array('yotp_verification_failed', 'token length error')
  1475. );
  1476. return false;
  1477. }
  1478. $yubico_modhex_id = substr($_data['token'], 0, 12);
  1479. $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
  1480. WHERE `username` = :username
  1481. AND `authmech` = 'yubi_otp'
  1482. AND `active` = '1'
  1483. AND `secret` LIKE :modhex");
  1484. $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id));
  1485. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1486. $yubico_auth = explode(':', $row['secret']);
  1487. $yubi = new Auth_Yubico($yubico_auth[0], $yubico_auth[1]);
  1488. $yauth = $yubi->verify($_data['token']);
  1489. if (PEAR::isError($yauth)) {
  1490. $_SESSION['return'][] = array(
  1491. 'type' => 'danger',
  1492. 'log' => array(__FUNCTION__, $username, '*'),
  1493. 'msg' => array('yotp_verification_failed', $yauth->getMessage())
  1494. );
  1495. return false;
  1496. }
  1497. else {
  1498. $_SESSION['tfa_id'] = $row['id'];
  1499. $_SESSION['return'][] = array(
  1500. 'type' => 'success',
  1501. 'log' => array(__FUNCTION__, $username, '*'),
  1502. 'msg' => 'verified_yotp_login'
  1503. );
  1504. return true;
  1505. }
  1506. $_SESSION['return'][] = array(
  1507. 'type' => 'danger',
  1508. 'log' => array(__FUNCTION__, $username, '*'),
  1509. 'msg' => array('yotp_verification_failed', 'unknown')
  1510. );
  1511. return false;
  1512. break;
  1513. case "hotp":
  1514. return false;
  1515. break;
  1516. case "totp":
  1517. try {
  1518. $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
  1519. WHERE `username` = :username
  1520. AND `authmech` = 'totp'
  1521. AND `id` = :id
  1522. AND `active`='1'");
  1523. $stmt->execute(array(':username' => $username, ':id' => $_data['id']));
  1524. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1525. foreach ($rows as $row) {
  1526. if ($tfa->verifyCode($row['secret'], $_data['token']) === true) {
  1527. $_SESSION['tfa_id'] = $row['id'];
  1528. $_SESSION['return'][] = array(
  1529. 'type' => 'success',
  1530. 'log' => array(__FUNCTION__, $username, '*'),
  1531. 'msg' => 'verified_totp_login'
  1532. );
  1533. return true;
  1534. }
  1535. }
  1536. $_SESSION['return'][] = array(
  1537. 'type' => 'danger',
  1538. 'log' => array(__FUNCTION__, $username, '*'),
  1539. 'msg' => 'totp_verification_failed'
  1540. );
  1541. return false;
  1542. }
  1543. catch (PDOException $e) {
  1544. $_SESSION['return'][] = array(
  1545. 'type' => 'danger',
  1546. 'log' => array(__FUNCTION__, $username, '*'),
  1547. 'msg' => array('mysql_error', $e)
  1548. );
  1549. return false;
  1550. }
  1551. break;
  1552. case "webauthn":
  1553. $tokenData = json_decode($_data['token']);
  1554. $clientDataJSON = base64_decode($tokenData->clientDataJSON);
  1555. $authenticatorData = base64_decode($tokenData->authenticatorData);
  1556. $signature = base64_decode($tokenData->signature);
  1557. $id = base64_decode($tokenData->id);
  1558. $challenge = $_SESSION['challenge'];
  1559. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `keyHandle`, `username`, `publicKey` FROM `tfa` WHERE `id` = :id AND `active`='1'");
  1560. $stmt->execute(array(':id' => $_data['id']));
  1561. $process_webauthn = $stmt->fetch(PDO::FETCH_ASSOC);
  1562. if (empty($process_webauthn)){
  1563. $_SESSION['return'][] = array(
  1564. 'type' => 'danger',
  1565. 'log' => array(__FUNCTION__, $username, '*'),
  1566. 'msg' => array('webauthn_authenticator_failed')
  1567. );
  1568. return false;
  1569. }
  1570. if (empty($process_webauthn['publicKey']) || $process_webauthn['publicKey'] === false) {
  1571. $_SESSION['return'][] = array(
  1572. 'type' => 'danger',
  1573. 'log' => array(__FUNCTION__, $username, '*'),
  1574. 'msg' => array('webauthn_publickey_failed')
  1575. );
  1576. return false;
  1577. }
  1578. if ($process_webauthn['username'] != $_SESSION['pending_mailcow_cc_username']){
  1579. $_SESSION['return'][] = array(
  1580. 'type' => 'danger',
  1581. 'log' => array(__FUNCTION__, $username, '*'),
  1582. 'msg' => array('webauthn_username_failed')
  1583. );
  1584. return false;
  1585. }
  1586. try {
  1587. $WebAuthn->processGet($clientDataJSON, $authenticatorData, $signature, $process_webauthn['publicKey'], $challenge, null, $GLOBALS['WEBAUTHN_UV_FLAG_LOGIN'], $GLOBALS['WEBAUTHN_USER_PRESENT_FLAG']);
  1588. }
  1589. catch (Throwable $ex) {
  1590. $_SESSION['return'][] = array(
  1591. 'type' => 'danger',
  1592. 'log' => array(__FUNCTION__, $username, '*'),
  1593. 'msg' => array('webauthn_verification_failed', $ex->getMessage())
  1594. );
  1595. return false;
  1596. }
  1597. $stmt = $pdo->prepare("SELECT `superadmin` FROM `admin` WHERE `username` = :username");
  1598. $stmt->execute(array(':username' => $process_webauthn['username']));
  1599. $obj_props = $stmt->fetch(PDO::FETCH_ASSOC);
  1600. if ($obj_props['superadmin'] === 1) {
  1601. $_SESSION["mailcow_cc_role"] = "admin";
  1602. }
  1603. elseif ($obj_props['superadmin'] === 0) {
  1604. $_SESSION["mailcow_cc_role"] = "domainadmin";
  1605. }
  1606. else {
  1607. $stmt = $pdo->prepare("SELECT `username` FROM `mailbox` WHERE `username` = :username");
  1608. $stmt->execute(array(':username' => $process_webauthn['username']));
  1609. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1610. if (!empty($row['username'])) {
  1611. $_SESSION["mailcow_cc_role"] = "user";
  1612. } else {
  1613. $_SESSION['return'][] = array(
  1614. 'type' => 'danger',
  1615. 'log' => array(__FUNCTION__, $username, '*'),
  1616. 'msg' => array('webauthn_role_failed')
  1617. );
  1618. return false;
  1619. }
  1620. }
  1621. $_SESSION["mailcow_cc_username"] = $process_webauthn['username'];
  1622. $_SESSION['tfa_id'] = $process_webauthn['id'];
  1623. $_SESSION['authReq'] = null;
  1624. unset($_SESSION["challenge"]);
  1625. $_SESSION['return'][] = array(
  1626. 'type' => 'success',
  1627. 'log' => array("webauthn_login"),
  1628. 'msg' => array('logged_in_as', $process_webauthn['username'])
  1629. );
  1630. return true;
  1631. break;
  1632. default:
  1633. $_SESSION['return'][] = array(
  1634. 'type' => 'danger',
  1635. 'log' => array(__FUNCTION__, $username, '*'),
  1636. 'msg' => 'unknown_tfa_method'
  1637. );
  1638. return false;
  1639. break;
  1640. }
  1641. return false;
  1642. } else {
  1643. // delete old keys that used u2f
  1644. $stmt = $pdo->prepare("SELECT * FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username");
  1645. $stmt->execute(array(':username' => $username));
  1646. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1647. if (count($rows) == 0) return false;
  1648. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username");
  1649. $stmt->execute(array(':username' => $username));
  1650. return true;
  1651. }
  1652. }
  1653. function admin_api($access, $action, $data = null) {
  1654. global $pdo;
  1655. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1656. $_SESSION['return'][] = array(
  1657. 'type' => 'danger',
  1658. 'log' => array(__FUNCTION__),
  1659. 'msg' => 'access_denied'
  1660. );
  1661. return false;
  1662. }
  1663. if ($access !== "ro" && $access !== "rw") {
  1664. $_SESSION['return'][] = array(
  1665. 'type' => 'danger',
  1666. 'log' => array(__FUNCTION__),
  1667. 'msg' => 'invalid access type'
  1668. );
  1669. return false;
  1670. }
  1671. if ($action == "edit") {
  1672. $active = (!empty($data['active'])) ? 1 : 0;
  1673. $skip_ip_check = (isset($data['skip_ip_check'])) ? 1 : 0;
  1674. $allow_from = array();
  1675. if (isset($data['allow_from'])) {
  1676. $allow_from = array_map('trim', preg_split( "/( |,|;|\n)/", $data['allow_from']));
  1677. }
  1678. foreach ($allow_from as $key => $val) {
  1679. if (empty($val)) {
  1680. unset($allow_from[$key]);
  1681. continue;
  1682. }
  1683. if (valid_network($val) !== true) {
  1684. $_SESSION['return'][] = array(
  1685. 'type' => 'warning',
  1686. 'log' => array(__FUNCTION__, $data),
  1687. 'msg' => array('ip_invalid', htmlspecialchars($allow_from[$key]))
  1688. );
  1689. unset($allow_from[$key]);
  1690. continue;
  1691. }
  1692. }
  1693. $allow_from = implode(',', array_unique(array_filter($allow_from)));
  1694. if (empty($allow_from) && $skip_ip_check == 0) {
  1695. $_SESSION['return'][] = array(
  1696. 'type' => 'danger',
  1697. 'log' => array(__FUNCTION__, $data),
  1698. 'msg' => 'ip_list_empty'
  1699. );
  1700. return false;
  1701. }
  1702. $api_key = implode('-', array(
  1703. strtoupper(bin2hex(random_bytes(3))),
  1704. strtoupper(bin2hex(random_bytes(3))),
  1705. strtoupper(bin2hex(random_bytes(3))),
  1706. strtoupper(bin2hex(random_bytes(3))),
  1707. strtoupper(bin2hex(random_bytes(3)))
  1708. ));
  1709. $stmt = $pdo->query("SELECT `api_key` FROM `api` WHERE `access` = '" . $access . "'");
  1710. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  1711. if (empty($num_results)) {
  1712. $stmt = $pdo->prepare("INSERT INTO `api` (`api_key`, `skip_ip_check`, `active`, `allow_from`, `access`)
  1713. VALUES (:api_key, :skip_ip_check, :active, :allow_from, :access);");
  1714. $stmt->execute(array(
  1715. ':api_key' => $api_key,
  1716. ':skip_ip_check' => $skip_ip_check,
  1717. ':active' => $active,
  1718. ':allow_from' => $allow_from,
  1719. ':access' => $access
  1720. ));
  1721. }
  1722. else {
  1723. if ($skip_ip_check == 0) {
  1724. $stmt = $pdo->prepare("UPDATE `api` SET `skip_ip_check` = :skip_ip_check,
  1725. `active` = :active,
  1726. `allow_from` = :allow_from
  1727. WHERE `access` = :access;");
  1728. $stmt->execute(array(
  1729. ':active' => $active,
  1730. ':skip_ip_check' => $skip_ip_check,
  1731. ':allow_from' => $allow_from,
  1732. ':access' => $access
  1733. ));
  1734. }
  1735. else {
  1736. $stmt = $pdo->prepare("UPDATE `api` SET `skip_ip_check` = :skip_ip_check,
  1737. `active` = :active
  1738. WHERE `access` = :access;");
  1739. $stmt->execute(array(
  1740. ':active' => $active,
  1741. ':skip_ip_check' => $skip_ip_check,
  1742. ':access' => $access
  1743. ));
  1744. }
  1745. }
  1746. }
  1747. elseif ($action == "regen_key") {
  1748. $api_key = implode('-', array(
  1749. strtoupper(bin2hex(random_bytes(3))),
  1750. strtoupper(bin2hex(random_bytes(3))),
  1751. strtoupper(bin2hex(random_bytes(3))),
  1752. strtoupper(bin2hex(random_bytes(3))),
  1753. strtoupper(bin2hex(random_bytes(3)))
  1754. ));
  1755. $stmt = $pdo->prepare("UPDATE `api` SET `api_key` = :api_key WHERE `access` = :access");
  1756. $stmt->execute(array(
  1757. ':api_key' => $api_key,
  1758. ':access' => $access
  1759. ));
  1760. }
  1761. elseif ($action == "get") {
  1762. $stmt = $pdo->query("SELECT * FROM `api` WHERE `access` = '" . $access . "'");
  1763. $apidata = $stmt->fetch(PDO::FETCH_ASSOC);
  1764. if ($apidata !== false) {
  1765. $apidata['allow_from'] = str_replace(',', PHP_EOL, $apidata['allow_from']);
  1766. }
  1767. return $apidata;
  1768. }
  1769. $_SESSION['return'][] = array(
  1770. 'type' => 'success',
  1771. 'log' => array(__FUNCTION__, $data),
  1772. 'msg' => 'admin_api_modified'
  1773. );
  1774. }
  1775. function license($action, $data = null) {
  1776. global $pdo;
  1777. global $redis;
  1778. global $lang;
  1779. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1780. $_SESSION['return'][] = array(
  1781. 'type' => 'danger',
  1782. 'log' => array(__FUNCTION__),
  1783. 'msg' => 'access_denied'
  1784. );
  1785. return false;
  1786. }
  1787. switch ($action) {
  1788. case "verify":
  1789. // Keep result until revalidate button is pressed or session expired
  1790. $stmt = $pdo->query("SELECT `version` FROM `versions` WHERE `application` = 'GUID'");
  1791. $versions = $stmt->fetch(PDO::FETCH_ASSOC);
  1792. $post = array('guid' => $versions['version']);
  1793. $curl = curl_init('https://verify.mailcow.email');
  1794. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  1795. curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
  1796. curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
  1797. $response = curl_exec($curl);
  1798. curl_close($curl);
  1799. $json_return = json_decode($response, true);
  1800. if ($response && $json_return) {
  1801. if ($json_return['response'] === "ok") {
  1802. $_SESSION['gal']['valid'] = "true";
  1803. $_SESSION['gal']['c'] = $json_return['c'];
  1804. $_SESSION['gal']['s'] = $json_return['s'];
  1805. if ($json_return['m'] == 'NoMoore') {
  1806. $_SESSION['gal']['m'] = '🐄';
  1807. }
  1808. else {
  1809. $_SESSION['gal']['m'] = str_repeat('🐄', substr_count($json_return['m'], 'o'));
  1810. }
  1811. }
  1812. elseif ($json_return['response'] === "invalid") {
  1813. $_SESSION['gal']['valid'] = "false";
  1814. $_SESSION['gal']['c'] = $lang['mailbox']['no'];
  1815. $_SESSION['gal']['s'] = $lang['mailbox']['no'];
  1816. $_SESSION['gal']['m'] = $lang['mailbox']['no'];
  1817. }
  1818. }
  1819. else {
  1820. $_SESSION['gal']['valid'] = "false";
  1821. $_SESSION['gal']['c'] = $lang['danger']['temp_error'];
  1822. $_SESSION['gal']['s'] = $lang['danger']['temp_error'];
  1823. $_SESSION['gal']['m'] = $lang['danger']['temp_error'];
  1824. }
  1825. try {
  1826. // json_encode needs "true"/"false" instead of true/false, to not encode it to 0 or 1
  1827. $redis->Set('LICENSE_STATUS_CACHE', json_encode($_SESSION['gal']));
  1828. }
  1829. catch (RedisException $e) {
  1830. $_SESSION['return'][] = array(
  1831. 'type' => 'danger',
  1832. 'log' => array(__FUNCTION__, $_action, $_data_log),
  1833. 'msg' => array('redis_error', $e)
  1834. );
  1835. return false;
  1836. }
  1837. return $_SESSION['gal']['valid'];
  1838. break;
  1839. case "guid":
  1840. $stmt = $pdo->query("SELECT `version` FROM `versions` WHERE `application` = 'GUID'");
  1841. $versions = $stmt->fetch(PDO::FETCH_ASSOC);
  1842. return $versions['version'];
  1843. break;
  1844. }
  1845. }
  1846. function rspamd_ui($action, $data = null) {
  1847. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1848. $_SESSION['return'][] = array(
  1849. 'type' => 'danger',
  1850. 'log' => array(__FUNCTION__),
  1851. 'msg' => 'access_denied'
  1852. );
  1853. return false;
  1854. }
  1855. switch ($action) {
  1856. case "edit":
  1857. $rspamd_ui_pass = $data['rspamd_ui_pass'];
  1858. $rspamd_ui_pass2 = $data['rspamd_ui_pass2'];
  1859. if (empty($rspamd_ui_pass) || empty($rspamd_ui_pass2)) {
  1860. $_SESSION['return'][] = array(
  1861. 'type' => 'danger',
  1862. 'log' => array(__FUNCTION__, '*', '*'),
  1863. 'msg' => 'password_empty'
  1864. );
  1865. return false;
  1866. }
  1867. if ($rspamd_ui_pass != $rspamd_ui_pass2) {
  1868. $_SESSION['return'][] = array(
  1869. 'type' => 'danger',
  1870. 'log' => array(__FUNCTION__, '*', '*'),
  1871. 'msg' => 'password_mismatch'
  1872. );
  1873. return false;
  1874. }
  1875. if (strlen($rspamd_ui_pass) < 6) {
  1876. $_SESSION['return'][] = array(
  1877. 'type' => 'danger',
  1878. 'log' => array(__FUNCTION__, '*', '*'),
  1879. 'msg' => 'rspamd_ui_pw_length'
  1880. );
  1881. return false;
  1882. }
  1883. $docker_return = docker('post', 'rspamd-mailcow', 'exec', array('cmd' => 'rspamd', 'task' => 'worker_password', 'raw' => $rspamd_ui_pass), array('Content-Type: application/json'));
  1884. if ($docker_return_array = json_decode($docker_return, true)) {
  1885. if ($docker_return_array['type'] == 'success') {
  1886. $_SESSION['return'][] = array(
  1887. 'type' => 'success',
  1888. 'log' => array(__FUNCTION__, '*', '*'),
  1889. 'msg' => 'rspamd_ui_pw_set'
  1890. );
  1891. return true;
  1892. }
  1893. else {
  1894. $_SESSION['return'][] = array(
  1895. 'type' => $docker_return_array['type'],
  1896. 'log' => array(__FUNCTION__, '*', '*'),
  1897. 'msg' => $docker_return_array['msg']
  1898. );
  1899. return false;
  1900. }
  1901. }
  1902. else {
  1903. $_SESSION['return'][] = array(
  1904. 'type' => 'danger',
  1905. 'log' => array(__FUNCTION__, '*', '*'),
  1906. 'msg' => 'unknown'
  1907. );
  1908. return false;
  1909. }
  1910. break;
  1911. }
  1912. }
  1913. function cors($action, $data = null) {
  1914. global $redis;
  1915. switch ($action) {
  1916. case "edit":
  1917. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1918. $_SESSION['return'][] = array(
  1919. 'type' => 'danger',
  1920. 'log' => array(__FUNCTION__, $action, $data),
  1921. 'msg' => 'access_denied'
  1922. );
  1923. return false;
  1924. }
  1925. $allowed_origins = isset($data['allowed_origins']) ? $data['allowed_origins'] : array($_SERVER['SERVER_NAME']);
  1926. $allowed_origins = !is_array($allowed_origins) ? array_filter(array_map('trim', explode("\n", $allowed_origins))) : $allowed_origins;
  1927. foreach ($allowed_origins as $origin) {
  1928. if (!filter_var($origin, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) && $origin != '*') {
  1929. $_SESSION['return'][] = array(
  1930. 'type' => 'danger',
  1931. 'log' => array(__FUNCTION__, $action, $data),
  1932. 'msg' => 'cors_invalid_origin'
  1933. );
  1934. return false;
  1935. }
  1936. }
  1937. $allowed_methods = isset($data['allowed_methods']) ? $data['allowed_methods'] : array('GET', 'POST', 'PUT', 'DELETE');
  1938. $allowed_methods = !is_array($allowed_methods) ? array_map('trim', preg_split( "/( |,|;|\n)/", $allowed_methods)) : $allowed_methods;
  1939. $available_methods = array('GET', 'POST', 'PUT', 'DELETE');
  1940. foreach ($allowed_methods as $method) {
  1941. if (!in_array($method, $available_methods)) {
  1942. $_SESSION['return'][] = array(
  1943. 'type' => 'danger',
  1944. 'log' => array(__FUNCTION__, $action, $data),
  1945. 'msg' => 'cors_invalid_method'
  1946. );
  1947. return false;
  1948. }
  1949. }
  1950. try {
  1951. $redis->hMSet('CORS_SETTINGS', array(
  1952. 'allowed_origins' => implode(', ', $allowed_origins),
  1953. 'allowed_methods' => implode(', ', $allowed_methods)
  1954. ));
  1955. } catch (RedisException $e) {
  1956. $_SESSION['return'][] = array(
  1957. 'type' => 'danger',
  1958. 'log' => array(__FUNCTION__, $action, $data),
  1959. 'msg' => array('redis_error', $e)
  1960. );
  1961. return false;
  1962. }
  1963. $_SESSION['return'][] = array(
  1964. 'type' => 'success',
  1965. 'log' => array(__FUNCTION__, $action, $data),
  1966. 'msg' => 'cors_headers_edited'
  1967. );
  1968. return true;
  1969. break;
  1970. case "get":
  1971. try {
  1972. $cors_settings = $redis->hMGet('CORS_SETTINGS', array('allowed_origins', 'allowed_methods'));
  1973. } catch (RedisException $e) {
  1974. $_SESSION['return'][] = array(
  1975. 'type' => 'danger',
  1976. 'log' => array(__FUNCTION__, $action, $data),
  1977. 'msg' => array('redis_error', $e)
  1978. );
  1979. }
  1980. $cors_settings = !$cors_settings ? array('allowed_origins' => $_SERVER['SERVER_NAME'], 'allowed_methods' => 'GET, POST, PUT, DELETE') : $cors_settings;
  1981. $cors_settings['allowed_origins'] = empty($cors_settings['allowed_origins']) ? $_SERVER['SERVER_NAME'] : $cors_settings['allowed_origins'];
  1982. $cors_settings['allowed_methods'] = empty($cors_settings['allowed_methods']) ? 'GET, POST, PUT, DELETE, OPTION' : $cors_settings['allowed_methods'];
  1983. return $cors_settings;
  1984. break;
  1985. case "set_headers":
  1986. $cors_settings = cors('get');
  1987. // check if requested origin is in allowed origins
  1988. $allowed_origins = explode(', ', $cors_settings['allowed_origins']);
  1989. $cors_settings['allowed_origins'] = $allowed_origins[0];
  1990. if (in_array('*', $allowed_origins)){
  1991. $cors_settings['allowed_origins'] = '*';
  1992. } else if (in_array($_SERVER['HTTP_ORIGIN'], $allowed_origins)) {
  1993. $cors_settings['allowed_origins'] = $_SERVER['HTTP_ORIGIN'];
  1994. }
  1995. // always allow OPTIONS for preflight request
  1996. $cors_settings["allowed_methods"] = empty($cors_settings["allowed_methods"]) ? 'OPTIONS' : $cors_settings["allowed_methods"] . ', ' . 'OPTIONS';
  1997. header('Access-Control-Allow-Origin: ' . $cors_settings['allowed_origins']);
  1998. header('Access-Control-Allow-Methods: '. $cors_settings['allowed_methods']);
  1999. header('Access-Control-Allow-Headers: Accept, Content-Type, X-Api-Key, Origin');
  2000. // Access-Control settings requested, this is just a preflight request
  2001. if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS' &&
  2002. isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']) &&
  2003. isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
  2004. $allowed_methods = explode(', ', $cors_settings["allowed_methods"]);
  2005. if (in_array($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'], $allowed_methods, true))
  2006. // method allowed send 200 OK
  2007. http_response_code(200);
  2008. else
  2009. // method not allowed send 405 METHOD NOT ALLOWED
  2010. http_response_code(405);
  2011. exit;
  2012. }
  2013. break;
  2014. }
  2015. }
  2016. function getBaseURL() {
  2017. $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
  2018. $host = $_SERVER['HTTP_HOST'];
  2019. $base_url = $protocol . '://' . $host;
  2020. return $base_url;
  2021. }
  2022. function uuid4() {
  2023. $data = openssl_random_pseudo_bytes(16);
  2024. $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
  2025. $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
  2026. return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
  2027. }
  2028. function identity_provider($_action = null, $_data = null, $_extra = null) {
  2029. global $pdo;
  2030. global $iam_provider;
  2031. $data_log = $_data;
  2032. if (isset($data_log['client_secret'])) $data_log['client_secret'] = '*';
  2033. if (isset($data_log['access_token'])) $data_log['access_token'] = '*';
  2034. switch ($_action) {
  2035. case NULL:
  2036. if ($iam_provider) {
  2037. return $iam_provider;
  2038. } else {
  2039. $iam_provider = identity_provider("init");
  2040. return $iam_provider;
  2041. }
  2042. break;
  2043. case 'get':
  2044. $settings = array();
  2045. $stmt = $pdo->prepare("SELECT * FROM `identity_provider`;");
  2046. $stmt->execute();
  2047. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2048. foreach($rows as $row){
  2049. switch ($row["key"]) {
  2050. case "mappers":
  2051. case "templates":
  2052. $settings[$row["key"]] = json_decode($row["value"]);
  2053. break;
  2054. case "use_ssl":
  2055. case "use_tls":
  2056. case "ignore_ssl_errors":
  2057. $settings[$row["key"]] = boolval($row["value"]);
  2058. break;
  2059. default:
  2060. $settings[$row["key"]] = $row["value"];
  2061. break;
  2062. }
  2063. }
  2064. // return default client_scopes for generic-oidc if none is set
  2065. if ($settings["authsource"] == "generic-oidc" && empty($settings["client_scopes"])){
  2066. $settings["client_scopes"] = "openid profile email";
  2067. }
  2068. if ($_extra['hide_sensitive']){
  2069. $settings['client_secret'] = '';
  2070. $settings['access_token'] = '';
  2071. }
  2072. // return default ldap options
  2073. if ($settings["authsource"] == "ldap"){
  2074. $settings['use_ssl'] = !isset($settings['use_ssl']) ? false : $settings['use_ssl'];
  2075. $settings['use_tls'] = !isset($settings['use_tls']) ? false : $settings['use_tls'];
  2076. $settings['ignore_ssl_errors'] = !isset($settings['ignore_ssl_errors']) ? false : $settings['ignore_ssl_errors'];
  2077. }
  2078. return $settings;
  2079. break;
  2080. case 'edit':
  2081. if ($_SESSION['mailcow_cc_role'] != "admin") {
  2082. $_SESSION['return'][] = array(
  2083. 'type' => 'danger',
  2084. 'log' => array(__FUNCTION__, $_action, $_data),
  2085. 'msg' => 'access_denied'
  2086. );
  2087. return false;
  2088. }
  2089. if (!isset($_data['authsource'])){
  2090. $_SESSION['return'][] = array(
  2091. 'type' => 'danger',
  2092. 'log' => array(__FUNCTION__, $_action, $data_log),
  2093. 'msg' => array('required_data_missing', '')
  2094. );
  2095. return false;
  2096. }
  2097. $available_authsources = array(
  2098. "keycloak",
  2099. "generic-oidc",
  2100. "ldap"
  2101. );
  2102. $_data['authsource'] = strtolower($_data['authsource']);
  2103. if (!in_array($_data['authsource'], $available_authsources)){
  2104. $_SESSION['return'][] = array(
  2105. 'type' => 'danger',
  2106. 'log' => array(__FUNCTION__, $_action, $data_log),
  2107. 'msg' => array('invalid_authsource', $setting)
  2108. );
  2109. return false;
  2110. }
  2111. $stmt = $pdo->prepare("SELECT * FROM `mailbox`
  2112. WHERE `authsource` != 'mailcow'
  2113. AND `authsource` IS NOT NULL
  2114. AND `authsource` != :authsource");
  2115. $stmt->execute(array(':authsource' => $_data['authsource']));
  2116. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2117. if ($rows) {
  2118. $_SESSION['return'][] = array(
  2119. 'type' => 'danger',
  2120. 'log' => array(__FUNCTION__, $_action, $data_log),
  2121. 'msg' => array('authsource_in_use', $setting)
  2122. );
  2123. return false;
  2124. }
  2125. switch ($_data['authsource']) {
  2126. case "keycloak":
  2127. $_data['server_url'] = (!empty($_data['server_url'])) ? rtrim($_data['server_url'], '/') : null;
  2128. $_data['mailpassword_flow'] = isset($_data['mailpassword_flow']) ? intval($_data['mailpassword_flow']) : 0;
  2129. $_data['periodic_sync'] = isset($_data['periodic_sync']) ? intval($_data['periodic_sync']) : 0;
  2130. $_data['import_users'] = isset($_data['import_users']) ? intval($_data['import_users']) : 0;
  2131. $_data['sync_interval'] = (!empty($_data['sync_interval'])) ? intval($_data['sync_interval']) : 15;
  2132. $_data['sync_interval'] = $_data['sync_interval'] < 1 ? 1 : $_data['sync_interval'];
  2133. $required_settings = array('authsource', 'server_url', 'realm', 'client_id', 'client_secret', 'redirect_url', 'version', 'mailpassword_flow', 'periodic_sync', 'import_users', 'sync_interval');
  2134. break;
  2135. case "generic-oidc":
  2136. $_data['authorize_url'] = (!empty($_data['authorize_url'])) ? $_data['authorize_url'] : null;
  2137. $_data['token_url'] = (!empty($_data['token_url'])) ? $_data['token_url'] : null;
  2138. $_data['userinfo_url'] = (!empty($_data['userinfo_url'])) ? $_data['userinfo_url'] : null;
  2139. $_data['client_scopes'] = (!empty($_data['client_scopes'])) ? $_data['client_scopes'] : "openid profile email";
  2140. $required_settings = array('authsource', 'authorize_url', 'token_url', 'client_id', 'client_secret', 'redirect_url', 'userinfo_url', 'client_scopes');
  2141. break;
  2142. case "ldap":
  2143. $_data['port'] = (!empty($_data['port'])) ? intval($_data['port']) : 389;
  2144. $_data['username_field'] = (!empty($_data['username_field'])) ? $_data['username_field'] : "mail";
  2145. $_data['filter'] = (!empty($_data['filter'])) ? $_data['filter'] : "";
  2146. $_data['periodic_sync'] = isset($_data['periodic_sync']) ? intval($_data['periodic_sync']) : 0;
  2147. $_data['import_users'] = isset($_data['import_users']) ? intval($_data['import_users']) : 0;
  2148. $_data['use_ssl'] = isset($_data['use_ssl']) ? boolval($_data['use_ssl']) : false;
  2149. $_data['use_tls'] = isset($_data['use_tls']) && !$_data['use_ssl'] ? boolval($_data['use_tls']) : false;
  2150. $_data['ignore_ssl_error'] = isset($_data['ignore_ssl_error']) ? boolval($_data['ignore_ssl_error']) : false;
  2151. $_data['sync_interval'] = (!empty($_data['sync_interval'])) ? intval($_data['sync_interval']) : 15;
  2152. $_data['sync_interval'] = $_data['sync_interval'] < 1 ? 1 : $_data['sync_interval'];
  2153. $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');
  2154. break;
  2155. }
  2156. $pdo->beginTransaction();
  2157. $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES (:key, :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
  2158. // add connection settings
  2159. foreach($required_settings as $setting){
  2160. if (!isset($_data[$setting])){
  2161. $_SESSION['return'][] = array(
  2162. 'type' => 'danger',
  2163. 'log' => array(__FUNCTION__, $_action, $data_log),
  2164. 'msg' => array('required_data_missing', $setting)
  2165. );
  2166. $pdo->rollback();
  2167. return false;
  2168. }
  2169. $stmt->bindParam(':key', $setting);
  2170. $stmt->bindParam(':value', $_data[$setting]);
  2171. $stmt->execute();
  2172. }
  2173. $pdo->commit();
  2174. // add mappers
  2175. if ($_data['mappers'] && $_data['templates']){
  2176. $_data['mappers'] = (!is_array($_data['mappers'])) ? array($_data['mappers']) : $_data['mappers'];
  2177. $_data['templates'] = (!is_array($_data['templates'])) ? array($_data['templates']) : $_data['templates'];
  2178. $mappers = array_filter($_data['mappers']);
  2179. $templates = array_filter($_data['templates']);
  2180. if (count($mappers) == count($templates)){
  2181. $mappers = json_encode($mappers);
  2182. $templates = json_encode($templates);
  2183. $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES ('mappers', :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
  2184. $stmt->bindParam(':value', $mappers);
  2185. $stmt->execute();
  2186. $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES ('templates', :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
  2187. $stmt->bindParam(':value', $templates);
  2188. $stmt->execute();
  2189. }
  2190. }
  2191. // delete old access_token
  2192. $stmt = $pdo->query("INSERT INTO identity_provider (`key`, `value`) VALUES ('access_token', '') ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
  2193. $_SESSION['return'][] = array(
  2194. 'type' => 'success',
  2195. 'log' => array(__FUNCTION__, $_action, $data_log),
  2196. 'msg' => array('object_modified', '')
  2197. );
  2198. return true;
  2199. break;
  2200. case 'test':
  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. switch ($_data['authsource']) {
  2210. case 'keycloak':
  2211. case 'generic-oidc':
  2212. if ($_data['authsource'] == 'keycloak') {
  2213. $url = "{$_data['server_url']}/realms/{$_data['realm']}/protocol/openid-connect/token";
  2214. } else {
  2215. $url = $_data['token_url'];
  2216. }
  2217. $req = http_build_query(array(
  2218. 'grant_type' => 'client_credentials',
  2219. 'client_id' => $_data['client_id'],
  2220. 'client_secret' => $_data['client_secret']
  2221. ));
  2222. $curl = curl_init();
  2223. curl_setopt($curl, CURLOPT_URL, $url);
  2224. curl_setopt($curl, CURLOPT_TIMEOUT, 7);
  2225. curl_setopt($curl, CURLOPT_POST, 1);
  2226. curl_setopt($curl, CURLOPT_POSTFIELDS, $req);
  2227. curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
  2228. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2229. $res = curl_exec($curl);
  2230. $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  2231. curl_close ($curl);
  2232. if ($code != 200) {
  2233. return false;
  2234. }
  2235. break;
  2236. case 'ldap':
  2237. if (!$_data['host'] || !$_data['port'] || !$_data['basedn'] ||
  2238. !$_data['binddn'] || !$_data['bindpass']){
  2239. return false;
  2240. }
  2241. $_data['use_ssl'] = isset($_data['use_ssl']) ? boolval($_data['use_ssl']) : false;
  2242. $_data['use_tls'] = isset($_data['use_tls']) && !$_data['use_ssl'] ? boolval($_data['use_tls']) : false;
  2243. $_data['ignore_ssl_error'] = isset($_data['ignore_ssl_error']) ? boolval($_data['ignore_ssl_error']) : false;
  2244. $options = array();
  2245. if ($_data['ignore_ssl_error']) {
  2246. $options['LDAP_OPT_X_TLS_REQUIRE_CERT'] = "LDAP_OPT_X_TLS_NEVER";
  2247. }
  2248. $provider = new \LdapRecord\Connection([
  2249. 'hosts' => [$_data['host']],
  2250. 'port' => $_data['port'],
  2251. 'base_dn' => $_data['basedn'],
  2252. 'username' => $_data['binddn'],
  2253. 'password' => $_data['bindpass'],
  2254. 'use_ssl' => $_data['use_ssl'],
  2255. 'use_tls' => $_data['use_tls'],
  2256. 'options' => $options
  2257. ]);
  2258. try {
  2259. $provider->connect();
  2260. } catch (TypeError $e) {
  2261. return false;
  2262. } catch (\LdapRecord\Auth\BindException $e) {
  2263. return false;
  2264. }
  2265. break;
  2266. }
  2267. return true;
  2268. break;
  2269. case "delete":
  2270. if ($_SESSION['mailcow_cc_role'] != "admin") {
  2271. $_SESSION['return'][] = array(
  2272. 'type' => 'danger',
  2273. 'log' => array(__FUNCTION__, $_action, $_data),
  2274. 'msg' => 'access_denied'
  2275. );
  2276. return false;
  2277. }
  2278. $stmt = $pdo->query("SELECT * FROM `mailbox`
  2279. WHERE `authsource` != 'mailcow'
  2280. AND `authsource` IS NOT NULL");
  2281. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2282. if ($rows) {
  2283. $_SESSION['return'][] = array(
  2284. 'type' => 'danger',
  2285. 'log' => array(__FUNCTION__, $_action, $data_log),
  2286. 'msg' => array('authsource_in_use', $setting)
  2287. );
  2288. return false;
  2289. }
  2290. $stmt = $pdo->query("DELETE FROM identity_provider;");
  2291. $_SESSION['return'][] = array(
  2292. 'type' => 'success',
  2293. 'log' => array(__FUNCTION__, $_action, $data_log),
  2294. 'msg' => array('item_deleted', '')
  2295. );
  2296. return true;
  2297. break;
  2298. case "init":
  2299. $iam_settings = identity_provider('get');
  2300. $provider = null;
  2301. switch ($iam_settings['authsource']) {
  2302. case "keycloak":
  2303. if ($iam_settings['server_url'] && $iam_settings['realm'] && $iam_settings['client_id'] &&
  2304. $iam_settings['client_secret'] && $iam_settings['redirect_url'] && $iam_settings['version']){
  2305. $provider = new Stevenmaguire\OAuth2\Client\Provider\Keycloak([
  2306. 'authServerUrl' => $iam_settings['server_url'],
  2307. 'realm' => $iam_settings['realm'],
  2308. 'clientId' => $iam_settings['client_id'],
  2309. 'clientSecret' => $iam_settings['client_secret'],
  2310. 'redirectUri' => $iam_settings['redirect_url'],
  2311. 'version' => $iam_settings['version'],
  2312. // 'encryptionAlgorithm' => 'RS256', // optional
  2313. // 'encryptionKeyPath' => '../key.pem' // optional
  2314. // 'encryptionKey' => 'contents_of_key_or_certificate' // optional
  2315. ]);
  2316. }
  2317. break;
  2318. case "generic-oidc":
  2319. if ($iam_settings['client_id'] && $iam_settings['client_secret'] && $iam_settings['redirect_url'] &&
  2320. $iam_settings['authorize_url'] && $iam_settings['token_url'] && $iam_settings['userinfo_url']){
  2321. $provider = new \League\OAuth2\Client\Provider\GenericProvider([
  2322. 'clientId' => $iam_settings['client_id'],
  2323. 'clientSecret' => $iam_settings['client_secret'],
  2324. 'redirectUri' => $iam_settings['redirect_url'],
  2325. 'urlAuthorize' => $iam_settings['authorize_url'],
  2326. 'urlAccessToken' => $iam_settings['token_url'],
  2327. 'urlResourceOwnerDetails' => $iam_settings['userinfo_url'],
  2328. 'scopes' => $iam_settings['client_scopes']
  2329. ]);
  2330. }
  2331. break;
  2332. case "ldap":
  2333. if ($iam_settings['host'] && $iam_settings['port'] && $iam_settings['basedn'] &&
  2334. $iam_settings['binddn'] && $iam_settings['bindpass']){
  2335. $options = array();
  2336. if ($iam_settings['ignore_ssl_error']) {
  2337. $options['LDAP_OPT_X_TLS_REQUIRE_CERT'] = "LDAP_OPT_X_TLS_NEVER";
  2338. }
  2339. $provider = new \LdapRecord\Connection([
  2340. 'hosts' => [$iam_settings['host']],
  2341. 'port' => $iam_settings['port'],
  2342. 'base_dn' => $iam_settings['basedn'],
  2343. 'username' => $iam_settings['binddn'],
  2344. 'password' => $iam_settings['bindpass'],
  2345. 'use_ssl' => $iam_settings['use_ssl'],
  2346. 'use_tls' => $iam_settings['use_tls'],
  2347. 'options' => $options
  2348. ]);
  2349. try {
  2350. $provider->connect();
  2351. } catch (Throwable $e) {
  2352. $provider = null;
  2353. }
  2354. }
  2355. break;
  2356. }
  2357. return $provider;
  2358. break;
  2359. case "verify-sso":
  2360. $provider = $_data['iam_provider'];
  2361. $iam_settings = identity_provider('get');
  2362. if ($iam_settings['authsource'] != 'keycloak' && $iam_settings['authsource'] != 'generic-oidc'){
  2363. $_SESSION['return'][] = array(
  2364. 'type' => 'danger',
  2365. 'log' => array(__FUNCTION__),
  2366. 'msg' => array('login_failed', "no OIDC provider configured")
  2367. );
  2368. return false;
  2369. }
  2370. try {
  2371. $token = $provider->getAccessToken('authorization_code', ['code' => $_GET['code']]);
  2372. $_SESSION['iam_token'] = $token->getToken();
  2373. $_SESSION['iam_refresh_token'] = $token->getRefreshToken();
  2374. $info = $provider->getResourceOwner($token)->toArray();
  2375. } catch (Throwable $e) {
  2376. $_SESSION['return'][] = array(
  2377. 'type' => 'danger',
  2378. 'log' => array(__FUNCTION__),
  2379. 'msg' => array('login_failed', $e->getMessage())
  2380. );
  2381. return false;
  2382. }
  2383. // check if email address is given
  2384. if (empty($info['email'])) return false;
  2385. // token valid, get mailbox
  2386. $stmt = $pdo->prepare("SELECT * FROM `mailbox`
  2387. INNER JOIN domain on mailbox.domain = domain.domain
  2388. WHERE `kind` NOT REGEXP 'location|thing|group'
  2389. AND `mailbox`.`active`='1'
  2390. AND `domain`.`active`='1'
  2391. AND `username` = :user
  2392. AND (`authsource`='keycloak' OR `authsource`='generic-oidc')");
  2393. $stmt->execute(array(':user' => $info['email']));
  2394. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  2395. if ($row){
  2396. // success
  2397. set_user_loggedin_session($info['email']);
  2398. $_SESSION['return'][] = array(
  2399. 'type' => 'success',
  2400. 'log' => array(__FUNCTION__, $_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role']),
  2401. 'msg' => array('logged_in_as', $_SESSION['mailcow_cc_username'])
  2402. );
  2403. return true;
  2404. }
  2405. // get mapped template, if not set return false
  2406. // also return false if no mappers were defined
  2407. $user_template = $info['mailcow_template'];
  2408. if (empty($iam_settings['mappers']) || empty($user_template)){
  2409. clear_session();
  2410. $_SESSION['return'][] = array(
  2411. 'type' => 'danger',
  2412. 'log' => array(__FUNCTION__, $info['email']),
  2413. 'msg' => array('login_failed', 'empty attribute mapping or missing template attribute')
  2414. );
  2415. return false;
  2416. }
  2417. // check if matching attribute exist
  2418. $mapper_key = array_search($user_template, $iam_settings['mappers']);
  2419. if ($mapper_key === false) {
  2420. clear_session();
  2421. $_SESSION['return'][] = array(
  2422. 'type' => 'danger',
  2423. 'log' => array(__FUNCTION__, $info['email']),
  2424. 'msg' => array('login_failed', 'specified template not found')
  2425. );
  2426. return false;
  2427. }
  2428. // create mailbox
  2429. $create_res = mailbox('add', 'mailbox_from_template', array(
  2430. 'domain' => explode('@', $info['email'])[1],
  2431. 'local_part' => explode('@', $info['email'])[0],
  2432. 'name' => $info['firstName'] . " " . $info['lastName'],
  2433. 'authsource' => $iam_settings['authsource'],
  2434. 'template' => $iam_settings['templates'][$mapper_key]
  2435. ));
  2436. if (!$create_res){
  2437. clear_session();
  2438. $_SESSION['return'][] = array(
  2439. 'type' => 'danger',
  2440. 'log' => array(__FUNCTION__, $info['email']),
  2441. 'msg' => array('login_failed', 'mailbox creation failed')
  2442. );
  2443. return false;
  2444. }
  2445. set_user_loggedin_session($info['email']);
  2446. $_SESSION['return'][] = array(
  2447. 'type' => 'success',
  2448. 'log' => array(__FUNCTION__, $_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role']),
  2449. 'msg' => array('logged_in_as', $_SESSION['mailcow_cc_username'])
  2450. );
  2451. return true;
  2452. break;
  2453. case "refresh-token":
  2454. $provider = $_data['iam_provider'];
  2455. try {
  2456. $token = $provider->getAccessToken('refresh_token', ['refresh_token' => $_SESSION['iam_refresh_token']]);
  2457. $_SESSION['iam_token'] = $token->getToken();
  2458. $_SESSION['iam_refresh_token'] = $token->getRefreshToken();
  2459. $info = $provider->getResourceOwner($token)->toArray();
  2460. } catch (Throwable $e) {
  2461. clear_session();
  2462. $_SESSION['return'][] = array(
  2463. 'type' => 'danger',
  2464. 'log' => array(__FUNCTION__),
  2465. 'msg' => array('refresh_login_failed', $e->getMessage())
  2466. );
  2467. return false;
  2468. }
  2469. if (empty($info['email'])){
  2470. clear_session();
  2471. $_SESSION['return'][] = array(
  2472. 'type' => 'danger',
  2473. 'log' => array(__FUNCTION__, $_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role']),
  2474. 'msg' => 'refresh_login_failed'
  2475. );
  2476. return false;
  2477. }
  2478. $_SESSION['mailcow_cc_username'] = $info['email'];
  2479. $_SESSION['mailcow_cc_role'] = "user";
  2480. return true;
  2481. break;
  2482. case "get-redirect":
  2483. $iam_settings = identity_provider('get');
  2484. if ($iam_settings['authsource'] != 'keycloak' && $iam_settings['authsource'] != 'generic-oidc')
  2485. return false;
  2486. $provider = $_data['iam_provider'];
  2487. $authUrl = $provider->getAuthorizationUrl();
  2488. $_SESSION['oauth2state'] = $provider->getState();
  2489. return $authUrl;
  2490. break;
  2491. case "get-keycloak-admin-token":
  2492. // get access_token for service account of mailcow client
  2493. $iam_settings = identity_provider('get');
  2494. if ($iam_settings['authsource'] !== 'keycloak') return false;
  2495. if (isset($iam_settings['access_token'])) {
  2496. // check if access_token is valid
  2497. $url = "{$iam_settings['server_url']}/realms/{$iam_settings['realm']}/protocol/openid-connect/token/introspect";
  2498. $req = http_build_query(array(
  2499. 'token' => $iam_settings['access_token'],
  2500. 'client_id' => $iam_settings['client_id'],
  2501. 'client_secret' => $iam_settings['client_secret']
  2502. ));
  2503. $curl = curl_init();
  2504. curl_setopt($curl, CURLOPT_URL, $url);
  2505. curl_setopt($curl, CURLOPT_TIMEOUT, 7);
  2506. curl_setopt($curl, CURLOPT_POST, 1);
  2507. curl_setopt($curl, CURLOPT_POSTFIELDS, $req);
  2508. curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
  2509. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2510. curl_setopt($curl, CURLOPT_TIMEOUT, 5);
  2511. $res = json_decode(curl_exec($curl), true);
  2512. $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  2513. curl_close ($curl);
  2514. if ($code == 200 && $res['active'] == true) {
  2515. // token is valid
  2516. return $iam_settings['access_token'];
  2517. }
  2518. }
  2519. $url = "{$iam_settings['server_url']}/realms/{$iam_settings['realm']}/protocol/openid-connect/token";
  2520. $req = http_build_query(array(
  2521. 'grant_type' => 'client_credentials',
  2522. 'client_id' => $iam_settings['client_id'],
  2523. 'client_secret' => $iam_settings['client_secret']
  2524. ));
  2525. $curl = curl_init();
  2526. curl_setopt($curl, CURLOPT_URL, $url);
  2527. curl_setopt($curl, CURLOPT_TIMEOUT, 7);
  2528. curl_setopt($curl, CURLOPT_POST, 1);
  2529. curl_setopt($curl, CURLOPT_POSTFIELDS, $req);
  2530. curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
  2531. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2532. curl_setopt($curl, CURLOPT_TIMEOUT, 5);
  2533. $res = json_decode(curl_exec($curl), true);
  2534. $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  2535. curl_close ($curl);
  2536. if ($code != 200) {
  2537. return false;
  2538. }
  2539. $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES (:key, :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
  2540. $stmt->execute(array(
  2541. ':key' => 'access_token',
  2542. ':value' => $res['access_token']
  2543. ));
  2544. return $res['access_token'];
  2545. break;
  2546. }
  2547. }
  2548. function clear_session(){
  2549. session_regenerate_id(true);
  2550. session_unset();
  2551. session_destroy();
  2552. session_write_close();
  2553. }
  2554. function set_user_loggedin_session($user) {
  2555. $_SESSION['mailcow_cc_username'] = $user;
  2556. $_SESSION['mailcow_cc_role'] = 'user';
  2557. $sogo_sso_pass = file_get_contents("/etc/sogo-sso/sogo-sso.pass");
  2558. $_SESSION['sogo-sso-user-allowed'][] = $user;
  2559. $_SESSION['sogo-sso-pass'] = $sogo_sso_pass;
  2560. unset($_SESSION['pending_mailcow_cc_username']);
  2561. unset($_SESSION['pending_mailcow_cc_role']);
  2562. unset($_SESSION['pending_tfa_methods']);
  2563. }
  2564. function get_logs($application, $lines = false) {
  2565. if ($lines === false) {
  2566. $lines = $GLOBALS['LOG_LINES'] - 1;
  2567. }
  2568. elseif(is_numeric($lines) && $lines >= 1) {
  2569. $lines = abs(intval($lines) - 1);
  2570. }
  2571. else {
  2572. list ($from, $to) = explode('-', $lines);
  2573. $from = intval($from);
  2574. $to = intval($to);
  2575. if ($from < 1 || $to < $from) { return false; }
  2576. }
  2577. global $redis;
  2578. global $pdo;
  2579. if ($_SESSION['mailcow_cc_role'] != "admin") {
  2580. return false;
  2581. }
  2582. // SQL
  2583. if ($application == "mailcow-ui") {
  2584. if (isset($from) && isset($to)) {
  2585. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :from, :to");
  2586. $stmt->execute(array(
  2587. ':from' => $from - 1,
  2588. ':to' => $to
  2589. ));
  2590. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2591. }
  2592. else {
  2593. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :lines");
  2594. $stmt->execute(array(
  2595. ':lines' => $lines + 1,
  2596. ));
  2597. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2598. }
  2599. if (is_array($data)) {
  2600. return $data;
  2601. }
  2602. }
  2603. if ($application == "sasl") {
  2604. if (isset($from) && isset($to)) {
  2605. $stmt = $pdo->prepare("SELECT * FROM `sasl_log` ORDER BY `datetime` DESC LIMIT :from, :to");
  2606. $stmt->execute(array(
  2607. ':from' => $from - 1,
  2608. ':to' => $to
  2609. ));
  2610. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2611. }
  2612. else {
  2613. $stmt = $pdo->prepare("SELECT * FROM `sasl_log` ORDER BY `datetime` DESC LIMIT :lines");
  2614. $stmt->execute(array(
  2615. ':lines' => $lines + 1,
  2616. ));
  2617. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2618. }
  2619. if (is_array($data)) {
  2620. return $data;
  2621. }
  2622. }
  2623. // Redis
  2624. if ($application == "dovecot-mailcow") {
  2625. if (isset($from) && isset($to)) {
  2626. $data = $redis->lRange('DOVECOT_MAILLOG', $from - 1, $to - 1);
  2627. }
  2628. else {
  2629. $data = $redis->lRange('DOVECOT_MAILLOG', 0, $lines);
  2630. }
  2631. if ($data) {
  2632. foreach ($data as $json_line) {
  2633. $data_array[] = json_decode($json_line, true);
  2634. }
  2635. return $data_array;
  2636. }
  2637. }
  2638. if ($application == "cron-mailcow") {
  2639. if (isset($from) && isset($to)) {
  2640. $data = $redis->lRange('CRON_LOG', $from - 1, $to - 1);
  2641. }
  2642. else {
  2643. $data = $redis->lRange('CRON_LOG', 0, $lines);
  2644. }
  2645. if ($data) {
  2646. foreach ($data as $json_line) {
  2647. $data_array[] = json_decode($json_line, true);
  2648. }
  2649. return $data_array;
  2650. }
  2651. }
  2652. if ($application == "postfix-mailcow") {
  2653. if (isset($from) && isset($to)) {
  2654. $data = $redis->lRange('POSTFIX_MAILLOG', $from - 1, $to - 1);
  2655. }
  2656. else {
  2657. $data = $redis->lRange('POSTFIX_MAILLOG', 0, $lines);
  2658. }
  2659. if ($data) {
  2660. foreach ($data as $json_line) {
  2661. $data_array[] = json_decode($json_line, true);
  2662. }
  2663. return $data_array;
  2664. }
  2665. }
  2666. if ($application == "sogo-mailcow") {
  2667. if (isset($from) && isset($to)) {
  2668. $data = $redis->lRange('SOGO_LOG', $from - 1, $to - 1);
  2669. }
  2670. else {
  2671. $data = $redis->lRange('SOGO_LOG', 0, $lines);
  2672. }
  2673. if ($data) {
  2674. foreach ($data as $json_line) {
  2675. $data_array[] = json_decode($json_line, true);
  2676. }
  2677. return $data_array;
  2678. }
  2679. }
  2680. if ($application == "watchdog-mailcow") {
  2681. if (isset($from) && isset($to)) {
  2682. $data = $redis->lRange('WATCHDOG_LOG', $from - 1, $to - 1);
  2683. }
  2684. else {
  2685. $data = $redis->lRange('WATCHDOG_LOG', 0, $lines);
  2686. }
  2687. if ($data) {
  2688. foreach ($data as $json_line) {
  2689. $data_array[] = json_decode($json_line, true);
  2690. }
  2691. return $data_array;
  2692. }
  2693. }
  2694. if ($application == "acme-mailcow") {
  2695. if (isset($from) && isset($to)) {
  2696. $data = $redis->lRange('ACME_LOG', $from - 1, $to - 1);
  2697. }
  2698. else {
  2699. $data = $redis->lRange('ACME_LOG', 0, $lines);
  2700. }
  2701. if ($data) {
  2702. foreach ($data as $json_line) {
  2703. $data_array[] = json_decode($json_line, true);
  2704. }
  2705. return $data_array;
  2706. }
  2707. }
  2708. if ($application == "ratelimited") {
  2709. if (isset($from) && isset($to)) {
  2710. $data = $redis->lRange('RL_LOG', $from - 1, $to - 1);
  2711. }
  2712. else {
  2713. $data = $redis->lRange('RL_LOG', 0, $lines);
  2714. }
  2715. if ($data) {
  2716. foreach ($data as $json_line) {
  2717. $data_array[] = json_decode($json_line, true);
  2718. }
  2719. return $data_array;
  2720. }
  2721. }
  2722. if ($application == "api-mailcow") {
  2723. if (isset($from) && isset($to)) {
  2724. $data = $redis->lRange('API_LOG', $from - 1, $to - 1);
  2725. }
  2726. else {
  2727. $data = $redis->lRange('API_LOG', 0, $lines);
  2728. }
  2729. if ($data) {
  2730. foreach ($data as $json_line) {
  2731. $data_array[] = json_decode($json_line, true);
  2732. }
  2733. return $data_array;
  2734. }
  2735. }
  2736. if ($application == "netfilter-mailcow") {
  2737. if (isset($from) && isset($to)) {
  2738. $data = $redis->lRange('NETFILTER_LOG', $from - 1, $to - 1);
  2739. }
  2740. else {
  2741. $data = $redis->lRange('NETFILTER_LOG', 0, $lines);
  2742. }
  2743. if ($data) {
  2744. foreach ($data as $json_line) {
  2745. $data_array[] = json_decode($json_line, true);
  2746. }
  2747. return $data_array;
  2748. }
  2749. }
  2750. if ($application == "autodiscover-mailcow") {
  2751. if (isset($from) && isset($to)) {
  2752. $data = $redis->lRange('AUTODISCOVER_LOG', $from - 1, $to - 1);
  2753. }
  2754. else {
  2755. $data = $redis->lRange('AUTODISCOVER_LOG', 0, $lines);
  2756. }
  2757. if ($data) {
  2758. foreach ($data as $json_line) {
  2759. $data_array[] = json_decode($json_line, true);
  2760. }
  2761. return $data_array;
  2762. }
  2763. }
  2764. if ($application == "rspamd-history") {
  2765. $curl = curl_init();
  2766. curl_setopt($curl, CURLOPT_UNIX_SOCKET_PATH, '/var/lib/rspamd/rspamd.sock');
  2767. if (!is_numeric($lines)) {
  2768. list ($from, $to) = explode('-', $lines);
  2769. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?from=" . intval($from) . "&to=" . intval($to));
  2770. }
  2771. else {
  2772. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?to=" . intval($lines));
  2773. }
  2774. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2775. $history = curl_exec($curl);
  2776. if (!curl_errno($curl)) {
  2777. $data_array = json_decode($history, true);
  2778. curl_close($curl);
  2779. return $data_array['rows'];
  2780. }
  2781. curl_close($curl);
  2782. return false;
  2783. }
  2784. if ($application == "rspamd-stats") {
  2785. $curl = curl_init();
  2786. curl_setopt($curl, CURLOPT_UNIX_SOCKET_PATH, '/var/lib/rspamd/rspamd.sock');
  2787. curl_setopt($curl, CURLOPT_URL,"http://rspamd/stat");
  2788. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2789. $stats = curl_exec($curl);
  2790. if (!curl_errno($curl)) {
  2791. $data_array = json_decode($stats, true);
  2792. curl_close($curl);
  2793. return $data_array;
  2794. }
  2795. curl_close($curl);
  2796. return false;
  2797. }
  2798. return false;
  2799. }
  2800. function getGUID() {
  2801. if (function_exists('com_create_guid')) {
  2802. return com_create_guid();
  2803. }
  2804. mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
  2805. $charid = strtoupper(md5(uniqid(rand(), true)));
  2806. $hyphen = chr(45);// "-"
  2807. return substr($charid, 0, 8).$hyphen
  2808. .substr($charid, 8, 4).$hyphen
  2809. .substr($charid,12, 4).$hyphen
  2810. .substr($charid,16, 4).$hyphen
  2811. .substr($charid,20,12);
  2812. }
  2813. function solr_status() {
  2814. $curl = curl_init();
  2815. $endpoint = 'http://solr:8983/solr/admin/cores';
  2816. $params = array(
  2817. 'action' => 'STATUS',
  2818. 'core' => 'dovecot-fts',
  2819. 'indexInfo' => 'true'
  2820. );
  2821. $url = $endpoint . '?' . http_build_query($params);
  2822. curl_setopt($curl, CURLOPT_URL, $url);
  2823. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  2824. curl_setopt($curl, CURLOPT_POST, 0);
  2825. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  2826. $response_core = curl_exec($curl);
  2827. if ($response_core === false) {
  2828. $err = curl_error($curl);
  2829. curl_close($curl);
  2830. return false;
  2831. }
  2832. else {
  2833. curl_close($curl);
  2834. $curl = curl_init();
  2835. $status_core = json_decode($response_core, true);
  2836. $url = 'http://solr:8983/solr/admin/info/system';
  2837. curl_setopt($curl, CURLOPT_URL, $url);
  2838. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  2839. curl_setopt($curl, CURLOPT_POST, 0);
  2840. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  2841. $response_sysinfo = curl_exec($curl);
  2842. if ($response_sysinfo === false) {
  2843. $err = curl_error($curl);
  2844. curl_close($curl);
  2845. return false;
  2846. }
  2847. else {
  2848. curl_close($curl);
  2849. $status_sysinfo = json_decode($response_sysinfo, true);
  2850. $status = array_merge($status_core, $status_sysinfo);
  2851. return (!empty($status['status']['dovecot-fts']) && !empty($status['jvm']['memory'])) ? $status : false;
  2852. }
  2853. return (!empty($status['status']['dovecot-fts'])) ? $status['status']['dovecot-fts'] : false;
  2854. }
  2855. return false;
  2856. }
  2857. function cleanupJS($ignore = '', $folder = '/tmp/*.js') {
  2858. $now = time();
  2859. foreach (glob($folder) as $filename) {
  2860. if(strpos($filename, $ignore) !== false) {
  2861. continue;
  2862. }
  2863. if (is_file($filename)) {
  2864. if ($now - filemtime($filename) >= 60 * 60) {
  2865. unlink($filename);
  2866. }
  2867. }
  2868. }
  2869. }
  2870. function cleanupCSS($ignore = '', $folder = '/tmp/*.css') {
  2871. $now = time();
  2872. foreach (glob($folder) as $filename) {
  2873. if(strpos($filename, $ignore) !== false) {
  2874. continue;
  2875. }
  2876. if (is_file($filename)) {
  2877. if ($now - filemtime($filename) >= 60 * 60) {
  2878. unlink($filename);
  2879. }
  2880. }
  2881. }
  2882. }
  2883. ?>