functions.inc.php 108 KB

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