functions.inc.php 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406
  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/lookup/" . $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['location']['shortcountry'])) {
  290. $sasl[$k]['location'] = $ip_data_array['location']['shortcountry'];
  291. try {
  292. $redis->hSet('IP_SHORTCOUNTRY', $sasl[$k]['real_rip'], $ip_data_array['location']['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() {
  988. if (getenv('SKIP_SOGO') == "y") {
  989. return true;
  990. }
  991. global $pdo;
  992. global $lang;
  993. $stmt = $pdo->query("SELECT 'OK' FROM INFORMATION_SCHEMA.TABLES
  994. WHERE TABLE_NAME = 'sogo_view'");
  995. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  996. if ($num_results != 0) {
  997. $stmt = $pdo->query("REPLACE INTO _sogo_static_view (`c_uid`, `domain`, `c_name`, `c_password`, `c_cn`, `mail`, `aliases`, `ad_aliases`, `ext_acl`, `kind`, `multiple_bookings`)
  998. SELECT `c_uid`, `domain`, `c_name`, `c_password`, `c_cn`, `mail`, `aliases`, `ad_aliases`, `ext_acl`, `kind`, `multiple_bookings` from sogo_view");
  999. $stmt = $pdo->query("DELETE FROM _sogo_static_view WHERE `c_uid` NOT IN (SELECT `username` FROM `mailbox` WHERE `active` = '1');");
  1000. }
  1001. flush_memcached();
  1002. }
  1003. function edit_user_account($_data) {
  1004. global $lang;
  1005. global $pdo;
  1006. $_data_log = $_data;
  1007. !isset($_data_log['user_new_pass']) ?: $_data_log['user_new_pass'] = '*';
  1008. !isset($_data_log['user_new_pass2']) ?: $_data_log['user_new_pass2'] = '*';
  1009. !isset($_data_log['user_old_pass']) ?: $_data_log['user_old_pass'] = '*';
  1010. $username = $_SESSION['mailcow_cc_username'];
  1011. $role = $_SESSION['mailcow_cc_role'];
  1012. $password_old = $_data['user_old_pass'];
  1013. if (filter_var($username, FILTER_VALIDATE_EMAIL === false) || $role != 'user') {
  1014. $_SESSION['return'][] = array(
  1015. 'type' => 'danger',
  1016. 'log' => array(__FUNCTION__, $_data_log),
  1017. 'msg' => 'access_denied'
  1018. );
  1019. return false;
  1020. }
  1021. $stmt = $pdo->prepare("SELECT `password` FROM `mailbox`
  1022. WHERE `kind` NOT REGEXP 'location|thing|group'
  1023. AND `username` = :user");
  1024. $stmt->execute(array(':user' => $username));
  1025. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1026. if (!verify_hash($row['password'], $password_old)) {
  1027. $_SESSION['return'][] = array(
  1028. 'type' => 'danger',
  1029. 'log' => array(__FUNCTION__, $_data_log),
  1030. 'msg' => 'access_denied'
  1031. );
  1032. return false;
  1033. }
  1034. if (!empty($_data['user_new_pass']) && !empty($_data['user_new_pass2'])) {
  1035. $password_new = $_data['user_new_pass'];
  1036. $password_new2 = $_data['user_new_pass2'];
  1037. if (password_check($password_new, $password_new2) !== true) {
  1038. return false;
  1039. }
  1040. $password_hashed = hash_password($password_new);
  1041. $stmt = $pdo->prepare("UPDATE `mailbox` SET `password` = :password_hashed,
  1042. `attributes` = JSON_SET(`attributes`, '$.force_pw_update', '0'),
  1043. `attributes` = JSON_SET(`attributes`, '$.passwd_update', NOW())
  1044. WHERE `username` = :username");
  1045. $stmt->execute(array(
  1046. ':password_hashed' => $password_hashed,
  1047. ':username' => $username
  1048. ));
  1049. }
  1050. update_sogo_static_view();
  1051. $_SESSION['return'][] = array(
  1052. 'type' => 'success',
  1053. 'log' => array(__FUNCTION__, $_data_log),
  1054. 'msg' => array('mailbox_modified', htmlspecialchars($username))
  1055. );
  1056. }
  1057. function user_get_alias_details($username) {
  1058. global $pdo;
  1059. global $lang;
  1060. $data['direct_aliases'] = array();
  1061. $data['shared_aliases'] = array();
  1062. if ($_SESSION['mailcow_cc_role'] == "user") {
  1063. $username = $_SESSION['mailcow_cc_username'];
  1064. }
  1065. if (!filter_var($username, FILTER_VALIDATE_EMAIL)) {
  1066. return false;
  1067. }
  1068. if (!hasMailboxObjectAccess($username, $_SESSION['mailcow_cc_role'], $username)) {
  1069. return false;
  1070. }
  1071. $data['address'] = $username;
  1072. $stmt = $pdo->prepare("SELECT `address` AS `shared_aliases`, `public_comment` FROM `alias`
  1073. WHERE `goto` REGEXP :username_goto
  1074. AND `address` NOT LIKE '@%'
  1075. AND `goto` != :username_goto2
  1076. AND `address` != :username_address");
  1077. $stmt->execute(array(
  1078. ':username_goto' => '(^|,)'.$username.'($|,)',
  1079. ':username_goto2' => $username,
  1080. ':username_address' => $username
  1081. ));
  1082. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1083. while ($row = array_shift($run)) {
  1084. $data['shared_aliases'][$row['shared_aliases']]['public_comment'] = htmlspecialchars($row['public_comment']);
  1085. //$data['shared_aliases'][] = $row['shared_aliases'];
  1086. }
  1087. $stmt = $pdo->prepare("SELECT `address` AS `direct_aliases`, `public_comment` FROM `alias`
  1088. WHERE `goto` = :username_goto
  1089. AND `address` NOT LIKE '@%'
  1090. AND `address` != :username_address");
  1091. $stmt->execute(
  1092. array(
  1093. ':username_goto' => $username,
  1094. ':username_address' => $username
  1095. ));
  1096. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1097. while ($row = array_shift($run)) {
  1098. $data['direct_aliases'][$row['direct_aliases']]['public_comment'] = htmlspecialchars($row['public_comment']);
  1099. }
  1100. $stmt = $pdo->prepare("SELECT CONCAT(local_part, '@', alias_domain) AS `ad_alias`, `alias_domain` FROM `mailbox`
  1101. LEFT OUTER JOIN `alias_domain` on `target_domain` = `domain`
  1102. WHERE `username` = :username ;");
  1103. $stmt->execute(array(':username' => $username));
  1104. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1105. while ($row = array_shift($run)) {
  1106. if (empty($row['ad_alias'])) {
  1107. continue;
  1108. }
  1109. $data['direct_aliases'][$row['ad_alias']]['public_comment'] = $lang['add']['alias_domain'];
  1110. $data['alias_domains'][] = $row['alias_domain'];
  1111. }
  1112. $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 '@%';");
  1113. $stmt->execute(array(':username' => $username));
  1114. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1115. while ($row = array_shift($run)) {
  1116. $data['aliases_also_send_as'] = $row['send_as'];
  1117. }
  1118. $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 '@%';");
  1119. $stmt->execute(array(':username' => $username));
  1120. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1121. while ($row = array_shift($run)) {
  1122. $data['aliases_send_as_all'] = $row['send_as'];
  1123. }
  1124. $stmt = $pdo->prepare("SELECT IFNULL(GROUP_CONCAT(`address` SEPARATOR ', '), '') as `address` FROM `alias` WHERE `goto` REGEXP :username AND `address` LIKE '@%';");
  1125. $stmt->execute(array(':username' => '(^|,)'.$username.'($|,)'));
  1126. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1127. while ($row = array_shift($run)) {
  1128. $data['is_catch_all'] = $row['address'];
  1129. }
  1130. return $data;
  1131. }
  1132. function is_valid_domain_name($domain_name) {
  1133. if (empty($domain_name)) {
  1134. return false;
  1135. }
  1136. $domain_name = idn_to_ascii($domain_name, 0, INTL_IDNA_VARIANT_UTS46);
  1137. return (preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $domain_name)
  1138. && preg_match("/^.{1,253}$/", $domain_name)
  1139. && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $domain_name));
  1140. }
  1141. function set_tfa($_data) {
  1142. global $pdo;
  1143. global $yubi;
  1144. global $tfa;
  1145. $_data_log = $_data;
  1146. $access_denied = null;
  1147. !isset($_data_log['confirm_password']) ?: $_data_log['confirm_password'] = '*';
  1148. $username = $_SESSION['mailcow_cc_username'];
  1149. // check for empty user and role
  1150. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) $access_denied = true;
  1151. // check admin confirm password
  1152. if ($access_denied === null) {
  1153. $stmt = $pdo->prepare("SELECT `password` FROM `admin`
  1154. WHERE `username` = :username");
  1155. $stmt->execute(array(':username' => $username));
  1156. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1157. if ($row) {
  1158. if (!verify_hash($row['password'], $_data["confirm_password"])) $access_denied = true;
  1159. else $access_denied = false;
  1160. }
  1161. }
  1162. // check mailbox confirm password
  1163. if ($access_denied === null) {
  1164. $stmt = $pdo->prepare("SELECT `password` FROM `mailbox`
  1165. WHERE `username` = :username");
  1166. $stmt->execute(array(':username' => $username));
  1167. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1168. if ($row) {
  1169. if (!verify_hash($row['password'], $_data["confirm_password"])) $access_denied = true;
  1170. else $access_denied = false;
  1171. }
  1172. }
  1173. // set access_denied error
  1174. if ($access_denied){
  1175. $_SESSION['return'][] = array(
  1176. 'type' => 'danger',
  1177. 'log' => array(__FUNCTION__, $_data_log),
  1178. 'msg' => 'access_denied'
  1179. );
  1180. return false;
  1181. }
  1182. switch ($_data["tfa_method"]) {
  1183. case "yubi_otp":
  1184. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  1185. $yubico_id = $_data['yubico_id'];
  1186. $yubico_key = $_data['yubico_key'];
  1187. $yubi = new Auth_Yubico($yubico_id, $yubico_key);
  1188. if (!$yubi) {
  1189. $_SESSION['return'][] = array(
  1190. 'type' => 'danger',
  1191. 'log' => array(__FUNCTION__, $_data_log),
  1192. 'msg' => 'access_denied'
  1193. );
  1194. return false;
  1195. }
  1196. if (!ctype_alnum($_data["otp_token"]) || strlen($_data["otp_token"]) != 44) {
  1197. $_SESSION['return'][] = array(
  1198. 'type' => 'danger',
  1199. 'log' => array(__FUNCTION__, $_data_log),
  1200. 'msg' => 'tfa_token_invalid'
  1201. );
  1202. return false;
  1203. }
  1204. $yauth = $yubi->verify($_data["otp_token"]);
  1205. if (PEAR::isError($yauth)) {
  1206. $_SESSION['return'][] = array(
  1207. 'type' => 'danger',
  1208. 'log' => array(__FUNCTION__, $_data_log),
  1209. 'msg' => array('yotp_verification_failed', $yauth->getMessage())
  1210. );
  1211. return false;
  1212. }
  1213. try {
  1214. // We could also do a modhex translation here
  1215. $yubico_modhex_id = substr($_data["otp_token"], 0, 12);
  1216. $stmt = $pdo->prepare("DELETE FROM `tfa`
  1217. WHERE `username` = :username
  1218. AND (`authmech` = 'yubi_otp' AND `secret` LIKE :modhex)");
  1219. $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id));
  1220. $stmt = $pdo->prepare("INSERT INTO `tfa` (`key_id`, `username`, `authmech`, `active`, `secret`) VALUES
  1221. (:key_id, :username, 'yubi_otp', '1', :secret)");
  1222. $stmt->execute(array(':key_id' => $key_id, ':username' => $username, ':secret' => $yubico_id . ':' . $yubico_key . ':' . $yubico_modhex_id));
  1223. }
  1224. catch (PDOException $e) {
  1225. $_SESSION['return'][] = array(
  1226. 'type' => 'danger',
  1227. 'log' => array(__FUNCTION__, $_data_log),
  1228. 'msg' => array('mysql_error', $e)
  1229. );
  1230. return false;
  1231. }
  1232. $_SESSION['return'][] = array(
  1233. 'type' => 'success',
  1234. 'log' => array(__FUNCTION__, $_data_log),
  1235. 'msg' => array('object_modified', htmlspecialchars($username))
  1236. );
  1237. break;
  1238. case "totp":
  1239. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  1240. if ($tfa->verifyCode($_POST['totp_secret'], $_POST['totp_confirm_token']) === true) {
  1241. //$stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
  1242. //$stmt->execute(array(':username' => $username));
  1243. $stmt = $pdo->prepare("INSERT INTO `tfa` (`username`, `key_id`, `authmech`, `secret`, `active`) VALUES (?, ?, 'totp', ?, '1')");
  1244. $stmt->execute(array($username, $key_id, $_POST['totp_secret']));
  1245. $_SESSION['return'][] = array(
  1246. 'type' => 'success',
  1247. 'log' => array(__FUNCTION__, $_data_log),
  1248. 'msg' => array('object_modified', $username)
  1249. );
  1250. }
  1251. else {
  1252. $_SESSION['return'][] = array(
  1253. 'type' => 'danger',
  1254. 'log' => array(__FUNCTION__, $_data_log),
  1255. 'msg' => 'totp_verification_failed'
  1256. );
  1257. }
  1258. break;
  1259. case "webauthn":
  1260. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  1261. $stmt = $pdo->prepare("INSERT INTO `tfa` (`username`, `key_id`, `authmech`, `keyHandle`, `publicKey`, `certificate`, `counter`, `active`)
  1262. VALUES (?, ?, 'webauthn', ?, ?, ?, ?, '1')");
  1263. $stmt->execute(array(
  1264. $username,
  1265. $key_id,
  1266. base64_encode($_data['registration']->credentialId),
  1267. $_data['registration']->credentialPublicKey,
  1268. $_data['registration']->certificate,
  1269. 0
  1270. ));
  1271. $_SESSION['return'][] = array(
  1272. 'type' => 'success',
  1273. 'log' => array(__FUNCTION__, $_data_log),
  1274. 'msg' => array('object_modified', $username)
  1275. );
  1276. break;
  1277. case "none":
  1278. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
  1279. $stmt->execute(array(':username' => $username));
  1280. $_SESSION['return'][] = array(
  1281. 'type' => 'success',
  1282. 'log' => array(__FUNCTION__, $_data_log),
  1283. 'msg' => array('object_modified', htmlspecialchars($username))
  1284. );
  1285. break;
  1286. }
  1287. }
  1288. function fido2($_data) {
  1289. global $pdo;
  1290. $_data_log = $_data;
  1291. // Not logging registration data, only actions
  1292. // Silent errors for "get" requests
  1293. switch ($_data["action"]) {
  1294. case "register":
  1295. $username = $_SESSION['mailcow_cc_username'];
  1296. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1297. $_SESSION['return'][] = array(
  1298. 'type' => 'danger',
  1299. 'log' => array(__FUNCTION__, $_data["action"]),
  1300. 'msg' => 'access_denied'
  1301. );
  1302. return false;
  1303. }
  1304. $stmt = $pdo->prepare("INSERT INTO `fido2` (`username`, `rpId`, `credentialPublicKey`, `certificateChain`, `certificate`, `certificateIssuer`, `certificateSubject`, `signatureCounter`, `AAGUID`, `credentialId`)
  1305. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
  1306. $stmt->execute(array(
  1307. $username,
  1308. $_data['registration']->rpId,
  1309. $_data['registration']->credentialPublicKey,
  1310. $_data['registration']->certificateChain,
  1311. $_data['registration']->certificate,
  1312. $_data['registration']->certificateIssuer,
  1313. $_data['registration']->certificateSubject,
  1314. $_data['registration']->signatureCounter,
  1315. $_data['registration']->AAGUID,
  1316. $_data['registration']->credentialId)
  1317. );
  1318. $_SESSION['return'][] = array(
  1319. 'type' => 'success',
  1320. 'log' => array(__FUNCTION__, $_data["action"]),
  1321. 'msg' => array('object_modified', $username)
  1322. );
  1323. break;
  1324. case "get_user_cids":
  1325. // Used to exclude existing CredentialIds while registering
  1326. $username = $_SESSION['mailcow_cc_username'];
  1327. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1328. return false;
  1329. }
  1330. $stmt = $pdo->prepare("SELECT `credentialId` FROM `fido2` WHERE `username` = :username");
  1331. $stmt->execute(array(':username' => $username));
  1332. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1333. while($row = array_shift($rows)) {
  1334. $cids[] = $row['credentialId'];
  1335. }
  1336. return $cids;
  1337. break;
  1338. case "get_all_cids":
  1339. // Only needed when using fido2 with username
  1340. $stmt = $pdo->query("SELECT `credentialId` FROM `fido2`");
  1341. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1342. while($row = array_shift($rows)) {
  1343. $cids[] = $row['credentialId'];
  1344. }
  1345. return $cids;
  1346. break;
  1347. case "get_by_b64cid":
  1348. if (!isset($_data['cid']) || empty($_data['cid'])) {
  1349. return false;
  1350. }
  1351. $stmt = $pdo->prepare("SELECT `certificateSubject`, `username`, `credentialPublicKey`, SHA2(`credentialId`, 256) AS `cid` FROM `fido2` WHERE `credentialId` = :cid");
  1352. $stmt->execute(array(':cid' => base64_decode($_data['cid'])));
  1353. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1354. if (empty($row) || empty($row['credentialPublicKey']) || empty($row['username'])) {
  1355. return false;
  1356. }
  1357. $data['pub_key'] = $row['credentialPublicKey'];
  1358. $data['username'] = $row['username'];
  1359. $data['subject'] = $row['certificateSubject'];
  1360. $data['cid'] = $row['cid'];
  1361. return $data;
  1362. break;
  1363. case "get_friendly_names":
  1364. $username = $_SESSION['mailcow_cc_username'];
  1365. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1366. return false;
  1367. }
  1368. $stmt = $pdo->prepare("SELECT SHA2(`credentialId`, 256) AS `cid`, `created`, `certificateSubject`, `friendlyName` FROM `fido2` WHERE `username` = :username");
  1369. $stmt->execute(array(':username' => $username));
  1370. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1371. while($row = array_shift($rows)) {
  1372. $fns[] = array(
  1373. "subject" => (empty($row['certificateSubject']) ? 'Unknown (' . $row['created'] . ')' : $row['certificateSubject']),
  1374. "fn" => $row['friendlyName'],
  1375. "cid" => $row['cid']
  1376. );
  1377. }
  1378. return $fns;
  1379. break;
  1380. case "unset_fido2_key":
  1381. $username = $_SESSION['mailcow_cc_username'];
  1382. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1383. $_SESSION['return'][] = array(
  1384. 'type' => 'danger',
  1385. 'log' => array(__FUNCTION__, $_data["action"]),
  1386. 'msg' => 'access_denied'
  1387. );
  1388. return false;
  1389. }
  1390. $stmt = $pdo->prepare("DELETE FROM `fido2` WHERE `username` = :username AND SHA2(`credentialId`, 256) = :cid");
  1391. $stmt->execute(array(
  1392. ':username' => $username,
  1393. ':cid' => $_data['post_data']['unset_fido2_key']
  1394. ));
  1395. $_SESSION['return'][] = array(
  1396. 'type' => 'success',
  1397. 'log' => array(__FUNCTION__, $_data_log),
  1398. 'msg' => array('object_modified', htmlspecialchars($username))
  1399. );
  1400. break;
  1401. case "edit_fn":
  1402. $username = $_SESSION['mailcow_cc_username'];
  1403. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1404. $_SESSION['return'][] = array(
  1405. 'type' => 'danger',
  1406. 'log' => array(__FUNCTION__, $_data["action"]),
  1407. 'msg' => 'access_denied'
  1408. );
  1409. return false;
  1410. }
  1411. $stmt = $pdo->prepare("UPDATE `fido2` SET `friendlyName` = :friendlyName WHERE SHA2(`credentialId`, 256) = :cid AND `username` = :username");
  1412. $stmt->execute(array(
  1413. ':username' => $username,
  1414. ':friendlyName' => $_data['fido2_attrs']['fido2_fn'],
  1415. ':cid' => $_data['fido2_attrs']['fido2_cid']
  1416. ));
  1417. $_SESSION['return'][] = array(
  1418. 'type' => 'success',
  1419. 'log' => array(__FUNCTION__, $_data_log),
  1420. 'msg' => array('object_modified', htmlspecialchars($username))
  1421. );
  1422. break;
  1423. }
  1424. }
  1425. function unset_tfa_key($_data) {
  1426. // Can only unset own keys
  1427. // Needs at least one key left
  1428. global $pdo;
  1429. global $lang;
  1430. $_data_log = $_data;
  1431. $access_denied = null;
  1432. $id = intval($_data['unset_tfa_key']);
  1433. $username = $_SESSION['mailcow_cc_username'];
  1434. // check for empty user and role
  1435. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) $access_denied = true;
  1436. try {
  1437. if (!is_numeric($id)) $access_denied = true;
  1438. // set access_denied error
  1439. if ($access_denied){
  1440. $_SESSION['return'][] = array(
  1441. 'type' => 'danger',
  1442. 'log' => array(__FUNCTION__, $_data_log),
  1443. 'msg' => 'access_denied'
  1444. );
  1445. return false;
  1446. }
  1447. // check if it's last key
  1448. $stmt = $pdo->prepare("SELECT COUNT(*) AS `keys` FROM `tfa`
  1449. WHERE `username` = :username AND `active` = '1'");
  1450. $stmt->execute(array(':username' => $username));
  1451. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1452. if ($row['keys'] == "1") {
  1453. $_SESSION['return'][] = array(
  1454. 'type' => 'danger',
  1455. 'log' => array(__FUNCTION__, $_data_log),
  1456. 'msg' => 'last_key'
  1457. );
  1458. return false;
  1459. }
  1460. // delete key
  1461. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username AND `id` = :id");
  1462. $stmt->execute(array(':username' => $username, ':id' => $id));
  1463. $_SESSION['return'][] = array(
  1464. 'type' => 'success',
  1465. 'log' => array(__FUNCTION__, $_data_log),
  1466. 'msg' => array('object_modified', $username)
  1467. );
  1468. }
  1469. catch (PDOException $e) {
  1470. $_SESSION['return'][] = array(
  1471. 'type' => 'danger',
  1472. 'log' => array(__FUNCTION__, $_data_log),
  1473. 'msg' => array('mysql_error', $e)
  1474. );
  1475. return false;
  1476. }
  1477. }
  1478. function get_tfa($username = null, $id = null) {
  1479. global $pdo;
  1480. if (isset($_SESSION['mailcow_cc_username'])) {
  1481. $username = $_SESSION['mailcow_cc_username'];
  1482. }
  1483. elseif (empty($username)) {
  1484. return false;
  1485. }
  1486. if (!isset($id)){
  1487. // fetch all tfa methods - just get information about possible authenticators
  1488. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `authmech` FROM `tfa`
  1489. WHERE `username` = :username AND `active` = '1'");
  1490. $stmt->execute(array(':username' => $username));
  1491. $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1492. // no tfa methods found
  1493. if (count($results) == 0) {
  1494. $data['name'] = 'none';
  1495. $data['pretty'] = "-";
  1496. $data['additional'] = array();
  1497. return $data;
  1498. }
  1499. $data['additional'] = $results;
  1500. return $data;
  1501. } else {
  1502. // fetch specific authenticator details by id
  1503. $stmt = $pdo->prepare("SELECT * FROM `tfa`
  1504. WHERE `username` = :username AND `id` = :id AND `active` = '1'");
  1505. $stmt->execute(array(':username' => $username, ':id' => $id));
  1506. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1507. if (isset($row["authmech"])) {
  1508. switch ($row["authmech"]) {
  1509. case "yubi_otp":
  1510. $data['name'] = "yubi_otp";
  1511. $data['pretty'] = "Yubico OTP";
  1512. $stmt = $pdo->prepare("SELECT `id`, `key_id`, RIGHT(`secret`, 12) AS 'modhex' FROM `tfa` WHERE `authmech` = 'yubi_otp' AND `username` = :username AND `id` = :id");
  1513. $stmt->execute(array(
  1514. ':username' => $username,
  1515. ':id' => $id
  1516. ));
  1517. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1518. while($row = array_shift($rows)) {
  1519. $data['additional'][] = $row;
  1520. }
  1521. return $data;
  1522. break;
  1523. // u2f - deprecated, should be removed
  1524. case "u2f":
  1525. $data['name'] = "u2f";
  1526. $data['pretty'] = "Fido U2F";
  1527. $stmt = $pdo->prepare("SELECT `id`, `key_id` FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username AND `id` = :id");
  1528. $stmt->execute(array(
  1529. ':username' => $username,
  1530. ':id' => $id
  1531. ));
  1532. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1533. while($row = array_shift($rows)) {
  1534. $data['additional'][] = $row;
  1535. }
  1536. return $data;
  1537. break;
  1538. case "hotp":
  1539. $data['name'] = "hotp";
  1540. $data['pretty'] = "HMAC-based OTP";
  1541. return $data;
  1542. break;
  1543. case "totp":
  1544. $data['name'] = "totp";
  1545. $data['pretty'] = "Time-based OTP";
  1546. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `secret` FROM `tfa` WHERE `authmech` = 'totp' AND `username` = :username AND `id` = :id");
  1547. $stmt->execute(array(
  1548. ':username' => $username,
  1549. ':id' => $id
  1550. ));
  1551. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1552. while($row = array_shift($rows)) {
  1553. $data['additional'][] = $row;
  1554. }
  1555. return $data;
  1556. break;
  1557. case "webauthn":
  1558. $data['name'] = "webauthn";
  1559. $data['pretty'] = "WebAuthn";
  1560. $stmt = $pdo->prepare("SELECT `id`, `key_id` FROM `tfa` WHERE `authmech` = 'webauthn' AND `username` = :username AND `id` = :id");
  1561. $stmt->execute(array(
  1562. ':username' => $username,
  1563. ':id' => $id
  1564. ));
  1565. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1566. while($row = array_shift($rows)) {
  1567. $data['additional'][] = $row;
  1568. }
  1569. return $data;
  1570. break;
  1571. default:
  1572. $data['name'] = 'none';
  1573. $data['pretty'] = "-";
  1574. return $data;
  1575. break;
  1576. }
  1577. }
  1578. else {
  1579. $data['name'] = 'none';
  1580. $data['pretty'] = "-";
  1581. return $data;
  1582. }
  1583. }
  1584. }
  1585. function verify_tfa_login($username, $_data) {
  1586. global $pdo;
  1587. global $yubi;
  1588. global $u2f;
  1589. global $tfa;
  1590. global $WebAuthn;
  1591. if ($_data['tfa_method'] != 'u2f'){
  1592. switch ($_data["tfa_method"]) {
  1593. case "yubi_otp":
  1594. if (!ctype_alnum($_data['token']) || strlen($_data['token']) != 44) {
  1595. $_SESSION['return'][] = array(
  1596. 'type' => 'danger',
  1597. 'log' => array(__FUNCTION__, $username, '*'),
  1598. 'msg' => array('yotp_verification_failed', 'token length error')
  1599. );
  1600. return false;
  1601. }
  1602. $yubico_modhex_id = substr($_data['token'], 0, 12);
  1603. $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
  1604. WHERE `username` = :username
  1605. AND `authmech` = 'yubi_otp'
  1606. AND `active` = '1'
  1607. AND `secret` LIKE :modhex");
  1608. $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id));
  1609. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1610. $yubico_auth = explode(':', $row['secret']);
  1611. $yubi = new Auth_Yubico($yubico_auth[0], $yubico_auth[1]);
  1612. $yauth = $yubi->verify($_data['token']);
  1613. if (PEAR::isError($yauth)) {
  1614. $_SESSION['return'][] = array(
  1615. 'type' => 'danger',
  1616. 'log' => array(__FUNCTION__, $username, '*'),
  1617. 'msg' => array('yotp_verification_failed', $yauth->getMessage())
  1618. );
  1619. return false;
  1620. }
  1621. else {
  1622. $_SESSION['tfa_id'] = $row['id'];
  1623. $_SESSION['return'][] = array(
  1624. 'type' => 'success',
  1625. 'log' => array(__FUNCTION__, $username, '*'),
  1626. 'msg' => 'verified_yotp_login'
  1627. );
  1628. return true;
  1629. }
  1630. $_SESSION['return'][] = array(
  1631. 'type' => 'danger',
  1632. 'log' => array(__FUNCTION__, $username, '*'),
  1633. 'msg' => array('yotp_verification_failed', 'unknown')
  1634. );
  1635. return false;
  1636. break;
  1637. case "hotp":
  1638. return false;
  1639. break;
  1640. case "totp":
  1641. try {
  1642. $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
  1643. WHERE `username` = :username
  1644. AND `authmech` = 'totp'
  1645. AND `id` = :id
  1646. AND `active`='1'");
  1647. $stmt->execute(array(':username' => $username, ':id' => $_data['id']));
  1648. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1649. foreach ($rows as $row) {
  1650. if ($tfa->verifyCode($row['secret'], $_data['token']) === true) {
  1651. $_SESSION['tfa_id'] = $row['id'];
  1652. $_SESSION['return'][] = array(
  1653. 'type' => 'success',
  1654. 'log' => array(__FUNCTION__, $username, '*'),
  1655. 'msg' => 'verified_totp_login'
  1656. );
  1657. return true;
  1658. }
  1659. }
  1660. $_SESSION['return'][] = array(
  1661. 'type' => 'danger',
  1662. 'log' => array(__FUNCTION__, $username, '*'),
  1663. 'msg' => 'totp_verification_failed'
  1664. );
  1665. return false;
  1666. }
  1667. catch (PDOException $e) {
  1668. $_SESSION['return'][] = array(
  1669. 'type' => 'danger',
  1670. 'log' => array(__FUNCTION__, $username, '*'),
  1671. 'msg' => array('mysql_error', $e)
  1672. );
  1673. return false;
  1674. }
  1675. break;
  1676. case "webauthn":
  1677. $tokenData = json_decode($_data['token']);
  1678. $clientDataJSON = base64_decode($tokenData->clientDataJSON);
  1679. $authenticatorData = base64_decode($tokenData->authenticatorData);
  1680. $signature = base64_decode($tokenData->signature);
  1681. $id = base64_decode($tokenData->id);
  1682. $challenge = $_SESSION['challenge'];
  1683. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `keyHandle`, `username`, `publicKey` FROM `tfa` WHERE `id` = :id AND `active`='1'");
  1684. $stmt->execute(array(':id' => $_data['id']));
  1685. $process_webauthn = $stmt->fetch(PDO::FETCH_ASSOC);
  1686. if (empty($process_webauthn)){
  1687. $_SESSION['return'][] = array(
  1688. 'type' => 'danger',
  1689. 'log' => array(__FUNCTION__, $username, '*'),
  1690. 'msg' => array('webauthn_authenticator_failed')
  1691. );
  1692. return false;
  1693. }
  1694. if (empty($process_webauthn['publicKey']) || $process_webauthn['publicKey'] === false) {
  1695. $_SESSION['return'][] = array(
  1696. 'type' => 'danger',
  1697. 'log' => array(__FUNCTION__, $username, '*'),
  1698. 'msg' => array('webauthn_publickey_failed')
  1699. );
  1700. return false;
  1701. }
  1702. if ($process_webauthn['username'] != $_SESSION['pending_mailcow_cc_username']){
  1703. $_SESSION['return'][] = array(
  1704. 'type' => 'danger',
  1705. 'log' => array(__FUNCTION__, $username, '*'),
  1706. 'msg' => array('webauthn_username_failed')
  1707. );
  1708. return false;
  1709. }
  1710. try {
  1711. $WebAuthn->processGet($clientDataJSON, $authenticatorData, $signature, $process_webauthn['publicKey'], $challenge, null, $GLOBALS['WEBAUTHN_UV_FLAG_LOGIN'], $GLOBALS['WEBAUTHN_USER_PRESENT_FLAG']);
  1712. }
  1713. catch (Throwable $ex) {
  1714. $_SESSION['return'][] = array(
  1715. 'type' => 'danger',
  1716. 'log' => array(__FUNCTION__, $username, '*'),
  1717. 'msg' => array('webauthn_verification_failed', $ex->getMessage())
  1718. );
  1719. return false;
  1720. }
  1721. $stmt = $pdo->prepare("SELECT `superadmin` FROM `admin` WHERE `username` = :username");
  1722. $stmt->execute(array(':username' => $process_webauthn['username']));
  1723. $obj_props = $stmt->fetch(PDO::FETCH_ASSOC);
  1724. if ($obj_props['superadmin'] === 1) {
  1725. $_SESSION["mailcow_cc_role"] = "admin";
  1726. }
  1727. elseif ($obj_props['superadmin'] === 0) {
  1728. $_SESSION["mailcow_cc_role"] = "domainadmin";
  1729. }
  1730. else {
  1731. $stmt = $pdo->prepare("SELECT `username` FROM `mailbox` WHERE `username` = :username");
  1732. $stmt->execute(array(':username' => $process_webauthn['username']));
  1733. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1734. if (!empty($row['username'])) {
  1735. $_SESSION["mailcow_cc_role"] = "user";
  1736. } else {
  1737. $_SESSION['return'][] = array(
  1738. 'type' => 'danger',
  1739. 'log' => array(__FUNCTION__, $username, '*'),
  1740. 'msg' => array('webauthn_role_failed')
  1741. );
  1742. return false;
  1743. }
  1744. }
  1745. $_SESSION["mailcow_cc_username"] = $process_webauthn['username'];
  1746. $_SESSION['tfa_id'] = $process_webauthn['id'];
  1747. $_SESSION['authReq'] = null;
  1748. unset($_SESSION["challenge"]);
  1749. $_SESSION['return'][] = array(
  1750. 'type' => 'success',
  1751. 'log' => array("webauthn_login"),
  1752. 'msg' => array('logged_in_as', $process_webauthn['username'])
  1753. );
  1754. return true;
  1755. break;
  1756. default:
  1757. $_SESSION['return'][] = array(
  1758. 'type' => 'danger',
  1759. 'log' => array(__FUNCTION__, $username, '*'),
  1760. 'msg' => 'unknown_tfa_method'
  1761. );
  1762. return false;
  1763. break;
  1764. }
  1765. return false;
  1766. } else {
  1767. // delete old keys that used u2f
  1768. $stmt = $pdo->prepare("SELECT * FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username");
  1769. $stmt->execute(array(':username' => $username));
  1770. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1771. if (count($rows) == 0) return false;
  1772. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username");
  1773. $stmt->execute(array(':username' => $username));
  1774. return true;
  1775. }
  1776. }
  1777. function admin_api($access, $action, $data = null) {
  1778. global $pdo;
  1779. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1780. $_SESSION['return'][] = array(
  1781. 'type' => 'danger',
  1782. 'log' => array(__FUNCTION__),
  1783. 'msg' => 'access_denied'
  1784. );
  1785. return false;
  1786. }
  1787. if ($access !== "ro" && $access !== "rw") {
  1788. $_SESSION['return'][] = array(
  1789. 'type' => 'danger',
  1790. 'log' => array(__FUNCTION__),
  1791. 'msg' => 'invalid access type'
  1792. );
  1793. return false;
  1794. }
  1795. if ($action == "edit") {
  1796. $active = (!empty($data['active'])) ? 1 : 0;
  1797. $skip_ip_check = (isset($data['skip_ip_check'])) ? 1 : 0;
  1798. $allow_from = array();
  1799. if (isset($data['allow_from'])) {
  1800. $allow_from = array_map('trim', preg_split( "/( |,|;|\n)/", $data['allow_from']));
  1801. }
  1802. foreach ($allow_from as $key => $val) {
  1803. if (empty($val)) {
  1804. unset($allow_from[$key]);
  1805. continue;
  1806. }
  1807. if (valid_network($val) !== true) {
  1808. $_SESSION['return'][] = array(
  1809. 'type' => 'warning',
  1810. 'log' => array(__FUNCTION__, $data),
  1811. 'msg' => array('ip_invalid', htmlspecialchars($allow_from[$key]))
  1812. );
  1813. unset($allow_from[$key]);
  1814. continue;
  1815. }
  1816. }
  1817. $allow_from = implode(',', array_unique(array_filter($allow_from)));
  1818. if (empty($allow_from) && $skip_ip_check == 0) {
  1819. $_SESSION['return'][] = array(
  1820. 'type' => 'danger',
  1821. 'log' => array(__FUNCTION__, $data),
  1822. 'msg' => 'ip_list_empty'
  1823. );
  1824. return false;
  1825. }
  1826. $api_key = implode('-', array(
  1827. strtoupper(bin2hex(random_bytes(3))),
  1828. strtoupper(bin2hex(random_bytes(3))),
  1829. strtoupper(bin2hex(random_bytes(3))),
  1830. strtoupper(bin2hex(random_bytes(3))),
  1831. strtoupper(bin2hex(random_bytes(3)))
  1832. ));
  1833. $stmt = $pdo->query("SELECT `api_key` FROM `api` WHERE `access` = '" . $access . "'");
  1834. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  1835. if (empty($num_results)) {
  1836. $stmt = $pdo->prepare("INSERT INTO `api` (`api_key`, `skip_ip_check`, `active`, `allow_from`, `access`)
  1837. VALUES (:api_key, :skip_ip_check, :active, :allow_from, :access);");
  1838. $stmt->execute(array(
  1839. ':api_key' => $api_key,
  1840. ':skip_ip_check' => $skip_ip_check,
  1841. ':active' => $active,
  1842. ':allow_from' => $allow_from,
  1843. ':access' => $access
  1844. ));
  1845. }
  1846. else {
  1847. if ($skip_ip_check == 0) {
  1848. $stmt = $pdo->prepare("UPDATE `api` SET `skip_ip_check` = :skip_ip_check,
  1849. `active` = :active,
  1850. `allow_from` = :allow_from
  1851. WHERE `access` = :access;");
  1852. $stmt->execute(array(
  1853. ':active' => $active,
  1854. ':skip_ip_check' => $skip_ip_check,
  1855. ':allow_from' => $allow_from,
  1856. ':access' => $access
  1857. ));
  1858. }
  1859. else {
  1860. $stmt = $pdo->prepare("UPDATE `api` SET `skip_ip_check` = :skip_ip_check,
  1861. `active` = :active
  1862. WHERE `access` = :access;");
  1863. $stmt->execute(array(
  1864. ':active' => $active,
  1865. ':skip_ip_check' => $skip_ip_check,
  1866. ':access' => $access
  1867. ));
  1868. }
  1869. }
  1870. }
  1871. elseif ($action == "regen_key") {
  1872. $api_key = implode('-', array(
  1873. strtoupper(bin2hex(random_bytes(3))),
  1874. strtoupper(bin2hex(random_bytes(3))),
  1875. strtoupper(bin2hex(random_bytes(3))),
  1876. strtoupper(bin2hex(random_bytes(3))),
  1877. strtoupper(bin2hex(random_bytes(3)))
  1878. ));
  1879. $stmt = $pdo->prepare("UPDATE `api` SET `api_key` = :api_key WHERE `access` = :access");
  1880. $stmt->execute(array(
  1881. ':api_key' => $api_key,
  1882. ':access' => $access
  1883. ));
  1884. }
  1885. elseif ($action == "get") {
  1886. $stmt = $pdo->query("SELECT * FROM `api` WHERE `access` = '" . $access . "'");
  1887. $apidata = $stmt->fetch(PDO::FETCH_ASSOC);
  1888. if ($apidata !== false) {
  1889. $apidata['allow_from'] = str_replace(',', PHP_EOL, $apidata['allow_from']);
  1890. }
  1891. return $apidata;
  1892. }
  1893. $_SESSION['return'][] = array(
  1894. 'type' => 'success',
  1895. 'log' => array(__FUNCTION__, $data),
  1896. 'msg' => 'admin_api_modified'
  1897. );
  1898. }
  1899. function license($action, $data = null) {
  1900. global $pdo;
  1901. global $redis;
  1902. global $lang;
  1903. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1904. $_SESSION['return'][] = array(
  1905. 'type' => 'danger',
  1906. 'log' => array(__FUNCTION__),
  1907. 'msg' => 'access_denied'
  1908. );
  1909. return false;
  1910. }
  1911. switch ($action) {
  1912. case "verify":
  1913. // Keep result until revalidate button is pressed or session expired
  1914. $stmt = $pdo->query("SELECT `version` FROM `versions` WHERE `application` = 'GUID'");
  1915. $versions = $stmt->fetch(PDO::FETCH_ASSOC);
  1916. $post = array('guid' => $versions['version']);
  1917. $curl = curl_init('https://verify.mailcow.email');
  1918. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  1919. curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
  1920. curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
  1921. $response = curl_exec($curl);
  1922. curl_close($curl);
  1923. $json_return = json_decode($response, true);
  1924. if ($response && $json_return) {
  1925. if ($json_return['response'] === "ok") {
  1926. $_SESSION['gal']['valid'] = "true";
  1927. $_SESSION['gal']['c'] = $json_return['c'];
  1928. $_SESSION['gal']['s'] = $json_return['s'];
  1929. if ($json_return['m'] == 'NoMoore') {
  1930. $_SESSION['gal']['m'] = '🐄';
  1931. }
  1932. else {
  1933. $_SESSION['gal']['m'] = str_repeat('🐄', substr_count($json_return['m'], 'o'));
  1934. }
  1935. }
  1936. elseif ($json_return['response'] === "invalid") {
  1937. $_SESSION['gal']['valid'] = "false";
  1938. $_SESSION['gal']['c'] = $lang['mailbox']['no'];
  1939. $_SESSION['gal']['s'] = $lang['mailbox']['no'];
  1940. $_SESSION['gal']['m'] = $lang['mailbox']['no'];
  1941. }
  1942. }
  1943. else {
  1944. $_SESSION['gal']['valid'] = "false";
  1945. $_SESSION['gal']['c'] = $lang['danger']['temp_error'];
  1946. $_SESSION['gal']['s'] = $lang['danger']['temp_error'];
  1947. $_SESSION['gal']['m'] = $lang['danger']['temp_error'];
  1948. }
  1949. try {
  1950. // json_encode needs "true"/"false" instead of true/false, to not encode it to 0 or 1
  1951. $redis->Set('LICENSE_STATUS_CACHE', json_encode($_SESSION['gal']));
  1952. }
  1953. catch (RedisException $e) {
  1954. $_SESSION['return'][] = array(
  1955. 'type' => 'danger',
  1956. 'log' => array(__FUNCTION__, $_action, $_data_log),
  1957. 'msg' => array('redis_error', $e)
  1958. );
  1959. return false;
  1960. }
  1961. return $_SESSION['gal']['valid'];
  1962. break;
  1963. case "guid":
  1964. $stmt = $pdo->query("SELECT `version` FROM `versions` WHERE `application` = 'GUID'");
  1965. $versions = $stmt->fetch(PDO::FETCH_ASSOC);
  1966. return $versions['version'];
  1967. break;
  1968. }
  1969. }
  1970. function rspamd_ui($action, $data = null) {
  1971. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1972. $_SESSION['return'][] = array(
  1973. 'type' => 'danger',
  1974. 'log' => array(__FUNCTION__),
  1975. 'msg' => 'access_denied'
  1976. );
  1977. return false;
  1978. }
  1979. switch ($action) {
  1980. case "edit":
  1981. $rspamd_ui_pass = $data['rspamd_ui_pass'];
  1982. $rspamd_ui_pass2 = $data['rspamd_ui_pass2'];
  1983. if (empty($rspamd_ui_pass) || empty($rspamd_ui_pass2)) {
  1984. $_SESSION['return'][] = array(
  1985. 'type' => 'danger',
  1986. 'log' => array(__FUNCTION__, '*', '*'),
  1987. 'msg' => 'password_empty'
  1988. );
  1989. return false;
  1990. }
  1991. if ($rspamd_ui_pass != $rspamd_ui_pass2) {
  1992. $_SESSION['return'][] = array(
  1993. 'type' => 'danger',
  1994. 'log' => array(__FUNCTION__, '*', '*'),
  1995. 'msg' => 'password_mismatch'
  1996. );
  1997. return false;
  1998. }
  1999. if (strlen($rspamd_ui_pass) < 6) {
  2000. $_SESSION['return'][] = array(
  2001. 'type' => 'danger',
  2002. 'log' => array(__FUNCTION__, '*', '*'),
  2003. 'msg' => 'rspamd_ui_pw_length'
  2004. );
  2005. return false;
  2006. }
  2007. $docker_return = docker('post', 'rspamd-mailcow', 'exec', array('cmd' => 'rspamd', 'task' => 'worker_password', 'raw' => $rspamd_ui_pass), array('Content-Type: application/json'));
  2008. if ($docker_return_array = json_decode($docker_return, true)) {
  2009. if ($docker_return_array['type'] == 'success') {
  2010. $_SESSION['return'][] = array(
  2011. 'type' => 'success',
  2012. 'log' => array(__FUNCTION__, '*', '*'),
  2013. 'msg' => 'rspamd_ui_pw_set'
  2014. );
  2015. return true;
  2016. }
  2017. else {
  2018. $_SESSION['return'][] = array(
  2019. 'type' => $docker_return_array['type'],
  2020. 'log' => array(__FUNCTION__, '*', '*'),
  2021. 'msg' => $docker_return_array['msg']
  2022. );
  2023. return false;
  2024. }
  2025. }
  2026. else {
  2027. $_SESSION['return'][] = array(
  2028. 'type' => 'danger',
  2029. 'log' => array(__FUNCTION__, '*', '*'),
  2030. 'msg' => 'unknown'
  2031. );
  2032. return false;
  2033. }
  2034. break;
  2035. }
  2036. }
  2037. function get_logs($application, $lines = false) {
  2038. if ($lines === false) {
  2039. $lines = $GLOBALS['LOG_LINES'] - 1;
  2040. }
  2041. elseif(is_numeric($lines) && $lines >= 1) {
  2042. $lines = abs(intval($lines) - 1);
  2043. }
  2044. else {
  2045. list ($from, $to) = explode('-', $lines);
  2046. $from = intval($from);
  2047. $to = intval($to);
  2048. if ($from < 1 || $to < $from) { return false; }
  2049. }
  2050. global $redis;
  2051. global $pdo;
  2052. if ($_SESSION['mailcow_cc_role'] != "admin") {
  2053. return false;
  2054. }
  2055. // SQL
  2056. if ($application == "mailcow-ui") {
  2057. if (isset($from) && isset($to)) {
  2058. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :from, :to");
  2059. $stmt->execute(array(
  2060. ':from' => $from - 1,
  2061. ':to' => $to
  2062. ));
  2063. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2064. }
  2065. else {
  2066. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :lines");
  2067. $stmt->execute(array(
  2068. ':lines' => $lines + 1,
  2069. ));
  2070. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2071. }
  2072. if (is_array($data)) {
  2073. return $data;
  2074. }
  2075. }
  2076. if ($application == "sasl") {
  2077. if (isset($from) && isset($to)) {
  2078. $stmt = $pdo->prepare("SELECT * FROM `sasl_log` ORDER BY `datetime` DESC LIMIT :from, :to");
  2079. $stmt->execute(array(
  2080. ':from' => $from - 1,
  2081. ':to' => $to
  2082. ));
  2083. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2084. }
  2085. else {
  2086. $stmt = $pdo->prepare("SELECT * FROM `sasl_log` ORDER BY `datetime` DESC LIMIT :lines");
  2087. $stmt->execute(array(
  2088. ':lines' => $lines + 1,
  2089. ));
  2090. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2091. }
  2092. if (is_array($data)) {
  2093. return $data;
  2094. }
  2095. }
  2096. // Redis
  2097. if ($application == "dovecot-mailcow") {
  2098. if (isset($from) && isset($to)) {
  2099. $data = $redis->lRange('DOVECOT_MAILLOG', $from - 1, $to - 1);
  2100. }
  2101. else {
  2102. $data = $redis->lRange('DOVECOT_MAILLOG', 0, $lines);
  2103. }
  2104. if ($data) {
  2105. foreach ($data as $json_line) {
  2106. $data_array[] = json_decode($json_line, true);
  2107. }
  2108. return $data_array;
  2109. }
  2110. }
  2111. if ($application == "postfix-mailcow") {
  2112. if (isset($from) && isset($to)) {
  2113. $data = $redis->lRange('POSTFIX_MAILLOG', $from - 1, $to - 1);
  2114. }
  2115. else {
  2116. $data = $redis->lRange('POSTFIX_MAILLOG', 0, $lines);
  2117. }
  2118. if ($data) {
  2119. foreach ($data as $json_line) {
  2120. $data_array[] = json_decode($json_line, true);
  2121. }
  2122. return $data_array;
  2123. }
  2124. }
  2125. if ($application == "sogo-mailcow") {
  2126. if (isset($from) && isset($to)) {
  2127. $data = $redis->lRange('SOGO_LOG', $from - 1, $to - 1);
  2128. }
  2129. else {
  2130. $data = $redis->lRange('SOGO_LOG', 0, $lines);
  2131. }
  2132. if ($data) {
  2133. foreach ($data as $json_line) {
  2134. $data_array[] = json_decode($json_line, true);
  2135. }
  2136. return $data_array;
  2137. }
  2138. }
  2139. if ($application == "watchdog-mailcow") {
  2140. if (isset($from) && isset($to)) {
  2141. $data = $redis->lRange('WATCHDOG_LOG', $from - 1, $to - 1);
  2142. }
  2143. else {
  2144. $data = $redis->lRange('WATCHDOG_LOG', 0, $lines);
  2145. }
  2146. if ($data) {
  2147. foreach ($data as $json_line) {
  2148. $data_array[] = json_decode($json_line, true);
  2149. }
  2150. return $data_array;
  2151. }
  2152. }
  2153. if ($application == "acme-mailcow") {
  2154. if (isset($from) && isset($to)) {
  2155. $data = $redis->lRange('ACME_LOG', $from - 1, $to - 1);
  2156. }
  2157. else {
  2158. $data = $redis->lRange('ACME_LOG', 0, $lines);
  2159. }
  2160. if ($data) {
  2161. foreach ($data as $json_line) {
  2162. $data_array[] = json_decode($json_line, true);
  2163. }
  2164. return $data_array;
  2165. }
  2166. }
  2167. if ($application == "ratelimited") {
  2168. if (isset($from) && isset($to)) {
  2169. $data = $redis->lRange('RL_LOG', $from - 1, $to - 1);
  2170. }
  2171. else {
  2172. $data = $redis->lRange('RL_LOG', 0, $lines);
  2173. }
  2174. if ($data) {
  2175. foreach ($data as $json_line) {
  2176. $data_array[] = json_decode($json_line, true);
  2177. }
  2178. return $data_array;
  2179. }
  2180. }
  2181. if ($application == "api-mailcow") {
  2182. if (isset($from) && isset($to)) {
  2183. $data = $redis->lRange('API_LOG', $from - 1, $to - 1);
  2184. }
  2185. else {
  2186. $data = $redis->lRange('API_LOG', 0, $lines);
  2187. }
  2188. if ($data) {
  2189. foreach ($data as $json_line) {
  2190. $data_array[] = json_decode($json_line, true);
  2191. }
  2192. return $data_array;
  2193. }
  2194. }
  2195. if ($application == "netfilter-mailcow") {
  2196. if (isset($from) && isset($to)) {
  2197. $data = $redis->lRange('NETFILTER_LOG', $from - 1, $to - 1);
  2198. }
  2199. else {
  2200. $data = $redis->lRange('NETFILTER_LOG', 0, $lines);
  2201. }
  2202. if ($data) {
  2203. foreach ($data as $json_line) {
  2204. $data_array[] = json_decode($json_line, true);
  2205. }
  2206. return $data_array;
  2207. }
  2208. }
  2209. if ($application == "autodiscover-mailcow") {
  2210. if (isset($from) && isset($to)) {
  2211. $data = $redis->lRange('AUTODISCOVER_LOG', $from - 1, $to - 1);
  2212. }
  2213. else {
  2214. $data = $redis->lRange('AUTODISCOVER_LOG', 0, $lines);
  2215. }
  2216. if ($data) {
  2217. foreach ($data as $json_line) {
  2218. $data_array[] = json_decode($json_line, true);
  2219. }
  2220. return $data_array;
  2221. }
  2222. }
  2223. if ($application == "rspamd-history") {
  2224. $curl = curl_init();
  2225. curl_setopt($curl, CURLOPT_UNIX_SOCKET_PATH, '/var/lib/rspamd/rspamd.sock');
  2226. if (!is_numeric($lines)) {
  2227. list ($from, $to) = explode('-', $lines);
  2228. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?from=" . intval($from) . "&to=" . intval($to));
  2229. }
  2230. else {
  2231. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?to=" . intval($lines));
  2232. }
  2233. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2234. $history = curl_exec($curl);
  2235. if (!curl_errno($curl)) {
  2236. $data_array = json_decode($history, true);
  2237. curl_close($curl);
  2238. return $data_array['rows'];
  2239. }
  2240. curl_close($curl);
  2241. return false;
  2242. }
  2243. if ($application == "rspamd-stats") {
  2244. $curl = curl_init();
  2245. curl_setopt($curl, CURLOPT_UNIX_SOCKET_PATH, '/var/lib/rspamd/rspamd.sock');
  2246. curl_setopt($curl, CURLOPT_URL,"http://rspamd/stat");
  2247. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2248. $stats = curl_exec($curl);
  2249. if (!curl_errno($curl)) {
  2250. $data_array = json_decode($stats, true);
  2251. curl_close($curl);
  2252. return $data_array;
  2253. }
  2254. curl_close($curl);
  2255. return false;
  2256. }
  2257. return false;
  2258. }
  2259. function getGUID() {
  2260. if (function_exists('com_create_guid')) {
  2261. return com_create_guid();
  2262. }
  2263. mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
  2264. $charid = strtoupper(md5(uniqid(rand(), true)));
  2265. $hyphen = chr(45);// "-"
  2266. return substr($charid, 0, 8).$hyphen
  2267. .substr($charid, 8, 4).$hyphen
  2268. .substr($charid,12, 4).$hyphen
  2269. .substr($charid,16, 4).$hyphen
  2270. .substr($charid,20,12);
  2271. }
  2272. function solr_status() {
  2273. $curl = curl_init();
  2274. $endpoint = 'http://solr:8983/solr/admin/cores';
  2275. $params = array(
  2276. 'action' => 'STATUS',
  2277. 'core' => 'dovecot-fts',
  2278. 'indexInfo' => 'true'
  2279. );
  2280. $url = $endpoint . '?' . http_build_query($params);
  2281. curl_setopt($curl, CURLOPT_URL, $url);
  2282. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  2283. curl_setopt($curl, CURLOPT_POST, 0);
  2284. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  2285. $response_core = curl_exec($curl);
  2286. if ($response_core === false) {
  2287. $err = curl_error($curl);
  2288. curl_close($curl);
  2289. return false;
  2290. }
  2291. else {
  2292. curl_close($curl);
  2293. $curl = curl_init();
  2294. $status_core = json_decode($response_core, true);
  2295. $url = 'http://solr:8983/solr/admin/info/system';
  2296. curl_setopt($curl, CURLOPT_URL, $url);
  2297. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  2298. curl_setopt($curl, CURLOPT_POST, 0);
  2299. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  2300. $response_sysinfo = curl_exec($curl);
  2301. if ($response_sysinfo === false) {
  2302. $err = curl_error($curl);
  2303. curl_close($curl);
  2304. return false;
  2305. }
  2306. else {
  2307. curl_close($curl);
  2308. $status_sysinfo = json_decode($response_sysinfo, true);
  2309. $status = array_merge($status_core, $status_sysinfo);
  2310. return (!empty($status['status']['dovecot-fts']) && !empty($status['jvm']['memory'])) ? $status : false;
  2311. }
  2312. return (!empty($status['status']['dovecot-fts'])) ? $status['status']['dovecot-fts'] : false;
  2313. }
  2314. return false;
  2315. }
  2316. function cleanupJS($ignore = '', $folder = '/tmp/*.js') {
  2317. $now = time();
  2318. foreach (glob($folder) as $filename) {
  2319. if(strpos($filename, $ignore) !== false) {
  2320. continue;
  2321. }
  2322. if (is_file($filename)) {
  2323. if ($now - filemtime($filename) >= 60 * 60) {
  2324. unlink($filename);
  2325. }
  2326. }
  2327. }
  2328. }
  2329. function cleanupCSS($ignore = '', $folder = '/tmp/*.css') {
  2330. $now = time();
  2331. foreach (glob($folder) as $filename) {
  2332. if(strpos($filename, $ignore) !== false) {
  2333. continue;
  2334. }
  2335. if (is_file($filename)) {
  2336. if ($now - filemtime($filename) >= 60 * 60) {
  2337. unlink($filename);
  2338. }
  2339. }
  2340. }
  2341. }
  2342. ?>