functions.inc.php 109 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992
  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 check_login($user, $pass, $app_passwd_data = false) {
  792. global $pdo;
  793. global $redis;
  794. global $imap_server;
  795. if (!filter_var($user, FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $user))) {
  796. $_SESSION['return'][] = array(
  797. 'type' => 'danger',
  798. 'log' => array(__FUNCTION__, $user, '*'),
  799. 'msg' => 'malformed_username'
  800. );
  801. return false;
  802. }
  803. // Validate admin
  804. $user = strtolower(trim($user));
  805. $stmt = $pdo->prepare("SELECT `password` FROM `admin`
  806. WHERE `superadmin` = '1'
  807. AND `active` = '1'
  808. AND `username` = :user");
  809. $stmt->execute(array(':user' => $user));
  810. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  811. foreach ($rows as $row) {
  812. // verify password
  813. if (verify_hash($row['password'], $pass)) {
  814. // check for tfa authenticators
  815. $authenticators = get_tfa($user);
  816. if (isset($authenticators['additional']) && is_array($authenticators['additional']) && count($authenticators['additional']) > 0) {
  817. // active tfa authenticators found, set pending user login
  818. $_SESSION['pending_mailcow_cc_username'] = $user;
  819. $_SESSION['pending_mailcow_cc_role'] = "admin";
  820. $_SESSION['pending_tfa_methods'] = $authenticators['additional'];
  821. unset($_SESSION['ldelay']);
  822. $_SESSION['return'][] = array(
  823. 'type' => 'info',
  824. 'log' => array(__FUNCTION__, $user, '*'),
  825. 'msg' => 'awaiting_tfa_confirmation'
  826. );
  827. return "pending";
  828. } else {
  829. unset($_SESSION['ldelay']);
  830. // Reactivate TFA if it was set to "deactivate TFA for next login"
  831. $stmt = $pdo->prepare("UPDATE `tfa` SET `active`='1' WHERE `username` = :user");
  832. $stmt->execute(array(':user' => $user));
  833. $_SESSION['return'][] = array(
  834. 'type' => 'success',
  835. 'log' => array(__FUNCTION__, $user, '*'),
  836. 'msg' => array('logged_in_as', $user)
  837. );
  838. return "admin";
  839. }
  840. }
  841. }
  842. // Validate domain admin
  843. $stmt = $pdo->prepare("SELECT `password` FROM `admin`
  844. WHERE `superadmin` = '0'
  845. AND `active`='1'
  846. AND `username` = :user");
  847. $stmt->execute(array(':user' => $user));
  848. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  849. foreach ($rows as $row) {
  850. // verify password
  851. if (verify_hash($row['password'], $pass) !== false) {
  852. // check for tfa authenticators
  853. $authenticators = get_tfa($user);
  854. if (isset($authenticators['additional']) && is_array($authenticators['additional']) && count($authenticators['additional']) > 0) {
  855. $_SESSION['pending_mailcow_cc_username'] = $user;
  856. $_SESSION['pending_mailcow_cc_role'] = "domainadmin";
  857. $_SESSION['pending_tfa_methods'] = $authenticators['additional'];
  858. unset($_SESSION['ldelay']);
  859. $_SESSION['return'][] = array(
  860. 'type' => 'info',
  861. 'log' => array(__FUNCTION__, $user, '*'),
  862. 'msg' => 'awaiting_tfa_confirmation'
  863. );
  864. return "pending";
  865. }
  866. else {
  867. unset($_SESSION['ldelay']);
  868. // Reactivate TFA if it was set to "deactivate TFA for next login"
  869. $stmt = $pdo->prepare("UPDATE `tfa` SET `active`='1' WHERE `username` = :user");
  870. $stmt->execute(array(':user' => $user));
  871. $_SESSION['return'][] = array(
  872. 'type' => 'success',
  873. 'log' => array(__FUNCTION__, $user, '*'),
  874. 'msg' => array('logged_in_as', $user)
  875. );
  876. return "domainadmin";
  877. }
  878. }
  879. }
  880. // Validate mailbox user
  881. $stmt = $pdo->prepare("SELECT `password`, JSON_UNQUOTE(JSON_EXTRACT(`attributes`, '$.force_pw_update')) AS `force_pw_update` FROM `mailbox`
  882. INNER JOIN domain on mailbox.domain = domain.domain
  883. WHERE `kind` NOT REGEXP 'location|thing|group'
  884. AND `mailbox`.`active`='1'
  885. AND `domain`.`active`='1'
  886. AND `username` = :user");
  887. $stmt->execute(array(':user' => $user));
  888. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  889. if ($app_passwd_data['eas'] === true) {
  890. $stmt = $pdo->prepare("SELECT `app_passwd`.`password` as `password`, `app_passwd`.`id` as `app_passwd_id` FROM `app_passwd`
  891. INNER JOIN `mailbox` ON `mailbox`.`username` = `app_passwd`.`mailbox`
  892. INNER JOIN `domain` ON `mailbox`.`domain` = `domain`.`domain`
  893. WHERE `mailbox`.`kind` NOT REGEXP 'location|thing|group'
  894. AND `mailbox`.`active` = '1'
  895. AND `domain`.`active` = '1'
  896. AND `app_passwd`.`active` = '1'
  897. AND `app_passwd`.`eas_access` = '1'
  898. AND `app_passwd`.`mailbox` = :user");
  899. $stmt->execute(array(':user' => $user));
  900. $rows = array_merge($rows, $stmt->fetchAll(PDO::FETCH_ASSOC));
  901. }
  902. elseif ($app_passwd_data['dav'] === true) {
  903. $stmt = $pdo->prepare("SELECT `app_passwd`.`password` as `password`, `app_passwd`.`id` as `app_passwd_id` FROM `app_passwd`
  904. INNER JOIN `mailbox` ON `mailbox`.`username` = `app_passwd`.`mailbox`
  905. INNER JOIN `domain` ON `mailbox`.`domain` = `domain`.`domain`
  906. WHERE `mailbox`.`kind` NOT REGEXP 'location|thing|group'
  907. AND `mailbox`.`active` = '1'
  908. AND `domain`.`active` = '1'
  909. AND `app_passwd`.`active` = '1'
  910. AND `app_passwd`.`dav_access` = '1'
  911. AND `app_passwd`.`mailbox` = :user");
  912. $stmt->execute(array(':user' => $user));
  913. $rows = array_merge($rows, $stmt->fetchAll(PDO::FETCH_ASSOC));
  914. }
  915. foreach ($rows as $row) {
  916. // verify password
  917. if (verify_hash($row['password'], $pass) !== false) {
  918. if (!array_key_exists("app_passwd_id", $row)){
  919. // password is not a app password
  920. // check if pw update is required
  921. if (array_key_exists('force_pw_update', $row) && intval($row['force_pw_update']) == 1) {
  922. $_SESSION['pending_pw_update'] = True;
  923. }
  924. // check for tfa authenticators
  925. $authenticators = get_tfa($user);
  926. if (isset($authenticators['additional']) && is_array($authenticators['additional']) && count($authenticators['additional']) > 0 &&
  927. $app_passwd_data['eas'] !== true && $app_passwd_data['dav'] !== true) {
  928. // authenticators found, init TFA flow
  929. $_SESSION['pending_mailcow_cc_username'] = $user;
  930. $_SESSION['pending_mailcow_cc_role'] = "user";
  931. $_SESSION['pending_tfa_methods'] = $authenticators['additional'];
  932. unset($_SESSION['ldelay']);
  933. $_SESSION['return'][] = array(
  934. 'type' => 'success',
  935. 'log' => array(__FUNCTION__, $user, '*'),
  936. 'msg' => array('logged_in_as', $user)
  937. );
  938. return "pending";
  939. } else if (!isset($authenticators['additional']) || !is_array($authenticators['additional']) || count($authenticators['additional']) == 0) {
  940. // no authenticators found, login successfull
  941. // Reactivate TFA if it was set to "deactivate TFA for next login"
  942. $stmt = $pdo->prepare("UPDATE `tfa` SET `active`='1' WHERE `username` = :user");
  943. $stmt->execute(array(':user' => $user));
  944. unset($_SESSION['ldelay']);
  945. return "user";
  946. }
  947. } elseif ($app_passwd_data['eas'] === true || $app_passwd_data['dav'] === true) {
  948. // password is a app password
  949. $service = ($app_passwd_data['eas'] === true) ? 'EAS' : 'DAV';
  950. $stmt = $pdo->prepare("REPLACE INTO sasl_log (`service`, `app_password`, `username`, `real_rip`) VALUES (:service, :app_id, :username, :remote_addr)");
  951. $stmt->execute(array(
  952. ':service' => $service,
  953. ':app_id' => $row['app_passwd_id'],
  954. ':username' => $user,
  955. ':remote_addr' => ($_SERVER['HTTP_X_REAL_IP'] ?? $_SERVER['REMOTE_ADDR'])
  956. ));
  957. unset($_SESSION['ldelay']);
  958. return "user";
  959. }
  960. }
  961. }
  962. if (!isset($_SESSION['ldelay'])) {
  963. $_SESSION['ldelay'] = "0";
  964. $redis->publish("F2B_CHANNEL", "mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  965. error_log("mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  966. }
  967. elseif (!isset($_SESSION['mailcow_cc_username'])) {
  968. $_SESSION['ldelay'] = $_SESSION['ldelay']+0.5;
  969. $redis->publish("F2B_CHANNEL", "mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  970. error_log("mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  971. }
  972. $_SESSION['return'][] = array(
  973. 'type' => 'danger',
  974. 'log' => array(__FUNCTION__, $user, '*'),
  975. 'msg' => 'login_failed'
  976. );
  977. sleep($_SESSION['ldelay']);
  978. return false;
  979. }
  980. function formatBytes($size, $precision = 2) {
  981. if(!is_numeric($size)) {
  982. return "0";
  983. }
  984. $base = log($size, 1024);
  985. $suffixes = array(' Byte', ' KiB', ' MiB', ' GiB', ' TiB');
  986. if ($size == "0") {
  987. return "0";
  988. }
  989. return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
  990. }
  991. function update_sogo_static_view($mailbox = null) {
  992. if (getenv('SKIP_SOGO') == "y") {
  993. return true;
  994. }
  995. global $pdo;
  996. global $lang;
  997. $mailbox_exists = false;
  998. if ($mailbox !== null) {
  999. // Check if the mailbox exists
  1000. $stmt = $pdo->prepare("SELECT username FROM mailbox WHERE username = :mailbox AND active = '1'");
  1001. $stmt->execute(array(':mailbox' => $mailbox));
  1002. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1003. if ($row){
  1004. $mailbox_exists = true;
  1005. }
  1006. }
  1007. $query = "REPLACE INTO _sogo_static_view (`c_uid`, `domain`, `c_name`, `c_password`, `c_cn`, `mail`, `aliases`, `ad_aliases`, `ext_acl`, `kind`, `multiple_bookings`)
  1008. SELECT
  1009. mailbox.username,
  1010. mailbox.domain,
  1011. mailbox.username,
  1012. IF(JSON_UNQUOTE(JSON_VALUE(attributes, '$.force_pw_update')) = '0',
  1013. IF(JSON_UNQUOTE(JSON_VALUE(attributes, '$.sogo_access')) = 1, password, '{SSHA256}A123A123A321A321A321B321B321B123B123B321B432F123E321123123321321'),
  1014. '{SSHA256}A123A123A321A321A321B321B321B123B123B321B432F123E321123123321321'),
  1015. mailbox.name,
  1016. mailbox.username,
  1017. IFNULL(GROUP_CONCAT(ga.aliases ORDER BY ga.aliases SEPARATOR ' '), ''),
  1018. IFNULL(gda.ad_alias, ''),
  1019. IFNULL(external_acl.send_as_acl, ''),
  1020. mailbox.kind,
  1021. mailbox.multiple_bookings
  1022. FROM
  1023. mailbox
  1024. LEFT OUTER JOIN grouped_mail_aliases ga ON ga.username REGEXP CONCAT('(^|,)', mailbox.username, '($|,)')
  1025. LEFT OUTER JOIN grouped_domain_alias_address gda ON gda.username = mailbox.username
  1026. LEFT OUTER JOIN grouped_sender_acl_external external_acl ON external_acl.username = mailbox.username
  1027. WHERE
  1028. mailbox.active = '1'";
  1029. if ($mailbox_exists) {
  1030. $query .= " AND mailbox.username = :mailbox";
  1031. $stmt = $pdo->prepare($query);
  1032. $stmt->execute(array(':mailbox' => $mailbox));
  1033. } else {
  1034. $query .= " GROUP BY mailbox.username";
  1035. $stmt = $pdo->query($query);
  1036. }
  1037. $stmt = $pdo->query("DELETE FROM _sogo_static_view WHERE `c_uid` NOT IN (SELECT `username` FROM `mailbox` WHERE `active` = '1');");
  1038. flush_memcached();
  1039. }
  1040. function edit_user_account($_data) {
  1041. global $lang;
  1042. global $pdo;
  1043. $_data_log = $_data;
  1044. !isset($_data_log['user_new_pass']) ?: $_data_log['user_new_pass'] = '*';
  1045. !isset($_data_log['user_new_pass2']) ?: $_data_log['user_new_pass2'] = '*';
  1046. !isset($_data_log['user_old_pass']) ?: $_data_log['user_old_pass'] = '*';
  1047. $username = (!empty($_data['username'])) ? $_data['username'] : $_SESSION['mailcow_cc_username'];
  1048. $role = (!empty($_data['role'])) ? $_data['role'] : $_SESSION['mailcow_cc_role'];
  1049. $password_old = $_data['user_old_pass'];
  1050. $skip_old_password_check = $_data['skip_old_password_check'];
  1051. $pw_recovery_email = $_data['pw_recovery_email'];
  1052. if (filter_var($username, FILTER_VALIDATE_EMAIL === false) || $role != 'user') {
  1053. $_SESSION['return'][] = array(
  1054. 'type' => 'danger',
  1055. 'log' => array(__FUNCTION__, $_data_log),
  1056. 'msg' => 'access_denied'
  1057. );
  1058. return false;
  1059. }
  1060. // edit password
  1061. if ((!empty($password_old) || $skip_old_password_check) && !empty($_data['user_new_pass']) && !empty($_data['user_new_pass2'])) {
  1062. if (!$skip_old_password_check) {
  1063. $stmt = $pdo->prepare("SELECT `password` FROM `mailbox`
  1064. WHERE `kind` NOT REGEXP 'location|thing|group'
  1065. AND `username` = :user");
  1066. $stmt->execute(array(':user' => $username));
  1067. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1068. if (!verify_hash($row['password'], $password_old)) {
  1069. $_SESSION['return'][] = array(
  1070. 'type' => 'danger',
  1071. 'log' => array(__FUNCTION__, $_data_log),
  1072. 'msg' => 'access_denied'
  1073. );
  1074. return false;
  1075. }
  1076. }
  1077. $password_new = $_data['user_new_pass'];
  1078. $password_new2 = $_data['user_new_pass2'];
  1079. if (password_check($password_new, $password_new2) !== true) {
  1080. return false;
  1081. }
  1082. $password_hashed = hash_password($password_new);
  1083. $stmt = $pdo->prepare("UPDATE `mailbox` SET `password` = :password_hashed,
  1084. `attributes` = JSON_SET(`attributes`, '$.force_pw_update', '0'),
  1085. `attributes` = JSON_SET(`attributes`, '$.passwd_update', NOW())
  1086. WHERE `username` = :username");
  1087. $stmt->execute(array(
  1088. ':password_hashed' => $password_hashed,
  1089. ':username' => $username
  1090. ));
  1091. update_sogo_static_view();
  1092. }
  1093. // edit password recovery email
  1094. elseif (isset($pw_recovery_email)) {
  1095. if (!isset($_SESSION['acl']['pw_reset']) || $_SESSION['acl']['pw_reset'] != "1" ) {
  1096. $_SESSION['return'][] = array(
  1097. 'type' => 'danger',
  1098. 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),
  1099. 'msg' => 'access_denied'
  1100. );
  1101. return false;
  1102. }
  1103. $pw_recovery_email = (!filter_var($pw_recovery_email, FILTER_VALIDATE_EMAIL)) ? '' : $pw_recovery_email;
  1104. $stmt = $pdo->prepare("UPDATE `mailbox` SET `attributes` = JSON_SET(`attributes`, '$.recovery_email', :recovery_email)
  1105. WHERE `username` = :username");
  1106. $stmt->execute(array(
  1107. ':recovery_email' => $pw_recovery_email,
  1108. ':username' => $username
  1109. ));
  1110. }
  1111. $_SESSION['return'][] = array(
  1112. 'type' => 'success',
  1113. 'log' => array(__FUNCTION__, $_data_log),
  1114. 'msg' => array('mailbox_modified', htmlspecialchars($username))
  1115. );
  1116. return true;
  1117. }
  1118. function user_get_alias_details($username) {
  1119. global $pdo;
  1120. global $lang;
  1121. $data['direct_aliases'] = array();
  1122. $data['shared_aliases'] = array();
  1123. if ($_SESSION['mailcow_cc_role'] == "user") {
  1124. $username = $_SESSION['mailcow_cc_username'];
  1125. }
  1126. if (!filter_var($username, FILTER_VALIDATE_EMAIL)) {
  1127. return false;
  1128. }
  1129. if (!hasMailboxObjectAccess($username, $_SESSION['mailcow_cc_role'], $username)) {
  1130. return false;
  1131. }
  1132. $data['address'] = $username;
  1133. $stmt = $pdo->prepare("SELECT `address` AS `shared_aliases`, `public_comment` FROM `alias`
  1134. WHERE `goto` REGEXP :username_goto
  1135. AND `address` NOT LIKE '@%'
  1136. AND `goto` != :username_goto2
  1137. AND `address` != :username_address");
  1138. $stmt->execute(array(
  1139. ':username_goto' => '(^|,)'.$username.'($|,)',
  1140. ':username_goto2' => $username,
  1141. ':username_address' => $username
  1142. ));
  1143. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1144. while ($row = array_shift($run)) {
  1145. $data['shared_aliases'][$row['shared_aliases']]['public_comment'] = htmlspecialchars($row['public_comment']);
  1146. //$data['shared_aliases'][] = $row['shared_aliases'];
  1147. }
  1148. $stmt = $pdo->prepare("SELECT `address` AS `direct_aliases`, `public_comment` FROM `alias`
  1149. WHERE `goto` = :username_goto
  1150. AND `address` NOT LIKE '@%'
  1151. AND `address` != :username_address");
  1152. $stmt->execute(
  1153. array(
  1154. ':username_goto' => $username,
  1155. ':username_address' => $username
  1156. ));
  1157. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1158. while ($row = array_shift($run)) {
  1159. $data['direct_aliases'][$row['direct_aliases']]['public_comment'] = htmlspecialchars($row['public_comment']);
  1160. }
  1161. $stmt = $pdo->prepare("SELECT CONCAT(local_part, '@', alias_domain) AS `ad_alias`, `alias_domain` FROM `mailbox`
  1162. LEFT OUTER JOIN `alias_domain` on `target_domain` = `domain`
  1163. WHERE `username` = :username ;");
  1164. $stmt->execute(array(':username' => $username));
  1165. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1166. while ($row = array_shift($run)) {
  1167. if (empty($row['ad_alias'])) {
  1168. continue;
  1169. }
  1170. $data['direct_aliases'][$row['ad_alias']]['public_comment'] = $lang['add']['alias_domain'];
  1171. $data['alias_domains'][] = $row['alias_domain'];
  1172. }
  1173. $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 '@%';");
  1174. $stmt->execute(array(':username' => $username));
  1175. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1176. while ($row = array_shift($run)) {
  1177. $data['aliases_also_send_as'] = $row['send_as'];
  1178. }
  1179. $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 '@%';");
  1180. $stmt->execute(array(':username' => $username));
  1181. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1182. while ($row = array_shift($run)) {
  1183. $data['aliases_send_as_all'] = $row['send_as'];
  1184. }
  1185. $stmt = $pdo->prepare("SELECT IFNULL(GROUP_CONCAT(`address` SEPARATOR ', '), '') as `address` FROM `alias` WHERE `goto` REGEXP :username AND `address` LIKE '@%';");
  1186. $stmt->execute(array(':username' => '(^|,)'.$username.'($|,)'));
  1187. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1188. while ($row = array_shift($run)) {
  1189. $data['is_catch_all'] = $row['address'];
  1190. }
  1191. return $data;
  1192. }
  1193. function is_valid_domain_name($domain_name) {
  1194. if (empty($domain_name)) {
  1195. return false;
  1196. }
  1197. $domain_name = idn_to_ascii($domain_name, 0, INTL_IDNA_VARIANT_UTS46);
  1198. return (preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $domain_name)
  1199. && preg_match("/^.{1,253}$/", $domain_name)
  1200. && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $domain_name));
  1201. }
  1202. function set_tfa($_data) {
  1203. global $pdo;
  1204. global $yubi;
  1205. global $tfa;
  1206. $_data_log = $_data;
  1207. $access_denied = null;
  1208. !isset($_data_log['confirm_password']) ?: $_data_log['confirm_password'] = '*';
  1209. $username = $_SESSION['mailcow_cc_username'];
  1210. // check for empty user and role
  1211. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) $access_denied = true;
  1212. // check admin confirm password
  1213. if ($access_denied === null) {
  1214. $stmt = $pdo->prepare("SELECT `password` FROM `admin`
  1215. WHERE `username` = :username");
  1216. $stmt->execute(array(':username' => $username));
  1217. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1218. if ($row) {
  1219. if (!verify_hash($row['password'], $_data["confirm_password"])) $access_denied = true;
  1220. else $access_denied = false;
  1221. }
  1222. }
  1223. // check mailbox confirm password
  1224. if ($access_denied === null) {
  1225. $stmt = $pdo->prepare("SELECT `password` FROM `mailbox`
  1226. WHERE `username` = :username");
  1227. $stmt->execute(array(':username' => $username));
  1228. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1229. if ($row) {
  1230. if (!verify_hash($row['password'], $_data["confirm_password"])) $access_denied = true;
  1231. else $access_denied = false;
  1232. }
  1233. }
  1234. // set access_denied error
  1235. if ($access_denied){
  1236. $_SESSION['return'][] = array(
  1237. 'type' => 'danger',
  1238. 'log' => array(__FUNCTION__, $_data_log),
  1239. 'msg' => 'access_denied'
  1240. );
  1241. return false;
  1242. }
  1243. switch ($_data["tfa_method"]) {
  1244. case "yubi_otp":
  1245. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  1246. $yubico_id = $_data['yubico_id'];
  1247. $yubico_key = $_data['yubico_key'];
  1248. $yubi = new Auth_Yubico($yubico_id, $yubico_key);
  1249. if (!$yubi) {
  1250. $_SESSION['return'][] = array(
  1251. 'type' => 'danger',
  1252. 'log' => array(__FUNCTION__, $_data_log),
  1253. 'msg' => 'access_denied'
  1254. );
  1255. return false;
  1256. }
  1257. if (!ctype_alnum($_data["otp_token"]) || strlen($_data["otp_token"]) != 44) {
  1258. $_SESSION['return'][] = array(
  1259. 'type' => 'danger',
  1260. 'log' => array(__FUNCTION__, $_data_log),
  1261. 'msg' => 'tfa_token_invalid'
  1262. );
  1263. return false;
  1264. }
  1265. $yauth = $yubi->verify($_data["otp_token"]);
  1266. if (PEAR::isError($yauth)) {
  1267. $_SESSION['return'][] = array(
  1268. 'type' => 'danger',
  1269. 'log' => array(__FUNCTION__, $_data_log),
  1270. 'msg' => array('yotp_verification_failed', $yauth->getMessage())
  1271. );
  1272. return false;
  1273. }
  1274. try {
  1275. // We could also do a modhex translation here
  1276. $yubico_modhex_id = substr($_data["otp_token"], 0, 12);
  1277. $stmt = $pdo->prepare("DELETE FROM `tfa`
  1278. WHERE `username` = :username
  1279. AND (`authmech` = 'yubi_otp' AND `secret` LIKE :modhex)");
  1280. $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id));
  1281. $stmt = $pdo->prepare("INSERT INTO `tfa` (`key_id`, `username`, `authmech`, `active`, `secret`) VALUES
  1282. (:key_id, :username, 'yubi_otp', '1', :secret)");
  1283. $stmt->execute(array(':key_id' => $key_id, ':username' => $username, ':secret' => $yubico_id . ':' . $yubico_key . ':' . $yubico_modhex_id));
  1284. }
  1285. catch (PDOException $e) {
  1286. $_SESSION['return'][] = array(
  1287. 'type' => 'danger',
  1288. 'log' => array(__FUNCTION__, $_data_log),
  1289. 'msg' => array('mysql_error', $e)
  1290. );
  1291. return false;
  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. case "totp":
  1300. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  1301. if ($tfa->verifyCode($_POST['totp_secret'], $_POST['totp_confirm_token']) === true) {
  1302. //$stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
  1303. //$stmt->execute(array(':username' => $username));
  1304. $stmt = $pdo->prepare("INSERT INTO `tfa` (`username`, `key_id`, `authmech`, `secret`, `active`) VALUES (?, ?, 'totp', ?, '1')");
  1305. $stmt->execute(array($username, $key_id, $_POST['totp_secret']));
  1306. $_SESSION['return'][] = array(
  1307. 'type' => 'success',
  1308. 'log' => array(__FUNCTION__, $_data_log),
  1309. 'msg' => array('object_modified', $username)
  1310. );
  1311. }
  1312. else {
  1313. $_SESSION['return'][] = array(
  1314. 'type' => 'danger',
  1315. 'log' => array(__FUNCTION__, $_data_log),
  1316. 'msg' => 'totp_verification_failed'
  1317. );
  1318. }
  1319. break;
  1320. case "webauthn":
  1321. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  1322. $stmt = $pdo->prepare("INSERT INTO `tfa` (`username`, `key_id`, `authmech`, `keyHandle`, `publicKey`, `certificate`, `counter`, `active`)
  1323. VALUES (?, ?, 'webauthn', ?, ?, ?, ?, '1')");
  1324. $stmt->execute(array(
  1325. $username,
  1326. $key_id,
  1327. base64_encode($_data['registration']->credentialId),
  1328. $_data['registration']->credentialPublicKey,
  1329. $_data['registration']->certificate,
  1330. 0
  1331. ));
  1332. $_SESSION['return'][] = array(
  1333. 'type' => 'success',
  1334. 'log' => array(__FUNCTION__, $_data_log),
  1335. 'msg' => array('object_modified', $username)
  1336. );
  1337. break;
  1338. case "none":
  1339. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
  1340. $stmt->execute(array(':username' => $username));
  1341. $_SESSION['return'][] = array(
  1342. 'type' => 'success',
  1343. 'log' => array(__FUNCTION__, $_data_log),
  1344. 'msg' => array('object_modified', htmlspecialchars($username))
  1345. );
  1346. break;
  1347. }
  1348. }
  1349. function fido2($_data) {
  1350. global $pdo;
  1351. $_data_log = $_data;
  1352. // Not logging registration data, only actions
  1353. // Silent errors for "get" requests
  1354. switch ($_data["action"]) {
  1355. case "register":
  1356. $username = $_SESSION['mailcow_cc_username'];
  1357. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1358. $_SESSION['return'][] = array(
  1359. 'type' => 'danger',
  1360. 'log' => array(__FUNCTION__, $_data["action"]),
  1361. 'msg' => 'access_denied'
  1362. );
  1363. return false;
  1364. }
  1365. $stmt = $pdo->prepare("INSERT INTO `fido2` (`username`, `rpId`, `credentialPublicKey`, `certificateChain`, `certificate`, `certificateIssuer`, `certificateSubject`, `signatureCounter`, `AAGUID`, `credentialId`)
  1366. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
  1367. $stmt->execute(array(
  1368. $username,
  1369. $_data['registration']->rpId,
  1370. $_data['registration']->credentialPublicKey,
  1371. $_data['registration']->certificateChain,
  1372. $_data['registration']->certificate,
  1373. $_data['registration']->certificateIssuer,
  1374. $_data['registration']->certificateSubject,
  1375. $_data['registration']->signatureCounter,
  1376. $_data['registration']->AAGUID,
  1377. $_data['registration']->credentialId)
  1378. );
  1379. $_SESSION['return'][] = array(
  1380. 'type' => 'success',
  1381. 'log' => array(__FUNCTION__, $_data["action"]),
  1382. 'msg' => array('object_modified', $username)
  1383. );
  1384. break;
  1385. case "get_user_cids":
  1386. // Used to exclude existing CredentialIds while registering
  1387. $username = $_SESSION['mailcow_cc_username'];
  1388. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1389. return false;
  1390. }
  1391. $stmt = $pdo->prepare("SELECT `credentialId` FROM `fido2` WHERE `username` = :username");
  1392. $stmt->execute(array(':username' => $username));
  1393. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1394. while($row = array_shift($rows)) {
  1395. $cids[] = $row['credentialId'];
  1396. }
  1397. return $cids;
  1398. break;
  1399. case "get_all_cids":
  1400. // Only needed when using fido2 with username
  1401. $stmt = $pdo->query("SELECT `credentialId` FROM `fido2`");
  1402. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1403. while($row = array_shift($rows)) {
  1404. $cids[] = $row['credentialId'];
  1405. }
  1406. return $cids;
  1407. break;
  1408. case "get_by_b64cid":
  1409. if (!isset($_data['cid']) || empty($_data['cid'])) {
  1410. return false;
  1411. }
  1412. $stmt = $pdo->prepare("SELECT `certificateSubject`, `username`, `credentialPublicKey`, SHA2(`credentialId`, 256) AS `cid` FROM `fido2` WHERE `credentialId` = :cid");
  1413. $stmt->execute(array(':cid' => base64_decode($_data['cid'])));
  1414. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1415. if (empty($row) || empty($row['credentialPublicKey']) || empty($row['username'])) {
  1416. return false;
  1417. }
  1418. $data['pub_key'] = $row['credentialPublicKey'];
  1419. $data['username'] = $row['username'];
  1420. $data['subject'] = $row['certificateSubject'];
  1421. $data['cid'] = $row['cid'];
  1422. return $data;
  1423. break;
  1424. case "get_friendly_names":
  1425. $username = $_SESSION['mailcow_cc_username'];
  1426. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1427. return false;
  1428. }
  1429. $stmt = $pdo->prepare("SELECT SHA2(`credentialId`, 256) AS `cid`, `created`, `certificateSubject`, `friendlyName` FROM `fido2` WHERE `username` = :username");
  1430. $stmt->execute(array(':username' => $username));
  1431. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1432. while($row = array_shift($rows)) {
  1433. $fns[] = array(
  1434. "subject" => (empty($row['certificateSubject']) ? 'Unknown (' . $row['created'] . ')' : $row['certificateSubject']),
  1435. "fn" => $row['friendlyName'],
  1436. "cid" => $row['cid']
  1437. );
  1438. }
  1439. return $fns;
  1440. break;
  1441. case "unset_fido2_key":
  1442. $username = $_SESSION['mailcow_cc_username'];
  1443. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1444. $_SESSION['return'][] = array(
  1445. 'type' => 'danger',
  1446. 'log' => array(__FUNCTION__, $_data["action"]),
  1447. 'msg' => 'access_denied'
  1448. );
  1449. return false;
  1450. }
  1451. $stmt = $pdo->prepare("DELETE FROM `fido2` WHERE `username` = :username AND SHA2(`credentialId`, 256) = :cid");
  1452. $stmt->execute(array(
  1453. ':username' => $username,
  1454. ':cid' => $_data['post_data']['unset_fido2_key']
  1455. ));
  1456. $_SESSION['return'][] = array(
  1457. 'type' => 'success',
  1458. 'log' => array(__FUNCTION__, $_data_log),
  1459. 'msg' => array('object_modified', htmlspecialchars($username))
  1460. );
  1461. break;
  1462. case "edit_fn":
  1463. $username = $_SESSION['mailcow_cc_username'];
  1464. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1465. $_SESSION['return'][] = array(
  1466. 'type' => 'danger',
  1467. 'log' => array(__FUNCTION__, $_data["action"]),
  1468. 'msg' => 'access_denied'
  1469. );
  1470. return false;
  1471. }
  1472. $stmt = $pdo->prepare("UPDATE `fido2` SET `friendlyName` = :friendlyName WHERE SHA2(`credentialId`, 256) = :cid AND `username` = :username");
  1473. $stmt->execute(array(
  1474. ':username' => $username,
  1475. ':friendlyName' => $_data['fido2_attrs']['fido2_fn'],
  1476. ':cid' => $_data['fido2_attrs']['fido2_cid']
  1477. ));
  1478. $_SESSION['return'][] = array(
  1479. 'type' => 'success',
  1480. 'log' => array(__FUNCTION__, $_data_log),
  1481. 'msg' => array('object_modified', htmlspecialchars($username))
  1482. );
  1483. break;
  1484. }
  1485. }
  1486. function unset_tfa_key($_data) {
  1487. // Can only unset own keys
  1488. // Needs at least one key left
  1489. global $pdo;
  1490. global $lang;
  1491. $_data_log = $_data;
  1492. $access_denied = null;
  1493. $id = intval($_data['unset_tfa_key']);
  1494. $username = $_SESSION['mailcow_cc_username'];
  1495. // check for empty user and role
  1496. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) $access_denied = true;
  1497. try {
  1498. if (!is_numeric($id)) $access_denied = true;
  1499. // set access_denied error
  1500. if ($access_denied){
  1501. $_SESSION['return'][] = array(
  1502. 'type' => 'danger',
  1503. 'log' => array(__FUNCTION__, $_data_log),
  1504. 'msg' => 'access_denied'
  1505. );
  1506. return false;
  1507. }
  1508. // check if it's last key
  1509. $stmt = $pdo->prepare("SELECT COUNT(*) AS `keys` FROM `tfa`
  1510. WHERE `username` = :username AND `active` = '1'");
  1511. $stmt->execute(array(':username' => $username));
  1512. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1513. if ($row['keys'] == "1") {
  1514. $_SESSION['return'][] = array(
  1515. 'type' => 'danger',
  1516. 'log' => array(__FUNCTION__, $_data_log),
  1517. 'msg' => 'last_key'
  1518. );
  1519. return false;
  1520. }
  1521. // delete key
  1522. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username AND `id` = :id");
  1523. $stmt->execute(array(':username' => $username, ':id' => $id));
  1524. $_SESSION['return'][] = array(
  1525. 'type' => 'success',
  1526. 'log' => array(__FUNCTION__, $_data_log),
  1527. 'msg' => array('object_modified', $username)
  1528. );
  1529. }
  1530. catch (PDOException $e) {
  1531. $_SESSION['return'][] = array(
  1532. 'type' => 'danger',
  1533. 'log' => array(__FUNCTION__, $_data_log),
  1534. 'msg' => array('mysql_error', $e)
  1535. );
  1536. return false;
  1537. }
  1538. }
  1539. function get_tfa($username = null, $id = null) {
  1540. global $pdo;
  1541. if (empty($username) && isset($_SESSION['mailcow_cc_username'])) {
  1542. $username = $_SESSION['mailcow_cc_username'];
  1543. }
  1544. elseif (empty($username)) {
  1545. return false;
  1546. }
  1547. if (!isset($id)){
  1548. // fetch all tfa methods - just get information about possible authenticators
  1549. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `authmech` FROM `tfa`
  1550. WHERE `username` = :username AND `active` = '1'");
  1551. $stmt->execute(array(':username' => $username));
  1552. $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1553. // no tfa methods found
  1554. if (count($results) == 0) {
  1555. $data['name'] = 'none';
  1556. $data['pretty'] = "-";
  1557. $data['additional'] = array();
  1558. return $data;
  1559. }
  1560. $data['additional'] = $results;
  1561. return $data;
  1562. } else {
  1563. // fetch specific authenticator details by id
  1564. $stmt = $pdo->prepare("SELECT * FROM `tfa`
  1565. WHERE `username` = :username AND `id` = :id AND `active` = '1'");
  1566. $stmt->execute(array(':username' => $username, ':id' => $id));
  1567. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1568. if (isset($row["authmech"])) {
  1569. switch ($row["authmech"]) {
  1570. case "yubi_otp":
  1571. $data['name'] = "yubi_otp";
  1572. $data['pretty'] = "Yubico OTP";
  1573. $stmt = $pdo->prepare("SELECT `id`, `key_id`, RIGHT(`secret`, 12) AS 'modhex' FROM `tfa` WHERE `authmech` = 'yubi_otp' AND `username` = :username AND `id` = :id");
  1574. $stmt->execute(array(
  1575. ':username' => $username,
  1576. ':id' => $id
  1577. ));
  1578. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1579. while($row = array_shift($rows)) {
  1580. $data['additional'][] = $row;
  1581. }
  1582. return $data;
  1583. break;
  1584. // u2f - deprecated, should be removed
  1585. case "u2f":
  1586. $data['name'] = "u2f";
  1587. $data['pretty'] = "Fido U2F";
  1588. $stmt = $pdo->prepare("SELECT `id`, `key_id` FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username AND `id` = :id");
  1589. $stmt->execute(array(
  1590. ':username' => $username,
  1591. ':id' => $id
  1592. ));
  1593. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1594. while($row = array_shift($rows)) {
  1595. $data['additional'][] = $row;
  1596. }
  1597. return $data;
  1598. break;
  1599. case "hotp":
  1600. $data['name'] = "hotp";
  1601. $data['pretty'] = "HMAC-based OTP";
  1602. return $data;
  1603. break;
  1604. case "totp":
  1605. $data['name'] = "totp";
  1606. $data['pretty'] = "Time-based OTP";
  1607. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `secret` FROM `tfa` WHERE `authmech` = 'totp' AND `username` = :username AND `id` = :id");
  1608. $stmt->execute(array(
  1609. ':username' => $username,
  1610. ':id' => $id
  1611. ));
  1612. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1613. while($row = array_shift($rows)) {
  1614. $data['additional'][] = $row;
  1615. }
  1616. return $data;
  1617. break;
  1618. case "webauthn":
  1619. $data['name'] = "webauthn";
  1620. $data['pretty'] = "WebAuthn";
  1621. $stmt = $pdo->prepare("SELECT `id`, `key_id` FROM `tfa` WHERE `authmech` = 'webauthn' AND `username` = :username AND `id` = :id");
  1622. $stmt->execute(array(
  1623. ':username' => $username,
  1624. ':id' => $id
  1625. ));
  1626. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1627. while($row = array_shift($rows)) {
  1628. $data['additional'][] = $row;
  1629. }
  1630. return $data;
  1631. break;
  1632. default:
  1633. $data['name'] = 'none';
  1634. $data['pretty'] = "-";
  1635. return $data;
  1636. break;
  1637. }
  1638. }
  1639. else {
  1640. $data['name'] = 'none';
  1641. $data['pretty'] = "-";
  1642. return $data;
  1643. }
  1644. }
  1645. }
  1646. function verify_tfa_login($username, $_data) {
  1647. global $pdo;
  1648. global $yubi;
  1649. global $u2f;
  1650. global $tfa;
  1651. global $WebAuthn;
  1652. if ($_data['tfa_method'] != 'u2f'){
  1653. switch ($_data["tfa_method"]) {
  1654. case "yubi_otp":
  1655. if (!ctype_alnum($_data['token']) || strlen($_data['token']) != 44) {
  1656. $_SESSION['return'][] = array(
  1657. 'type' => 'danger',
  1658. 'log' => array(__FUNCTION__, $username, '*'),
  1659. 'msg' => array('yotp_verification_failed', 'token length error')
  1660. );
  1661. return false;
  1662. }
  1663. $yubico_modhex_id = substr($_data['token'], 0, 12);
  1664. $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
  1665. WHERE `username` = :username
  1666. AND `authmech` = 'yubi_otp'
  1667. AND `active` = '1'
  1668. AND `secret` LIKE :modhex");
  1669. $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id));
  1670. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1671. $yubico_auth = explode(':', $row['secret']);
  1672. $yubi = new Auth_Yubico($yubico_auth[0], $yubico_auth[1]);
  1673. $yauth = $yubi->verify($_data['token']);
  1674. if (PEAR::isError($yauth)) {
  1675. $_SESSION['return'][] = array(
  1676. 'type' => 'danger',
  1677. 'log' => array(__FUNCTION__, $username, '*'),
  1678. 'msg' => array('yotp_verification_failed', $yauth->getMessage())
  1679. );
  1680. return false;
  1681. }
  1682. else {
  1683. $_SESSION['tfa_id'] = $row['id'];
  1684. $_SESSION['return'][] = array(
  1685. 'type' => 'success',
  1686. 'log' => array(__FUNCTION__, $username, '*'),
  1687. 'msg' => 'verified_yotp_login'
  1688. );
  1689. return true;
  1690. }
  1691. $_SESSION['return'][] = array(
  1692. 'type' => 'danger',
  1693. 'log' => array(__FUNCTION__, $username, '*'),
  1694. 'msg' => array('yotp_verification_failed', 'unknown')
  1695. );
  1696. return false;
  1697. break;
  1698. case "hotp":
  1699. return false;
  1700. break;
  1701. case "totp":
  1702. try {
  1703. $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
  1704. WHERE `username` = :username
  1705. AND `authmech` = 'totp'
  1706. AND `id` = :id
  1707. AND `active`='1'");
  1708. $stmt->execute(array(':username' => $username, ':id' => $_data['id']));
  1709. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1710. foreach ($rows as $row) {
  1711. if ($tfa->verifyCode($row['secret'], $_data['token']) === true) {
  1712. $_SESSION['tfa_id'] = $row['id'];
  1713. $_SESSION['return'][] = array(
  1714. 'type' => 'success',
  1715. 'log' => array(__FUNCTION__, $username, '*'),
  1716. 'msg' => 'verified_totp_login'
  1717. );
  1718. return true;
  1719. }
  1720. }
  1721. $_SESSION['return'][] = array(
  1722. 'type' => 'danger',
  1723. 'log' => array(__FUNCTION__, $username, '*'),
  1724. 'msg' => 'totp_verification_failed'
  1725. );
  1726. return false;
  1727. }
  1728. catch (PDOException $e) {
  1729. $_SESSION['return'][] = array(
  1730. 'type' => 'danger',
  1731. 'log' => array(__FUNCTION__, $username, '*'),
  1732. 'msg' => array('mysql_error', $e)
  1733. );
  1734. return false;
  1735. }
  1736. break;
  1737. case "webauthn":
  1738. $tokenData = json_decode($_data['token']);
  1739. $clientDataJSON = base64_decode($tokenData->clientDataJSON);
  1740. $authenticatorData = base64_decode($tokenData->authenticatorData);
  1741. $signature = base64_decode($tokenData->signature);
  1742. $id = base64_decode($tokenData->id);
  1743. $challenge = $_SESSION['challenge'];
  1744. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `keyHandle`, `username`, `publicKey` FROM `tfa` WHERE `id` = :id AND `active`='1'");
  1745. $stmt->execute(array(':id' => $_data['id']));
  1746. $process_webauthn = $stmt->fetch(PDO::FETCH_ASSOC);
  1747. if (empty($process_webauthn)){
  1748. $_SESSION['return'][] = array(
  1749. 'type' => 'danger',
  1750. 'log' => array(__FUNCTION__, $username, '*'),
  1751. 'msg' => array('webauthn_authenticator_failed')
  1752. );
  1753. return false;
  1754. }
  1755. if (empty($process_webauthn['publicKey']) || $process_webauthn['publicKey'] === false) {
  1756. $_SESSION['return'][] = array(
  1757. 'type' => 'danger',
  1758. 'log' => array(__FUNCTION__, $username, '*'),
  1759. 'msg' => array('webauthn_publickey_failed')
  1760. );
  1761. return false;
  1762. }
  1763. if ($process_webauthn['username'] != $_SESSION['pending_mailcow_cc_username']){
  1764. $_SESSION['return'][] = array(
  1765. 'type' => 'danger',
  1766. 'log' => array(__FUNCTION__, $username, '*'),
  1767. 'msg' => array('webauthn_username_failed')
  1768. );
  1769. return false;
  1770. }
  1771. try {
  1772. $WebAuthn->processGet($clientDataJSON, $authenticatorData, $signature, $process_webauthn['publicKey'], $challenge, null, $GLOBALS['WEBAUTHN_UV_FLAG_LOGIN'], $GLOBALS['WEBAUTHN_USER_PRESENT_FLAG']);
  1773. }
  1774. catch (Throwable $ex) {
  1775. $_SESSION['return'][] = array(
  1776. 'type' => 'danger',
  1777. 'log' => array(__FUNCTION__, $username, '*'),
  1778. 'msg' => array('webauthn_verification_failed', $ex->getMessage())
  1779. );
  1780. return false;
  1781. }
  1782. $stmt = $pdo->prepare("SELECT `superadmin` FROM `admin` WHERE `username` = :username");
  1783. $stmt->execute(array(':username' => $process_webauthn['username']));
  1784. $obj_props = $stmt->fetch(PDO::FETCH_ASSOC);
  1785. if ($obj_props['superadmin'] === 1) {
  1786. $_SESSION["mailcow_cc_role"] = "admin";
  1787. }
  1788. elseif ($obj_props['superadmin'] === 0) {
  1789. $_SESSION["mailcow_cc_role"] = "domainadmin";
  1790. }
  1791. else {
  1792. $stmt = $pdo->prepare("SELECT `username` FROM `mailbox` WHERE `username` = :username");
  1793. $stmt->execute(array(':username' => $process_webauthn['username']));
  1794. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1795. if (!empty($row['username'])) {
  1796. $_SESSION["mailcow_cc_role"] = "user";
  1797. } else {
  1798. $_SESSION['return'][] = array(
  1799. 'type' => 'danger',
  1800. 'log' => array(__FUNCTION__, $username, '*'),
  1801. 'msg' => array('webauthn_role_failed')
  1802. );
  1803. return false;
  1804. }
  1805. }
  1806. $_SESSION["mailcow_cc_username"] = $process_webauthn['username'];
  1807. $_SESSION['tfa_id'] = $process_webauthn['id'];
  1808. $_SESSION['authReq'] = null;
  1809. unset($_SESSION["challenge"]);
  1810. $_SESSION['return'][] = array(
  1811. 'type' => 'success',
  1812. 'log' => array("webauthn_login"),
  1813. 'msg' => array('logged_in_as', $process_webauthn['username'])
  1814. );
  1815. return true;
  1816. break;
  1817. default:
  1818. $_SESSION['return'][] = array(
  1819. 'type' => 'danger',
  1820. 'log' => array(__FUNCTION__, $username, '*'),
  1821. 'msg' => 'unknown_tfa_method'
  1822. );
  1823. return false;
  1824. break;
  1825. }
  1826. return false;
  1827. } else {
  1828. // delete old keys that used u2f
  1829. $stmt = $pdo->prepare("SELECT * FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username");
  1830. $stmt->execute(array(':username' => $username));
  1831. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1832. if (count($rows) == 0) return false;
  1833. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username");
  1834. $stmt->execute(array(':username' => $username));
  1835. return true;
  1836. }
  1837. }
  1838. function admin_api($access, $action, $data = null) {
  1839. global $pdo;
  1840. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1841. $_SESSION['return'][] = array(
  1842. 'type' => 'danger',
  1843. 'log' => array(__FUNCTION__),
  1844. 'msg' => 'access_denied'
  1845. );
  1846. return false;
  1847. }
  1848. if ($access !== "ro" && $access !== "rw") {
  1849. $_SESSION['return'][] = array(
  1850. 'type' => 'danger',
  1851. 'log' => array(__FUNCTION__),
  1852. 'msg' => 'invalid access type'
  1853. );
  1854. return false;
  1855. }
  1856. if ($action == "edit") {
  1857. $active = (!empty($data['active'])) ? 1 : 0;
  1858. $skip_ip_check = (isset($data['skip_ip_check'])) ? 1 : 0;
  1859. $allow_from = array();
  1860. if (isset($data['allow_from'])) {
  1861. $allow_from = array_map('trim', preg_split( "/( |,|;|\n)/", $data['allow_from']));
  1862. }
  1863. foreach ($allow_from as $key => $val) {
  1864. if (empty($val)) {
  1865. unset($allow_from[$key]);
  1866. continue;
  1867. }
  1868. if (valid_network($val) !== true) {
  1869. $_SESSION['return'][] = array(
  1870. 'type' => 'warning',
  1871. 'log' => array(__FUNCTION__, $data),
  1872. 'msg' => array('ip_invalid', htmlspecialchars($allow_from[$key]))
  1873. );
  1874. unset($allow_from[$key]);
  1875. continue;
  1876. }
  1877. }
  1878. $allow_from = implode(',', array_unique(array_filter($allow_from)));
  1879. if (empty($allow_from) && $skip_ip_check == 0) {
  1880. $_SESSION['return'][] = array(
  1881. 'type' => 'danger',
  1882. 'log' => array(__FUNCTION__, $data),
  1883. 'msg' => 'ip_list_empty'
  1884. );
  1885. return false;
  1886. }
  1887. $api_key = implode('-', array(
  1888. strtoupper(bin2hex(random_bytes(3))),
  1889. strtoupper(bin2hex(random_bytes(3))),
  1890. strtoupper(bin2hex(random_bytes(3))),
  1891. strtoupper(bin2hex(random_bytes(3))),
  1892. strtoupper(bin2hex(random_bytes(3)))
  1893. ));
  1894. $stmt = $pdo->query("SELECT `api_key` FROM `api` WHERE `access` = '" . $access . "'");
  1895. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  1896. if (empty($num_results)) {
  1897. $stmt = $pdo->prepare("INSERT INTO `api` (`api_key`, `skip_ip_check`, `active`, `allow_from`, `access`)
  1898. VALUES (:api_key, :skip_ip_check, :active, :allow_from, :access);");
  1899. $stmt->execute(array(
  1900. ':api_key' => $api_key,
  1901. ':skip_ip_check' => $skip_ip_check,
  1902. ':active' => $active,
  1903. ':allow_from' => $allow_from,
  1904. ':access' => $access
  1905. ));
  1906. }
  1907. else {
  1908. if ($skip_ip_check == 0) {
  1909. $stmt = $pdo->prepare("UPDATE `api` SET `skip_ip_check` = :skip_ip_check,
  1910. `active` = :active,
  1911. `allow_from` = :allow_from
  1912. WHERE `access` = :access;");
  1913. $stmt->execute(array(
  1914. ':active' => $active,
  1915. ':skip_ip_check' => $skip_ip_check,
  1916. ':allow_from' => $allow_from,
  1917. ':access' => $access
  1918. ));
  1919. }
  1920. else {
  1921. $stmt = $pdo->prepare("UPDATE `api` SET `skip_ip_check` = :skip_ip_check,
  1922. `active` = :active
  1923. WHERE `access` = :access;");
  1924. $stmt->execute(array(
  1925. ':active' => $active,
  1926. ':skip_ip_check' => $skip_ip_check,
  1927. ':access' => $access
  1928. ));
  1929. }
  1930. }
  1931. }
  1932. elseif ($action == "regen_key") {
  1933. $api_key = implode('-', array(
  1934. strtoupper(bin2hex(random_bytes(3))),
  1935. strtoupper(bin2hex(random_bytes(3))),
  1936. strtoupper(bin2hex(random_bytes(3))),
  1937. strtoupper(bin2hex(random_bytes(3))),
  1938. strtoupper(bin2hex(random_bytes(3)))
  1939. ));
  1940. $stmt = $pdo->prepare("UPDATE `api` SET `api_key` = :api_key WHERE `access` = :access");
  1941. $stmt->execute(array(
  1942. ':api_key' => $api_key,
  1943. ':access' => $access
  1944. ));
  1945. }
  1946. elseif ($action == "get") {
  1947. $stmt = $pdo->query("SELECT * FROM `api` WHERE `access` = '" . $access . "'");
  1948. $apidata = $stmt->fetch(PDO::FETCH_ASSOC);
  1949. if ($apidata !== false) {
  1950. $apidata['allow_from'] = str_replace(',', PHP_EOL, $apidata['allow_from']);
  1951. }
  1952. return $apidata;
  1953. }
  1954. $_SESSION['return'][] = array(
  1955. 'type' => 'success',
  1956. 'log' => array(__FUNCTION__, $data),
  1957. 'msg' => 'admin_api_modified'
  1958. );
  1959. }
  1960. function license($action, $data = null) {
  1961. global $pdo;
  1962. global $redis;
  1963. global $lang;
  1964. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1965. $_SESSION['return'][] = array(
  1966. 'type' => 'danger',
  1967. 'log' => array(__FUNCTION__),
  1968. 'msg' => 'access_denied'
  1969. );
  1970. return false;
  1971. }
  1972. switch ($action) {
  1973. case "verify":
  1974. // Keep result until revalidate button is pressed or session expired
  1975. $stmt = $pdo->query("SELECT `version` FROM `versions` WHERE `application` = 'GUID'");
  1976. $versions = $stmt->fetch(PDO::FETCH_ASSOC);
  1977. $post = array('guid' => $versions['version']);
  1978. $curl = curl_init('https://verify.mailcow.email');
  1979. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  1980. curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
  1981. curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
  1982. $response = curl_exec($curl);
  1983. curl_close($curl);
  1984. $json_return = json_decode($response, true);
  1985. if ($response && $json_return) {
  1986. if ($json_return['response'] === "ok") {
  1987. $_SESSION['gal']['valid'] = "true";
  1988. $_SESSION['gal']['c'] = $json_return['c'];
  1989. $_SESSION['gal']['s'] = $json_return['s'];
  1990. if ($json_return['m'] == 'NoMoore') {
  1991. $_SESSION['gal']['m'] = '🐄';
  1992. }
  1993. else {
  1994. $_SESSION['gal']['m'] = str_repeat('🐄', substr_count($json_return['m'], 'o'));
  1995. }
  1996. }
  1997. elseif ($json_return['response'] === "invalid") {
  1998. $_SESSION['gal']['valid'] = "false";
  1999. $_SESSION['gal']['c'] = $lang['mailbox']['no'];
  2000. $_SESSION['gal']['s'] = $lang['mailbox']['no'];
  2001. $_SESSION['gal']['m'] = $lang['mailbox']['no'];
  2002. }
  2003. }
  2004. else {
  2005. $_SESSION['gal']['valid'] = "false";
  2006. $_SESSION['gal']['c'] = $lang['danger']['temp_error'];
  2007. $_SESSION['gal']['s'] = $lang['danger']['temp_error'];
  2008. $_SESSION['gal']['m'] = $lang['danger']['temp_error'];
  2009. }
  2010. try {
  2011. // json_encode needs "true"/"false" instead of true/false, to not encode it to 0 or 1
  2012. $redis->Set('LICENSE_STATUS_CACHE', json_encode($_SESSION['gal']));
  2013. }
  2014. catch (RedisException $e) {
  2015. $_SESSION['return'][] = array(
  2016. 'type' => 'danger',
  2017. 'log' => array(__FUNCTION__, $_action, $_data_log),
  2018. 'msg' => array('redis_error', $e)
  2019. );
  2020. return false;
  2021. }
  2022. return $_SESSION['gal']['valid'];
  2023. break;
  2024. case "guid":
  2025. $stmt = $pdo->query("SELECT `version` FROM `versions` WHERE `application` = 'GUID'");
  2026. $versions = $stmt->fetch(PDO::FETCH_ASSOC);
  2027. return $versions['version'];
  2028. break;
  2029. }
  2030. }
  2031. function rspamd_ui($action, $data = null) {
  2032. if ($_SESSION['mailcow_cc_role'] != "admin") {
  2033. $_SESSION['return'][] = array(
  2034. 'type' => 'danger',
  2035. 'log' => array(__FUNCTION__),
  2036. 'msg' => 'access_denied'
  2037. );
  2038. return false;
  2039. }
  2040. switch ($action) {
  2041. case "edit":
  2042. $rspamd_ui_pass = $data['rspamd_ui_pass'];
  2043. $rspamd_ui_pass2 = $data['rspamd_ui_pass2'];
  2044. if (empty($rspamd_ui_pass) || empty($rspamd_ui_pass2)) {
  2045. $_SESSION['return'][] = array(
  2046. 'type' => 'danger',
  2047. 'log' => array(__FUNCTION__, '*', '*'),
  2048. 'msg' => 'password_empty'
  2049. );
  2050. return false;
  2051. }
  2052. if ($rspamd_ui_pass != $rspamd_ui_pass2) {
  2053. $_SESSION['return'][] = array(
  2054. 'type' => 'danger',
  2055. 'log' => array(__FUNCTION__, '*', '*'),
  2056. 'msg' => 'password_mismatch'
  2057. );
  2058. return false;
  2059. }
  2060. if (strlen($rspamd_ui_pass) < 6) {
  2061. $_SESSION['return'][] = array(
  2062. 'type' => 'danger',
  2063. 'log' => array(__FUNCTION__, '*', '*'),
  2064. 'msg' => 'rspamd_ui_pw_length'
  2065. );
  2066. return false;
  2067. }
  2068. $docker_return = docker('post', 'rspamd-mailcow', 'exec', array('cmd' => 'rspamd', 'task' => 'worker_password', 'raw' => $rspamd_ui_pass), array('Content-Type: application/json'));
  2069. if ($docker_return_array = json_decode($docker_return, true)) {
  2070. if ($docker_return_array['type'] == 'success') {
  2071. $_SESSION['return'][] = array(
  2072. 'type' => 'success',
  2073. 'log' => array(__FUNCTION__, '*', '*'),
  2074. 'msg' => 'rspamd_ui_pw_set'
  2075. );
  2076. return true;
  2077. }
  2078. else {
  2079. $_SESSION['return'][] = array(
  2080. 'type' => $docker_return_array['type'],
  2081. 'log' => array(__FUNCTION__, '*', '*'),
  2082. 'msg' => $docker_return_array['msg']
  2083. );
  2084. return false;
  2085. }
  2086. }
  2087. else {
  2088. $_SESSION['return'][] = array(
  2089. 'type' => 'danger',
  2090. 'log' => array(__FUNCTION__, '*', '*'),
  2091. 'msg' => 'unknown'
  2092. );
  2093. return false;
  2094. }
  2095. break;
  2096. }
  2097. }
  2098. function cors($action, $data = null) {
  2099. global $redis;
  2100. switch ($action) {
  2101. case "edit":
  2102. if ($_SESSION['mailcow_cc_role'] != "admin") {
  2103. $_SESSION['return'][] = array(
  2104. 'type' => 'danger',
  2105. 'log' => array(__FUNCTION__, $action, $data),
  2106. 'msg' => 'access_denied'
  2107. );
  2108. return false;
  2109. }
  2110. $allowed_origins = isset($data['allowed_origins']) ? $data['allowed_origins'] : array($_SERVER['SERVER_NAME']);
  2111. $allowed_origins = !is_array($allowed_origins) ? array_filter(array_map('trim', explode("\n", $allowed_origins))) : $allowed_origins;
  2112. foreach ($allowed_origins as $origin) {
  2113. if (!filter_var($origin, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) && $origin != '*') {
  2114. $_SESSION['return'][] = array(
  2115. 'type' => 'danger',
  2116. 'log' => array(__FUNCTION__, $action, $data),
  2117. 'msg' => 'cors_invalid_origin'
  2118. );
  2119. return false;
  2120. }
  2121. }
  2122. $allowed_methods = isset($data['allowed_methods']) ? $data['allowed_methods'] : array('GET', 'POST', 'PUT', 'DELETE');
  2123. $allowed_methods = !is_array($allowed_methods) ? array_map('trim', preg_split( "/( |,|;|\n)/", $allowed_methods)) : $allowed_methods;
  2124. $available_methods = array('GET', 'POST', 'PUT', 'DELETE');
  2125. foreach ($allowed_methods as $method) {
  2126. if (!in_array($method, $available_methods)) {
  2127. $_SESSION['return'][] = array(
  2128. 'type' => 'danger',
  2129. 'log' => array(__FUNCTION__, $action, $data),
  2130. 'msg' => 'cors_invalid_method'
  2131. );
  2132. return false;
  2133. }
  2134. }
  2135. try {
  2136. $redis->hMSet('CORS_SETTINGS', array(
  2137. 'allowed_origins' => implode(', ', $allowed_origins),
  2138. 'allowed_methods' => implode(', ', $allowed_methods)
  2139. ));
  2140. } catch (RedisException $e) {
  2141. $_SESSION['return'][] = array(
  2142. 'type' => 'danger',
  2143. 'log' => array(__FUNCTION__, $action, $data),
  2144. 'msg' => array('redis_error', $e)
  2145. );
  2146. return false;
  2147. }
  2148. $_SESSION['return'][] = array(
  2149. 'type' => 'success',
  2150. 'log' => array(__FUNCTION__, $action, $data),
  2151. 'msg' => 'cors_headers_edited'
  2152. );
  2153. return true;
  2154. break;
  2155. case "get":
  2156. try {
  2157. $cors_settings = $redis->hMGet('CORS_SETTINGS', array('allowed_origins', 'allowed_methods'));
  2158. } catch (RedisException $e) {
  2159. $_SESSION['return'][] = array(
  2160. 'type' => 'danger',
  2161. 'log' => array(__FUNCTION__, $action, $data),
  2162. 'msg' => array('redis_error', $e)
  2163. );
  2164. }
  2165. $cors_settings = !$cors_settings ? array('allowed_origins' => $_SERVER['SERVER_NAME'], 'allowed_methods' => 'GET, POST, PUT, DELETE') : $cors_settings;
  2166. $cors_settings['allowed_origins'] = empty($cors_settings['allowed_origins']) ? $_SERVER['SERVER_NAME'] : $cors_settings['allowed_origins'];
  2167. $cors_settings['allowed_methods'] = empty($cors_settings['allowed_methods']) ? 'GET, POST, PUT, DELETE, OPTION' : $cors_settings['allowed_methods'];
  2168. return $cors_settings;
  2169. break;
  2170. case "set_headers":
  2171. $cors_settings = cors('get');
  2172. // check if requested origin is in allowed origins
  2173. $allowed_origins = explode(', ', $cors_settings['allowed_origins']);
  2174. $cors_settings['allowed_origins'] = $allowed_origins[0];
  2175. if (in_array('*', $allowed_origins)){
  2176. $cors_settings['allowed_origins'] = '*';
  2177. } else if (in_array($_SERVER['HTTP_ORIGIN'], $allowed_origins)) {
  2178. $cors_settings['allowed_origins'] = $_SERVER['HTTP_ORIGIN'];
  2179. }
  2180. // always allow OPTIONS for preflight request
  2181. $cors_settings["allowed_methods"] = empty($cors_settings["allowed_methods"]) ? 'OPTIONS' : $cors_settings["allowed_methods"] . ', ' . 'OPTIONS';
  2182. header('Access-Control-Allow-Origin: ' . $cors_settings['allowed_origins']);
  2183. header('Access-Control-Allow-Methods: '. $cors_settings['allowed_methods']);
  2184. header('Access-Control-Allow-Headers: Accept, Content-Type, X-Api-Key, Origin');
  2185. // Access-Control settings requested, this is just a preflight request
  2186. if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS' &&
  2187. isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']) &&
  2188. isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
  2189. $allowed_methods = explode(', ', $cors_settings["allowed_methods"]);
  2190. if (in_array($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'], $allowed_methods, true))
  2191. // method allowed send 200 OK
  2192. http_response_code(200);
  2193. else
  2194. // method not allowed send 405 METHOD NOT ALLOWED
  2195. http_response_code(405);
  2196. exit;
  2197. }
  2198. break;
  2199. }
  2200. }
  2201. function getBaseURL() {
  2202. $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
  2203. $host = $_SERVER['HTTP_HOST'];
  2204. $base_url = $protocol . '://' . $host;
  2205. return $base_url;
  2206. }
  2207. function uuid4() {
  2208. $data = openssl_random_pseudo_bytes(16);
  2209. $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
  2210. $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
  2211. return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
  2212. }
  2213. function reset_password($action, $data = null) {
  2214. global $pdo;
  2215. global $redis;
  2216. global $mailcow_hostname;
  2217. global $PW_RESET_TOKEN_LIMIT;
  2218. global $PW_RESET_TOKEN_LIFETIME;
  2219. $_data_log = $data;
  2220. if (isset($_data_log['new_password'])) $_data_log['new_password'] = '*';
  2221. if (isset($_data_log['new_password2'])) $_data_log['new_password2'] = '*';
  2222. switch ($action) {
  2223. case 'check':
  2224. $token = $data;
  2225. $stmt = $pdo->prepare("SELECT `t1`.`username` FROM `reset_password` AS `t1` JOIN `mailbox` AS `t2` ON `t1`.`username` = `t2`.`username` WHERE `t1`.`token` = :token AND `t1`.`created` > DATE_SUB(NOW(), INTERVAL :lifetime MINUTE) AND `t2`.`active` = 1;");
  2226. $stmt->execute(array(
  2227. ':token' => preg_replace('/[^a-zA-Z0-9-]/', '', $token),
  2228. ':lifetime' => $PW_RESET_TOKEN_LIFETIME
  2229. ));
  2230. $return = $stmt->fetch(PDO::FETCH_ASSOC);
  2231. return empty($return['username']) ? false : $return['username'];
  2232. break;
  2233. case 'issue':
  2234. $username = $data;
  2235. // perform cleanup
  2236. $stmt = $pdo->prepare("DELETE FROM `reset_password` WHERE created < DATE_SUB(NOW(), INTERVAL :lifetime MINUTE);");
  2237. $stmt->execute(array(':lifetime' => $PW_RESET_TOKEN_LIFETIME));
  2238. if (filter_var($username, FILTER_VALIDATE_EMAIL) === false) {
  2239. $_SESSION['return'][] = array(
  2240. 'type' => 'danger',
  2241. 'log' => array(__FUNCTION__, $action, $_data_log),
  2242. 'msg' => 'access_denied'
  2243. );
  2244. return false;
  2245. }
  2246. $pw_reset_notification = reset_password('get_notification', 'raw');
  2247. if (!$pw_reset_notification) return false;
  2248. if (empty($pw_reset_notification['from']) || empty($pw_reset_notification['subject'])) {
  2249. $_SESSION['return'][] = array(
  2250. 'type' => 'danger',
  2251. 'log' => array(__FUNCTION__, $action, $_data_log),
  2252. 'msg' => 'password_reset_na'
  2253. );
  2254. return false;
  2255. }
  2256. $stmt = $pdo->prepare("SELECT * FROM `mailbox`
  2257. WHERE `username` = :username");
  2258. $stmt->execute(array(':username' => $username));
  2259. $mailbox_data = $stmt->fetch(PDO::FETCH_ASSOC);
  2260. if (empty($mailbox_data)) {
  2261. $_SESSION['return'][] = array(
  2262. 'type' => 'danger',
  2263. 'log' => array(__FUNCTION__, $action, $_data_log),
  2264. 'msg' => 'password_reset_invalid_user'
  2265. );
  2266. return false;
  2267. }
  2268. $mailbox_attr = json_decode($mailbox_data['attributes'], true);
  2269. if (empty($mailbox_attr['recovery_email']) || filter_var($mailbox_attr['recovery_email'], FILTER_VALIDATE_EMAIL) === false) {
  2270. $_SESSION['return'][] = array(
  2271. 'type' => 'danger',
  2272. 'log' => array(__FUNCTION__, $action, $_data_log),
  2273. 'msg' => "password_reset_invalid_user"
  2274. );
  2275. return false;
  2276. }
  2277. $stmt = $pdo->prepare("SELECT * FROM `reset_password`
  2278. WHERE `username` = :username");
  2279. $stmt->execute(array(':username' => $username));
  2280. $generated_token_count = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  2281. if ($generated_token_count >= $PW_RESET_TOKEN_LIMIT) {
  2282. $_SESSION['return'][] = array(
  2283. 'type' => 'danger',
  2284. 'log' => array(__FUNCTION__, $action, $_data_log),
  2285. 'msg' => "reset_token_limit_exceeded"
  2286. );
  2287. return false;
  2288. }
  2289. $token = implode('-', array(
  2290. strtoupper(bin2hex(random_bytes(3))),
  2291. strtoupper(bin2hex(random_bytes(3))),
  2292. strtoupper(bin2hex(random_bytes(3))),
  2293. strtoupper(bin2hex(random_bytes(3))),
  2294. strtoupper(bin2hex(random_bytes(3)))
  2295. ));
  2296. $stmt = $pdo->prepare("INSERT INTO `reset_password` (`username`, `token`)
  2297. VALUES (:username, :token)");
  2298. $stmt->execute(array(
  2299. ':username' => $username,
  2300. ':token' => $token
  2301. ));
  2302. $reset_link = getBaseURL() . "/reset-password?token=" . $token;
  2303. $request_date = new DateTime();
  2304. $locale_date = locale_get_default();
  2305. $date_formatter = new IntlDateFormatter(
  2306. $locale_date,
  2307. IntlDateFormatter::FULL,
  2308. IntlDateFormatter::FULL
  2309. );
  2310. $formatted_request_date = $date_formatter->format($request_date);
  2311. // set template vars
  2312. // subject
  2313. $pw_reset_notification['subject'] = str_replace('{{hostname}}', $mailcow_hostname, $pw_reset_notification['subject']);
  2314. $pw_reset_notification['subject'] = str_replace('{{link}}', $reset_link, $pw_reset_notification['subject']);
  2315. $pw_reset_notification['subject'] = str_replace('{{username}}', $username, $pw_reset_notification['subject']);
  2316. $pw_reset_notification['subject'] = str_replace('{{username2}}', $mailbox_attr['recovery_email'], $pw_reset_notification['subject']);
  2317. $pw_reset_notification['subject'] = str_replace('{{date}}', $formatted_request_date, $pw_reset_notification['subject']);
  2318. $pw_reset_notification['subject'] = str_replace('{{token_lifetime}}', $PW_RESET_TOKEN_LIFETIME, $pw_reset_notification['subject']);
  2319. // text
  2320. $pw_reset_notification['text_tmpl'] = str_replace('{{hostname}}', $mailcow_hostname, $pw_reset_notification['text_tmpl']);
  2321. $pw_reset_notification['text_tmpl'] = str_replace('{{link}}', $reset_link, $pw_reset_notification['text_tmpl']);
  2322. $pw_reset_notification['text_tmpl'] = str_replace('{{username}}', $username, $pw_reset_notification['text_tmpl']);
  2323. $pw_reset_notification['text_tmpl'] = str_replace('{{username2}}', $mailbox_attr['recovery_email'], $pw_reset_notification['text_tmpl']);
  2324. $pw_reset_notification['text_tmpl'] = str_replace('{{date}}', $formatted_request_date, $pw_reset_notification['text_tmpl']);
  2325. $pw_reset_notification['text_tmpl'] = str_replace('{{token_lifetime}}', $PW_RESET_TOKEN_LIFETIME, $pw_reset_notification['text_tmpl']);
  2326. // html
  2327. $pw_reset_notification['html_tmpl'] = str_replace('{{hostname}}', $mailcow_hostname, $pw_reset_notification['html_tmpl']);
  2328. $pw_reset_notification['html_tmpl'] = str_replace('{{link}}', $reset_link, $pw_reset_notification['html_tmpl']);
  2329. $pw_reset_notification['html_tmpl'] = str_replace('{{username}}', $username, $pw_reset_notification['html_tmpl']);
  2330. $pw_reset_notification['html_tmpl'] = str_replace('{{username2}}', $mailbox_attr['recovery_email'], $pw_reset_notification['html_tmpl']);
  2331. $pw_reset_notification['html_tmpl'] = str_replace('{{date}}', $formatted_request_date, $pw_reset_notification['html_tmpl']);
  2332. $pw_reset_notification['html_tmpl'] = str_replace('{{token_lifetime}}', $PW_RESET_TOKEN_LIFETIME, $pw_reset_notification['html_tmpl']);
  2333. $email_sent = reset_password('send_mail', array(
  2334. "from" => $pw_reset_notification['from'],
  2335. "to" => $mailbox_attr['recovery_email'],
  2336. "subject" => $pw_reset_notification['subject'],
  2337. "text" => $pw_reset_notification['text_tmpl'],
  2338. "html" => $pw_reset_notification['html_tmpl']
  2339. ));
  2340. if (!$email_sent){
  2341. $_SESSION['return'][] = array(
  2342. 'type' => 'danger',
  2343. 'log' => array(__FUNCTION__, $action, $_data_log),
  2344. 'msg' => "recovery_email_failed"
  2345. );
  2346. return false;
  2347. }
  2348. list($localPart, $domainPart) = explode('@', $mailbox_attr['recovery_email']);
  2349. if (strlen($localPart) > 1) {
  2350. $maskedLocalPart = $localPart[0] . str_repeat('*', strlen($localPart) - 1);
  2351. } else {
  2352. $maskedLocalPart = "*";
  2353. }
  2354. $_SESSION['return'][] = array(
  2355. 'type' => 'success',
  2356. 'log' => array(__FUNCTION__, $action, $_data_log),
  2357. 'msg' => array("recovery_email_sent", $maskedLocalPart . '@' . $domainPart)
  2358. );
  2359. return array(
  2360. "username" => $username,
  2361. "issue" => "success"
  2362. );
  2363. break;
  2364. case 'reset':
  2365. $token = $data['token'];
  2366. $new_password = $data['new_password'];
  2367. $new_password2 = $data['new_password2'];
  2368. $username = $data['username'];
  2369. $check_tfa = $data['check_tfa'];
  2370. if (!$username || !$token) {
  2371. $_SESSION['return'][] = array(
  2372. 'type' => 'danger',
  2373. 'log' => array(__FUNCTION__, $action, $_data_log),
  2374. 'msg' => 'invalid_reset_token'
  2375. );
  2376. return false;
  2377. }
  2378. # check new password
  2379. if (!password_check($new_password, $new_password2)) {
  2380. return false;
  2381. }
  2382. if ($check_tfa){
  2383. // check for tfa authenticators
  2384. $authenticators = get_tfa($username);
  2385. if (isset($authenticators['additional']) && is_array($authenticators['additional']) && count($authenticators['additional']) > 0) {
  2386. $_SESSION['pending_mailcow_cc_username'] = $username;
  2387. $_SESSION['pending_pw_reset_token'] = $token;
  2388. $_SESSION['pending_pw_new_password'] = $new_password;
  2389. $_SESSION['pending_tfa_methods'] = $authenticators['additional'];
  2390. $_SESSION['return'][] = array(
  2391. 'type' => 'info',
  2392. 'log' => array(__FUNCTION__, $user, '*'),
  2393. 'msg' => 'awaiting_tfa_confirmation'
  2394. );
  2395. return false;
  2396. }
  2397. }
  2398. # set new password
  2399. $password_hashed = hash_password($new_password);
  2400. $stmt = $pdo->prepare("UPDATE `mailbox` SET
  2401. `password` = :password_hashed,
  2402. `attributes` = JSON_SET(`attributes`, '$.passwd_update', NOW())
  2403. WHERE `username` = :username");
  2404. $stmt->execute(array(
  2405. ':password_hashed' => $password_hashed,
  2406. ':username' => $username
  2407. ));
  2408. // perform cleanup
  2409. $stmt = $pdo->prepare("DELETE FROM `reset_password` WHERE `username` = :username;");
  2410. $stmt->execute(array(
  2411. ':username' => $username
  2412. ));
  2413. $_SESSION['return'][] = array(
  2414. 'type' => 'success',
  2415. 'log' => array(__FUNCTION__, $action, $_data_log),
  2416. 'msg' => 'password_changed_success'
  2417. );
  2418. return true;
  2419. break;
  2420. case 'get_notification':
  2421. $type = $data;
  2422. try {
  2423. $settings['from'] = $redis->Get('PW_RESET_FROM');
  2424. $settings['subject'] = $redis->Get('PW_RESET_SUBJ');
  2425. $settings['html_tmpl'] = $redis->Get('PW_RESET_HTML');
  2426. $settings['text_tmpl'] = $redis->Get('PW_RESET_TEXT');
  2427. if (empty($settings['html_tmpl']) && empty($settings['text_tmpl'])) {
  2428. $settings['html_tmpl'] = file_get_contents("/tpls/pw_reset_html.tpl");
  2429. $settings['text_tmpl'] = file_get_contents("/tpls/pw_reset_text.tpl");
  2430. }
  2431. if ($type != "raw") {
  2432. $settings['html_tmpl'] = htmlspecialchars($settings['html_tmpl']);
  2433. $settings['text_tmpl'] = htmlspecialchars($settings['text_tmpl']);
  2434. }
  2435. }
  2436. catch (RedisException $e) {
  2437. $_SESSION['return'][] = array(
  2438. 'type' => 'danger',
  2439. 'log' => array(__FUNCTION__, $action, $_data_log),
  2440. 'msg' => array('redis_error', $e)
  2441. );
  2442. return false;
  2443. }
  2444. return $settings;
  2445. break;
  2446. case 'send_mail':
  2447. $from = $data['from'];
  2448. $to = $data['to'];
  2449. $text = $data['text'];
  2450. $html = $data['html'];
  2451. $subject = $data['subject'];
  2452. if (!filter_var($from, FILTER_VALIDATE_EMAIL)) {
  2453. $_SESSION['return'][] = array(
  2454. 'type' => 'danger',
  2455. 'log' => array(__FUNCTION__, $action, $_data_log),
  2456. 'msg' => 'from_invalid'
  2457. );
  2458. return false;
  2459. }
  2460. if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
  2461. $_SESSION['return'][] = array(
  2462. 'type' => 'danger',
  2463. 'log' => array(__FUNCTION__, $action, $_data_log),
  2464. 'msg' => 'to_invalid'
  2465. );
  2466. return false;
  2467. }
  2468. if (empty($subject)) {
  2469. $_SESSION['return'][] = array(
  2470. 'type' => 'danger',
  2471. 'log' => array(__FUNCTION__, $action, $_data_log),
  2472. 'msg' => 'subject_empty'
  2473. );
  2474. return false;
  2475. }
  2476. if (empty($text)) {
  2477. $_SESSION['return'][] = array(
  2478. 'type' => 'danger',
  2479. 'log' => array(__FUNCTION__, $action, $_data_log),
  2480. 'msg' => 'text_empty'
  2481. );
  2482. return false;
  2483. }
  2484. ini_set('max_execution_time', 0);
  2485. ini_set('max_input_time', 0);
  2486. $mail = new PHPMailer;
  2487. $mail->Timeout = 10;
  2488. $mail->SMTPOptions = array(
  2489. 'ssl' => array(
  2490. 'verify_peer' => false,
  2491. 'verify_peer_name' => false,
  2492. 'allow_self_signed' => true
  2493. )
  2494. );
  2495. $mail->isSMTP();
  2496. $mail->Host = 'postfix-mailcow';
  2497. $mail->SMTPAuth = false;
  2498. $mail->Port = 25;
  2499. $mail->setFrom($from);
  2500. $mail->Subject = $subject;
  2501. $mail->CharSet ="UTF-8";
  2502. if (!empty($html)) {
  2503. $mail->Body = $html;
  2504. $mail->AltBody = $text;
  2505. }
  2506. else {
  2507. $mail->Body = $text;
  2508. }
  2509. $mail->XMailer = 'MooMail';
  2510. $mail->AddAddress($to);
  2511. if (!$mail->send()) {
  2512. return false;
  2513. }
  2514. $mail->ClearAllRecipients();
  2515. return true;
  2516. break;
  2517. }
  2518. if ($_SESSION['mailcow_cc_role'] != "admin") {
  2519. $_SESSION['return'][] = array(
  2520. 'type' => 'danger',
  2521. 'log' => array(__FUNCTION__, $action, $_data_log),
  2522. 'msg' => 'access_denied'
  2523. );
  2524. return false;
  2525. }
  2526. switch ($action) {
  2527. case 'edit_notification':
  2528. $subject = $data['subject'];
  2529. $from = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $data['from']);
  2530. $from = (!filter_var($from, FILTER_VALIDATE_EMAIL)) ? "" : $from;
  2531. $subject = (empty($subject)) ? "" : $subject;
  2532. $text = (empty($data['text_tmpl'])) ? "" : $data['text_tmpl'];
  2533. $html = (empty($data['html_tmpl'])) ? "" : $data['html_tmpl'];
  2534. try {
  2535. $redis->Set('PW_RESET_FROM', $from);
  2536. $redis->Set('PW_RESET_SUBJ', $subject);
  2537. $redis->Set('PW_RESET_HTML', $html);
  2538. $redis->Set('PW_RESET_TEXT', $text);
  2539. }
  2540. catch (RedisException $e) {
  2541. $_SESSION['return'][] = array(
  2542. 'type' => 'danger',
  2543. 'log' => array(__FUNCTION__, $action, $_data_log),
  2544. 'msg' => array('redis_error', $e)
  2545. );
  2546. return false;
  2547. }
  2548. $_SESSION['return'][] = array(
  2549. 'type' => 'success',
  2550. 'log' => array(__FUNCTION__, $action, $_data_log),
  2551. 'msg' => 'saved_settings'
  2552. );
  2553. break;
  2554. }
  2555. }
  2556. function get_logs($application, $lines = false) {
  2557. if ($lines === false) {
  2558. $lines = $GLOBALS['LOG_LINES'] - 1;
  2559. }
  2560. elseif(is_numeric($lines) && $lines >= 1) {
  2561. $lines = abs(intval($lines) - 1);
  2562. }
  2563. else {
  2564. list ($from, $to) = explode('-', $lines);
  2565. $from = intval($from);
  2566. $to = intval($to);
  2567. if ($from < 1 || $to < $from) { return false; }
  2568. }
  2569. global $redis;
  2570. global $pdo;
  2571. if ($_SESSION['mailcow_cc_role'] != "admin") {
  2572. return false;
  2573. }
  2574. // SQL
  2575. if ($application == "mailcow-ui") {
  2576. if (isset($from) && isset($to)) {
  2577. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :from, :to");
  2578. $stmt->execute(array(
  2579. ':from' => $from - 1,
  2580. ':to' => $to
  2581. ));
  2582. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2583. }
  2584. else {
  2585. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :lines");
  2586. $stmt->execute(array(
  2587. ':lines' => $lines + 1,
  2588. ));
  2589. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2590. }
  2591. if (is_array($data)) {
  2592. return $data;
  2593. }
  2594. }
  2595. if ($application == "sasl") {
  2596. if (isset($from) && isset($to)) {
  2597. $stmt = $pdo->prepare("SELECT * FROM `sasl_log` ORDER BY `datetime` DESC LIMIT :from, :to");
  2598. $stmt->execute(array(
  2599. ':from' => $from - 1,
  2600. ':to' => $to
  2601. ));
  2602. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2603. }
  2604. else {
  2605. $stmt = $pdo->prepare("SELECT * FROM `sasl_log` ORDER BY `datetime` DESC LIMIT :lines");
  2606. $stmt->execute(array(
  2607. ':lines' => $lines + 1,
  2608. ));
  2609. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2610. }
  2611. if (is_array($data)) {
  2612. return $data;
  2613. }
  2614. }
  2615. // Redis
  2616. if ($application == "dovecot-mailcow") {
  2617. if (isset($from) && isset($to)) {
  2618. $data = $redis->lRange('DOVECOT_MAILLOG', $from - 1, $to - 1);
  2619. }
  2620. else {
  2621. $data = $redis->lRange('DOVECOT_MAILLOG', 0, $lines);
  2622. }
  2623. if ($data) {
  2624. foreach ($data as $json_line) {
  2625. $data_array[] = json_decode($json_line, true);
  2626. }
  2627. return $data_array;
  2628. }
  2629. }
  2630. if ($application == "postfix-mailcow") {
  2631. if (isset($from) && isset($to)) {
  2632. $data = $redis->lRange('POSTFIX_MAILLOG', $from - 1, $to - 1);
  2633. }
  2634. else {
  2635. $data = $redis->lRange('POSTFIX_MAILLOG', 0, $lines);
  2636. }
  2637. if ($data) {
  2638. foreach ($data as $json_line) {
  2639. $data_array[] = json_decode($json_line, true);
  2640. }
  2641. return $data_array;
  2642. }
  2643. }
  2644. if ($application == "sogo-mailcow") {
  2645. if (isset($from) && isset($to)) {
  2646. $data = $redis->lRange('SOGO_LOG', $from - 1, $to - 1);
  2647. }
  2648. else {
  2649. $data = $redis->lRange('SOGO_LOG', 0, $lines);
  2650. }
  2651. if ($data) {
  2652. foreach ($data as $json_line) {
  2653. $data_array[] = json_decode($json_line, true);
  2654. }
  2655. return $data_array;
  2656. }
  2657. }
  2658. if ($application == "watchdog-mailcow") {
  2659. if (isset($from) && isset($to)) {
  2660. $data = $redis->lRange('WATCHDOG_LOG', $from - 1, $to - 1);
  2661. }
  2662. else {
  2663. $data = $redis->lRange('WATCHDOG_LOG', 0, $lines);
  2664. }
  2665. if ($data) {
  2666. foreach ($data as $json_line) {
  2667. $data_array[] = json_decode($json_line, true);
  2668. }
  2669. return $data_array;
  2670. }
  2671. }
  2672. if ($application == "acme-mailcow") {
  2673. if (isset($from) && isset($to)) {
  2674. $data = $redis->lRange('ACME_LOG', $from - 1, $to - 1);
  2675. }
  2676. else {
  2677. $data = $redis->lRange('ACME_LOG', 0, $lines);
  2678. }
  2679. if ($data) {
  2680. foreach ($data as $json_line) {
  2681. $data_array[] = json_decode($json_line, true);
  2682. }
  2683. return $data_array;
  2684. }
  2685. }
  2686. if ($application == "ratelimited") {
  2687. if (isset($from) && isset($to)) {
  2688. $data = $redis->lRange('RL_LOG', $from - 1, $to - 1);
  2689. }
  2690. else {
  2691. $data = $redis->lRange('RL_LOG', 0, $lines);
  2692. }
  2693. if ($data) {
  2694. foreach ($data as $json_line) {
  2695. $data_array[] = json_decode($json_line, true);
  2696. }
  2697. return $data_array;
  2698. }
  2699. }
  2700. if ($application == "api-mailcow") {
  2701. if (isset($from) && isset($to)) {
  2702. $data = $redis->lRange('API_LOG', $from - 1, $to - 1);
  2703. }
  2704. else {
  2705. $data = $redis->lRange('API_LOG', 0, $lines);
  2706. }
  2707. if ($data) {
  2708. foreach ($data as $json_line) {
  2709. $data_array[] = json_decode($json_line, true);
  2710. }
  2711. return $data_array;
  2712. }
  2713. }
  2714. if ($application == "netfilter-mailcow") {
  2715. if (isset($from) && isset($to)) {
  2716. $data = $redis->lRange('NETFILTER_LOG', $from - 1, $to - 1);
  2717. }
  2718. else {
  2719. $data = $redis->lRange('NETFILTER_LOG', 0, $lines);
  2720. }
  2721. if ($data) {
  2722. foreach ($data as $json_line) {
  2723. $data_array[] = json_decode($json_line, true);
  2724. }
  2725. return $data_array;
  2726. }
  2727. }
  2728. if ($application == "autodiscover-mailcow") {
  2729. if (isset($from) && isset($to)) {
  2730. $data = $redis->lRange('AUTODISCOVER_LOG', $from - 1, $to - 1);
  2731. }
  2732. else {
  2733. $data = $redis->lRange('AUTODISCOVER_LOG', 0, $lines);
  2734. }
  2735. if ($data) {
  2736. foreach ($data as $json_line) {
  2737. $data_array[] = json_decode($json_line, true);
  2738. }
  2739. return $data_array;
  2740. }
  2741. }
  2742. if ($application == "rspamd-history") {
  2743. $curl = curl_init();
  2744. curl_setopt($curl, CURLOPT_UNIX_SOCKET_PATH, '/var/lib/rspamd/rspamd.sock');
  2745. if (!is_numeric($lines)) {
  2746. list ($from, $to) = explode('-', $lines);
  2747. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?from=" . intval($from) . "&to=" . intval($to));
  2748. }
  2749. else {
  2750. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?to=" . intval($lines));
  2751. }
  2752. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2753. $history = curl_exec($curl);
  2754. if (!curl_errno($curl)) {
  2755. $data_array = json_decode($history, true);
  2756. curl_close($curl);
  2757. return $data_array['rows'];
  2758. }
  2759. curl_close($curl);
  2760. return false;
  2761. }
  2762. if ($application == "rspamd-stats") {
  2763. $curl = curl_init();
  2764. curl_setopt($curl, CURLOPT_UNIX_SOCKET_PATH, '/var/lib/rspamd/rspamd.sock');
  2765. curl_setopt($curl, CURLOPT_URL,"http://rspamd/stat");
  2766. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2767. $stats = curl_exec($curl);
  2768. if (!curl_errno($curl)) {
  2769. $data_array = json_decode($stats, true);
  2770. curl_close($curl);
  2771. return $data_array;
  2772. }
  2773. curl_close($curl);
  2774. return false;
  2775. }
  2776. return false;
  2777. }
  2778. function getGUID() {
  2779. if (function_exists('com_create_guid')) {
  2780. return com_create_guid();
  2781. }
  2782. mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
  2783. $charid = strtoupper(md5(uniqid(rand(), true)));
  2784. $hyphen = chr(45);// "-"
  2785. return substr($charid, 0, 8).$hyphen
  2786. .substr($charid, 8, 4).$hyphen
  2787. .substr($charid,12, 4).$hyphen
  2788. .substr($charid,16, 4).$hyphen
  2789. .substr($charid,20,12);
  2790. }
  2791. function solr_status() {
  2792. $curl = curl_init();
  2793. $endpoint = 'http://solr:8983/solr/admin/cores';
  2794. $params = array(
  2795. 'action' => 'STATUS',
  2796. 'core' => 'dovecot-fts',
  2797. 'indexInfo' => 'true'
  2798. );
  2799. $url = $endpoint . '?' . http_build_query($params);
  2800. curl_setopt($curl, CURLOPT_URL, $url);
  2801. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  2802. curl_setopt($curl, CURLOPT_POST, 0);
  2803. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  2804. $response_core = curl_exec($curl);
  2805. if ($response_core === false) {
  2806. $err = curl_error($curl);
  2807. curl_close($curl);
  2808. return false;
  2809. }
  2810. else {
  2811. curl_close($curl);
  2812. $curl = curl_init();
  2813. $status_core = json_decode($response_core, true);
  2814. $url = 'http://solr:8983/solr/admin/info/system';
  2815. curl_setopt($curl, CURLOPT_URL, $url);
  2816. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  2817. curl_setopt($curl, CURLOPT_POST, 0);
  2818. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  2819. $response_sysinfo = curl_exec($curl);
  2820. if ($response_sysinfo === false) {
  2821. $err = curl_error($curl);
  2822. curl_close($curl);
  2823. return false;
  2824. }
  2825. else {
  2826. curl_close($curl);
  2827. $status_sysinfo = json_decode($response_sysinfo, true);
  2828. $status = array_merge($status_core, $status_sysinfo);
  2829. return (!empty($status['status']['dovecot-fts']) && !empty($status['jvm']['memory'])) ? $status : false;
  2830. }
  2831. return (!empty($status['status']['dovecot-fts'])) ? $status['status']['dovecot-fts'] : false;
  2832. }
  2833. return false;
  2834. }
  2835. function cleanupJS($ignore = '', $folder = '/tmp/*.js') {
  2836. $now = time();
  2837. foreach (glob($folder) as $filename) {
  2838. if(strpos($filename, $ignore) !== false) {
  2839. continue;
  2840. }
  2841. if (is_file($filename)) {
  2842. if ($now - filemtime($filename) >= 60 * 60) {
  2843. unlink($filename);
  2844. }
  2845. }
  2846. }
  2847. }
  2848. function cleanupCSS($ignore = '', $folder = '/tmp/*.css') {
  2849. $now = time();
  2850. foreach (glob($folder) as $filename) {
  2851. if(strpos($filename, $ignore) !== false) {
  2852. continue;
  2853. }
  2854. if (is_file($filename)) {
  2855. if ($now - filemtime($filename) >= 60 * 60) {
  2856. unlink($filename);
  2857. }
  2858. }
  2859. }
  2860. }
  2861. ?>