functions.inc.php 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379
  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) {
  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 1');
  318. $stmt->execute(array(':username' => $username));
  319. $ui = $stmt->fetch(PDO::FETCH_ASSOC);
  320. }
  321. else {
  322. $ui = array();
  323. }
  324. return array('ui' => $ui, 'sasl' => $sasl);
  325. break;
  326. case 'reset':
  327. if (filter_var($username, FILTER_VALIDATE_EMAIL) && hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $username)) {
  328. $stmt = $pdo->prepare('DELETE FROM `sasl_log`
  329. WHERE `username` = :username');
  330. $stmt->execute(array(':username' => $username));
  331. }
  332. if ($_SESSION['mailcow_cc_role'] == "admin" || $username == $_SESSION['mailcow_cc_username']) {
  333. $stmt = $pdo->prepare('DELETE FROM `logs`
  334. WHERE JSON_EXTRACT(`call`, "$[0]") = "check_login"
  335. AND JSON_EXTRACT(`call`, "$[1]") = :username
  336. AND `type` = "success"');
  337. $stmt->execute(array(':username' => $username));
  338. }
  339. return true;
  340. break;
  341. }
  342. }
  343. function flush_memcached() {
  344. try {
  345. $m = new Memcached();
  346. $m->addServer('memcached', 11211);
  347. $m->flush();
  348. }
  349. catch ( Exception $e ) {
  350. // Dunno
  351. }
  352. }
  353. function sys_mail($_data) {
  354. if ($_SESSION['mailcow_cc_role'] != "admin") {
  355. $_SESSION['return'][] = array(
  356. 'type' => 'danger',
  357. 'log' => array(__FUNCTION__),
  358. 'msg' => 'access_denied'
  359. );
  360. return false;
  361. }
  362. $excludes = $_data['mass_exclude'];
  363. $includes = $_data['mass_include'];
  364. $mailboxes = array();
  365. $mass_from = $_data['mass_from'];
  366. $mass_text = $_data['mass_text'];
  367. $mass_html = $_data['mass_html'];
  368. $mass_subject = $_data['mass_subject'];
  369. if (!filter_var($mass_from, FILTER_VALIDATE_EMAIL)) {
  370. $_SESSION['return'][] = array(
  371. 'type' => 'danger',
  372. 'log' => array(__FUNCTION__),
  373. 'msg' => 'from_invalid'
  374. );
  375. return false;
  376. }
  377. if (empty($mass_subject)) {
  378. $_SESSION['return'][] = array(
  379. 'type' => 'danger',
  380. 'log' => array(__FUNCTION__),
  381. 'msg' => 'subject_empty'
  382. );
  383. return false;
  384. }
  385. if (empty($mass_text)) {
  386. $_SESSION['return'][] = array(
  387. 'type' => 'danger',
  388. 'log' => array(__FUNCTION__),
  389. 'msg' => 'text_empty'
  390. );
  391. return false;
  392. }
  393. $domains = array_merge(mailbox('get', 'domains'), mailbox('get', 'alias_domains'));
  394. foreach ($domains as $domain) {
  395. foreach (mailbox('get', 'mailboxes', $domain) as $mailbox) {
  396. $mailboxes[] = $mailbox;
  397. }
  398. }
  399. if (!empty($includes)) {
  400. $rcpts = array_intersect($mailboxes, $includes);
  401. }
  402. elseif (!empty($excludes)) {
  403. $rcpts = array_diff($mailboxes, $excludes);
  404. }
  405. else {
  406. $rcpts = $mailboxes;
  407. }
  408. if (!empty($rcpts)) {
  409. ini_set('max_execution_time', 0);
  410. ini_set('max_input_time', 0);
  411. $mail = new PHPMailer;
  412. $mail->Timeout = 10;
  413. $mail->SMTPOptions = array(
  414. 'ssl' => array(
  415. 'verify_peer' => false,
  416. 'verify_peer_name' => false,
  417. 'allow_self_signed' => true
  418. )
  419. );
  420. $mail->isSMTP();
  421. $mail->Host = 'dovecot-mailcow';
  422. $mail->SMTPAuth = false;
  423. $mail->Port = 24;
  424. $mail->setFrom($mass_from);
  425. $mail->Subject = $mass_subject;
  426. $mail->CharSet ="UTF-8";
  427. if (!empty($mass_html)) {
  428. $mail->Body = $mass_html;
  429. $mail->AltBody = $mass_text;
  430. }
  431. else {
  432. $mail->Body = $mass_text;
  433. }
  434. $mail->XMailer = 'MooMassMail';
  435. foreach ($rcpts as $rcpt) {
  436. $mail->AddAddress($rcpt);
  437. if (!$mail->send()) {
  438. $_SESSION['return'][] = array(
  439. 'type' => 'warning',
  440. 'log' => array(__FUNCTION__),
  441. 'msg' => 'Mailer error (RCPT "' . htmlspecialchars($rcpt) . '"): ' . str_replace('https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting', '', $mail->ErrorInfo)
  442. );
  443. }
  444. $mail->ClearAllRecipients();
  445. }
  446. }
  447. $_SESSION['return'][] = array(
  448. 'type' => 'success',
  449. 'log' => array(__FUNCTION__),
  450. 'msg' => 'Mass mail job completed, sent ' . count($rcpts) . ' mails'
  451. );
  452. }
  453. function logger($_data = false) {
  454. /*
  455. logger() will be called as last function
  456. To manually log a message, logger needs to be called like below.
  457. logger(array(
  458. 'return' => array(
  459. array(
  460. 'type' => 'danger',
  461. 'log' => array(__FUNCTION__),
  462. 'msg' => $err
  463. )
  464. )
  465. ));
  466. These messages will not be printed as alert box.
  467. To do so, push them to $_SESSION['return'] and do not call logger as they will be included automatically:
  468. $_SESSION['return'][] = array(
  469. 'type' => 'danger',
  470. 'log' => array(__FUNCTION__, $user, '*'),
  471. 'msg' => $err
  472. );
  473. */
  474. global $pdo;
  475. if (!$_data) {
  476. $_data = $_SESSION;
  477. }
  478. if (!empty($_data['return'])) {
  479. $task = substr(strtoupper(md5(uniqid(rand(), true))), 0, 6);
  480. foreach ($_data['return'] as $return) {
  481. $type = $return['type'];
  482. $msg = null;
  483. if (isset($return['msg'])) {
  484. $msg = json_encode($return['msg'], JSON_UNESCAPED_UNICODE);
  485. }
  486. $call = null;
  487. if (isset($return['log'])) {
  488. $call = json_encode($return['log'], JSON_UNESCAPED_UNICODE);
  489. }
  490. if (!empty($_SESSION["dual-login"]["username"])) {
  491. $user = $_SESSION["dual-login"]["username"] . ' => ' . $_SESSION['mailcow_cc_username'];
  492. $role = $_SESSION["dual-login"]["role"] . ' => ' . $_SESSION['mailcow_cc_role'];
  493. }
  494. elseif (!empty($_SESSION['mailcow_cc_username'])) {
  495. $user = $_SESSION['mailcow_cc_username'];
  496. $role = $_SESSION['mailcow_cc_role'];
  497. }
  498. else {
  499. $user = 'unauthenticated';
  500. $role = 'unauthenticated';
  501. }
  502. // We cannot log when logs is missing...
  503. try {
  504. $stmt = $pdo->prepare("INSERT INTO `logs` (`type`, `task`, `msg`, `call`, `user`, `role`, `remote`, `time`) VALUES
  505. (:type, :task, :msg, :call, :user, :role, :remote, UNIX_TIMESTAMP())");
  506. $stmt->execute(array(
  507. ':type' => $type,
  508. ':task' => $task,
  509. ':call' => $call,
  510. ':msg' => $msg,
  511. ':user' => $user,
  512. ':role' => $role,
  513. ':remote' => get_remote_ip()
  514. ));
  515. }
  516. catch (Exception $e) {
  517. // Do nothing
  518. }
  519. }
  520. }
  521. else {
  522. return true;
  523. }
  524. }
  525. function hasDomainAccess($username, $role, $domain) {
  526. global $pdo;
  527. if (!filter_var($username, FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $username))) {
  528. return false;
  529. }
  530. if (empty($domain) || !is_valid_domain_name($domain)) {
  531. return false;
  532. }
  533. if ($role != 'admin' && $role != 'domainadmin') {
  534. return false;
  535. }
  536. if ($role == 'admin') {
  537. $stmt = $pdo->prepare("SELECT `domain` FROM `domain`
  538. WHERE `domain` = :domain");
  539. $stmt->execute(array(':domain' => $domain));
  540. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  541. $stmt = $pdo->prepare("SELECT `alias_domain` FROM `alias_domain`
  542. WHERE `alias_domain` = :domain");
  543. $stmt->execute(array(':domain' => $domain));
  544. $num_results = $num_results + count($stmt->fetchAll(PDO::FETCH_ASSOC));
  545. if ($num_results != 0) {
  546. return true;
  547. }
  548. }
  549. elseif ($role == 'domainadmin') {
  550. $stmt = $pdo->prepare("SELECT `domain` FROM `domain_admins`
  551. WHERE (
  552. `active`='1'
  553. AND `username` = :username
  554. AND (`domain` = :domain1 OR `domain` = (SELECT `target_domain` FROM `alias_domain` WHERE `alias_domain` = :domain2))
  555. )");
  556. $stmt->execute(array(':username' => $username, ':domain1' => $domain, ':domain2' => $domain));
  557. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  558. if (!empty($num_results)) {
  559. return true;
  560. }
  561. }
  562. return false;
  563. }
  564. function hasMailboxObjectAccess($username, $role, $object) {
  565. global $pdo;
  566. if (empty($username) || empty($role) || empty($object)) {
  567. return false;
  568. }
  569. if (!filter_var(html_entity_decode(rawurldecode($username)), FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $username))) {
  570. return false;
  571. }
  572. if ($role != 'admin' && $role != 'domainadmin' && $role != 'user') {
  573. return false;
  574. }
  575. if ($username == $object) {
  576. return true;
  577. }
  578. $stmt = $pdo->prepare("SELECT `domain` FROM `mailbox` WHERE `username` = :object");
  579. $stmt->execute(array(':object' => $object));
  580. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  581. if (isset($row['domain']) && hasDomainAccess($username, $role, $row['domain'])) {
  582. return true;
  583. }
  584. return false;
  585. }
  586. // does also verify mailboxes as a mailbox is a alias == goto
  587. function hasAliasObjectAccess($username, $role, $object) {
  588. global $pdo;
  589. if (empty($username) || empty($role) || empty($object)) {
  590. return false;
  591. }
  592. if (!filter_var(html_entity_decode(rawurldecode($username)), FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $username))) {
  593. return false;
  594. }
  595. if ($role != 'admin' && $role != 'domainadmin' && $role != 'user') {
  596. return false;
  597. }
  598. $stmt = $pdo->prepare("SELECT `domain` FROM `alias` WHERE `address` = :object");
  599. $stmt->execute(array(':object' => $object));
  600. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  601. if (isset($row['domain']) && hasDomainAccess($username, $role, $row['domain'])) {
  602. return true;
  603. }
  604. return false;
  605. }
  606. function pem_to_der($pem_key) {
  607. // Need to remove BEGIN/END PUBLIC KEY
  608. $lines = explode("\n", trim($pem_key));
  609. unset($lines[count($lines)-1]);
  610. unset($lines[0]);
  611. return base64_decode(implode('', $lines));
  612. }
  613. function expand_ipv6($ip) {
  614. $hex = unpack("H*hex", inet_pton($ip));
  615. $ip = substr(preg_replace("/([A-f0-9]{4})/", "$1:", $hex['hex']), 0, -1);
  616. return $ip;
  617. }
  618. function generate_tlsa_digest($hostname, $port, $starttls = null) {
  619. if (!is_valid_domain_name($hostname)) {
  620. return "Not a valid hostname";
  621. }
  622. if (empty($starttls)) {
  623. $context = stream_context_create(array("ssl" => array("capture_peer_cert" => true, 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true)));
  624. $stream = stream_socket_client('ssl://' . $hostname . ':' . $port, $error_nr, $error_msg, 5, STREAM_CLIENT_CONNECT, $context);
  625. if (!$stream) {
  626. $error_msg = isset($error_msg) ? $error_msg : '-';
  627. return $error_nr . ': ' . $error_msg;
  628. }
  629. }
  630. else {
  631. $stream = stream_socket_client('tcp://' . $hostname . ':' . $port, $error_nr, $error_msg, 5);
  632. if (!$stream) {
  633. return $error_nr . ': ' . $error_msg;
  634. }
  635. $banner = fread($stream, 512 );
  636. if (preg_match("/^220/i", $banner)) { // SMTP
  637. fwrite($stream,"HELO tlsa.generator.local\r\n");
  638. fread($stream, 512);
  639. fwrite($stream,"STARTTLS\r\n");
  640. fread($stream, 512);
  641. }
  642. elseif (preg_match("/imap.+starttls/i", $banner)) { // IMAP
  643. fwrite($stream,"A1 STARTTLS\r\n");
  644. fread($stream, 512);
  645. }
  646. elseif (preg_match("/^\+OK/", $banner)) { // POP3
  647. fwrite($stream,"STLS\r\n");
  648. fread($stream, 512);
  649. }
  650. elseif (preg_match("/^OK/m", $banner)) { // Sieve
  651. fwrite($stream,"STARTTLS\r\n");
  652. fread($stream, 512);
  653. }
  654. else {
  655. return 'Unknown banner: "' . htmlspecialchars(trim($banner)) . '"';
  656. }
  657. // Upgrade connection
  658. stream_set_blocking($stream, true);
  659. stream_context_set_option($stream, 'ssl', 'capture_peer_cert', true);
  660. stream_context_set_option($stream, 'ssl', 'verify_peer', false);
  661. stream_context_set_option($stream, 'ssl', 'verify_peer_name', false);
  662. stream_context_set_option($stream, 'ssl', 'allow_self_signed', true);
  663. stream_socket_enable_crypto($stream, true, STREAM_CRYPTO_METHOD_ANY_CLIENT);
  664. stream_set_blocking($stream, false);
  665. }
  666. $params = stream_context_get_params($stream);
  667. if (!empty($params['options']['ssl']['peer_certificate'])) {
  668. $key_resource = openssl_pkey_get_public($params['options']['ssl']['peer_certificate']);
  669. // We cannot get ['rsa']['n'], the binary data would contain BEGIN/END PUBLIC KEY
  670. $key_data = openssl_pkey_get_details($key_resource)['key'];
  671. return '3 1 1 ' . openssl_digest(pem_to_der($key_data), 'sha256');
  672. }
  673. else {
  674. return 'Error: Cannot read peer certificate';
  675. }
  676. }
  677. function alertbox_log_parser($_data) {
  678. global $lang;
  679. if (isset($_data['return'])) {
  680. foreach ($_data['return'] as $return) {
  681. // Get type
  682. $type = $return['type'];
  683. // If a lang[type][msg] string exists, use it as message
  684. if (isset($return['type']) && isset($return['msg']) && !is_array($return['msg'])) {
  685. if (isset($lang[$return['type']][$return['msg']])) {
  686. $msg = $lang[$return['type']][$return['msg']];
  687. }
  688. else {
  689. $msg = $return['msg'];
  690. }
  691. }
  692. // If msg is an array, use first element as language string and run printf on it with remaining array elements
  693. elseif (is_array($return['msg'])) {
  694. $msg = array_shift($return['msg']);
  695. $msg = vsprintf(
  696. $lang[$return['type']][$msg],
  697. $return['msg']
  698. );
  699. }
  700. else {
  701. $msg = '-';
  702. }
  703. $log_array[] = array('msg' => $msg, 'type' => json_encode($type));
  704. }
  705. if (!empty($log_array)) {
  706. return $log_array;
  707. }
  708. }
  709. return false;
  710. }
  711. function verify_salted_hash($hash, $password, $algo, $salt_length) {
  712. // Decode hash
  713. $dhash = base64_decode($hash);
  714. // Get first n bytes of binary which equals a SSHA hash
  715. $ohash = substr($dhash, 0, $salt_length);
  716. // Remove SSHA hash from decoded hash to get original salt string
  717. $osalt = str_replace($ohash, '', $dhash);
  718. // Check single salted SSHA hash against extracted hash
  719. if (hash_equals(hash($algo, $password . $osalt, true), $ohash)) {
  720. return true;
  721. }
  722. return false;
  723. }
  724. function verify_hash($hash, $password) {
  725. if (preg_match('/^{(.+)}(.+)/i', $hash, $hash_array)) {
  726. $scheme = strtoupper($hash_array[1]);
  727. $hash = $hash_array[2];
  728. switch ($scheme) {
  729. case "ARGON2I":
  730. case "ARGON2ID":
  731. case "BLF-CRYPT":
  732. case "CRYPT":
  733. case "DES-CRYPT":
  734. case "MD5-CRYPT":
  735. case "MD5":
  736. case "SHA256-CRYPT":
  737. case "SHA512-CRYPT":
  738. return password_verify($password, $hash);
  739. case "CLEAR":
  740. case "CLEARTEXT":
  741. case "PLAIN":
  742. return $password == $hash;
  743. case "LDAP-MD5":
  744. $hash = base64_decode($hash);
  745. return hash_equals(hash('md5', $password, true), $hash);
  746. case "PBKDF2":
  747. $components = explode('$', $hash);
  748. $salt = $components[2];
  749. $rounds = $components[3];
  750. $hash = $components[4];
  751. return hash_equals(hash_pbkdf2('sha1', $password, $salt, $rounds), $hash);
  752. case "PLAIN-MD4":
  753. return hash_equals(hash('md4', $password), $hash);
  754. case "PLAIN-MD5":
  755. return md5($password) == $hash;
  756. case "PLAIN-TRUNC":
  757. $components = explode('-', $hash);
  758. if (count($components) > 1) {
  759. $trunc_len = $components[0];
  760. $trunc_password = $components[1];
  761. return substr($password, 0, $trunc_len) == $trunc_password;
  762. } else {
  763. return $password == $hash;
  764. }
  765. case "SHA":
  766. case "SHA1":
  767. case "SHA256":
  768. case "SHA512":
  769. // SHA is an alias for SHA1
  770. $scheme = $scheme == "SHA" ? "sha1" : strtolower($scheme);
  771. $hash = base64_decode($hash);
  772. return hash_equals(hash($scheme, $password, true), $hash);
  773. case "SMD5":
  774. return verify_salted_hash($hash, $password, 'md5', 16);
  775. case "SSHA":
  776. return verify_salted_hash($hash, $password, 'sha1', 20);
  777. case "SSHA256":
  778. return verify_salted_hash($hash, $password, 'sha256', 32);
  779. case "SSHA512":
  780. return verify_salted_hash($hash, $password, 'sha512', 64);
  781. default:
  782. return false;
  783. }
  784. }
  785. return false;
  786. }
  787. function check_login($user, $pass, $app_passwd_data = false) {
  788. global $pdo;
  789. global $redis;
  790. global $imap_server;
  791. if (!filter_var($user, FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $user))) {
  792. $_SESSION['return'][] = array(
  793. 'type' => 'danger',
  794. 'log' => array(__FUNCTION__, $user, '*'),
  795. 'msg' => 'malformed_username'
  796. );
  797. return false;
  798. }
  799. // Validate admin
  800. $user = strtolower(trim($user));
  801. $stmt = $pdo->prepare("SELECT `password` FROM `admin`
  802. WHERE `superadmin` = '1'
  803. AND `active` = '1'
  804. AND `username` = :user");
  805. $stmt->execute(array(':user' => $user));
  806. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  807. foreach ($rows as $row) {
  808. // verify password
  809. if (verify_hash($row['password'], $pass)) {
  810. // check for tfa authenticators
  811. $authenticators = get_tfa($user);
  812. if (isset($authenticators['additional']) && is_array($authenticators['additional']) && count($authenticators['additional']) > 0) {
  813. // active tfa authenticators found, set pending user login
  814. $_SESSION['pending_mailcow_cc_username'] = $user;
  815. $_SESSION['pending_mailcow_cc_role'] = "admin";
  816. $_SESSION['pending_tfa_methods'] = $authenticators['additional'];
  817. unset($_SESSION['ldelay']);
  818. $_SESSION['return'][] = array(
  819. 'type' => 'info',
  820. 'log' => array(__FUNCTION__, $user, '*'),
  821. 'msg' => 'awaiting_tfa_confirmation'
  822. );
  823. return "pending";
  824. } else {
  825. unset($_SESSION['ldelay']);
  826. // Reactivate TFA if it was set to "deactivate TFA for next login"
  827. $stmt = $pdo->prepare("UPDATE `tfa` SET `active`='1' WHERE `username` = :user");
  828. $stmt->execute(array(':user' => $user));
  829. $_SESSION['return'][] = array(
  830. 'type' => 'success',
  831. 'log' => array(__FUNCTION__, $user, '*'),
  832. 'msg' => array('logged_in_as', $user)
  833. );
  834. return "admin";
  835. }
  836. }
  837. }
  838. // Validate domain admin
  839. $stmt = $pdo->prepare("SELECT `password` FROM `admin`
  840. WHERE `superadmin` = '0'
  841. AND `active`='1'
  842. AND `username` = :user");
  843. $stmt->execute(array(':user' => $user));
  844. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  845. foreach ($rows as $row) {
  846. // verify password
  847. if (verify_hash($row['password'], $pass) !== false) {
  848. // check for tfa authenticators
  849. $authenticators = get_tfa($user);
  850. if (isset($authenticators['additional']) && is_array($authenticators['additional']) && count($authenticators['additional']) > 0) {
  851. $_SESSION['pending_mailcow_cc_username'] = $user;
  852. $_SESSION['pending_mailcow_cc_role'] = "domainadmin";
  853. $_SESSION['pending_tfa_methods'] = $authenticators['additional'];
  854. unset($_SESSION['ldelay']);
  855. $_SESSION['return'][] = array(
  856. 'type' => 'info',
  857. 'log' => array(__FUNCTION__, $user, '*'),
  858. 'msg' => 'awaiting_tfa_confirmation'
  859. );
  860. return "pending";
  861. }
  862. else {
  863. unset($_SESSION['ldelay']);
  864. // Reactivate TFA if it was set to "deactivate TFA for next login"
  865. $stmt = $pdo->prepare("UPDATE `tfa` SET `active`='1' WHERE `username` = :user");
  866. $stmt->execute(array(':user' => $user));
  867. $_SESSION['return'][] = array(
  868. 'type' => 'success',
  869. 'log' => array(__FUNCTION__, $user, '*'),
  870. 'msg' => array('logged_in_as', $user)
  871. );
  872. return "domainadmin";
  873. }
  874. }
  875. }
  876. // Validate mailbox user
  877. $stmt = $pdo->prepare("SELECT `password` FROM `mailbox`
  878. INNER JOIN domain on mailbox.domain = domain.domain
  879. WHERE `kind` NOT REGEXP 'location|thing|group'
  880. AND `mailbox`.`active`='1'
  881. AND `domain`.`active`='1'
  882. AND `username` = :user");
  883. $stmt->execute(array(':user' => $user));
  884. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  885. if ($app_passwd_data['eas'] === true) {
  886. $stmt = $pdo->prepare("SELECT `app_passwd`.`password` as `password`, `app_passwd`.`id` as `app_passwd_id` FROM `app_passwd`
  887. INNER JOIN `mailbox` ON `mailbox`.`username` = `app_passwd`.`mailbox`
  888. INNER JOIN `domain` ON `mailbox`.`domain` = `domain`.`domain`
  889. WHERE `mailbox`.`kind` NOT REGEXP 'location|thing|group'
  890. AND `mailbox`.`active` = '1'
  891. AND `domain`.`active` = '1'
  892. AND `app_passwd`.`active` = '1'
  893. AND `app_passwd`.`eas_access` = '1'
  894. AND `app_passwd`.`mailbox` = :user");
  895. $stmt->execute(array(':user' => $user));
  896. $rows = array_merge($rows, $stmt->fetchAll(PDO::FETCH_ASSOC));
  897. }
  898. elseif ($app_passwd_data['dav'] === true) {
  899. $stmt = $pdo->prepare("SELECT `app_passwd`.`password` as `password`, `app_passwd`.`id` as `app_passwd_id` FROM `app_passwd`
  900. INNER JOIN `mailbox` ON `mailbox`.`username` = `app_passwd`.`mailbox`
  901. INNER JOIN `domain` ON `mailbox`.`domain` = `domain`.`domain`
  902. WHERE `mailbox`.`kind` NOT REGEXP 'location|thing|group'
  903. AND `mailbox`.`active` = '1'
  904. AND `domain`.`active` = '1'
  905. AND `app_passwd`.`active` = '1'
  906. AND `app_passwd`.`dav_access` = '1'
  907. AND `app_passwd`.`mailbox` = :user");
  908. $stmt->execute(array(':user' => $user));
  909. $rows = array_merge($rows, $stmt->fetchAll(PDO::FETCH_ASSOC));
  910. }
  911. foreach ($rows as $row) {
  912. if (verify_hash($row['password'], $pass) !== false) {
  913. unset($_SESSION['ldelay']);
  914. $_SESSION['return'][] = array(
  915. 'type' => 'success',
  916. 'log' => array(__FUNCTION__, $user, '*'),
  917. 'msg' => array('logged_in_as', $user)
  918. );
  919. if ($app_passwd_data['eas'] === true || $app_passwd_data['dav'] === true) {
  920. $service = ($app_passwd_data['eas'] === true) ? 'EAS' : 'DAV';
  921. $stmt = $pdo->prepare("REPLACE INTO sasl_log (`service`, `app_password`, `username`, `real_rip`) VALUES (:service, :app_id, :username, :remote_addr)");
  922. $stmt->execute(array(
  923. ':service' => $service,
  924. ':app_id' => $row['app_passwd_id'],
  925. ':username' => $user,
  926. ':remote_addr' => ($_SERVER['HTTP_X_REAL_IP'] ?? $_SERVER['REMOTE_ADDR'])
  927. ));
  928. }
  929. return "user";
  930. }
  931. }
  932. if (!isset($_SESSION['ldelay'])) {
  933. $_SESSION['ldelay'] = "0";
  934. $redis->publish("F2B_CHANNEL", "mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  935. error_log("mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  936. }
  937. elseif (!isset($_SESSION['mailcow_cc_username'])) {
  938. $_SESSION['ldelay'] = $_SESSION['ldelay']+0.5;
  939. $redis->publish("F2B_CHANNEL", "mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  940. error_log("mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  941. }
  942. $_SESSION['return'][] = array(
  943. 'type' => 'danger',
  944. 'log' => array(__FUNCTION__, $user, '*'),
  945. 'msg' => 'login_failed'
  946. );
  947. sleep($_SESSION['ldelay']);
  948. return false;
  949. }
  950. function formatBytes($size, $precision = 2) {
  951. if(!is_numeric($size)) {
  952. return "0";
  953. }
  954. $base = log($size, 1024);
  955. $suffixes = array(' Byte', ' KiB', ' MiB', ' GiB', ' TiB');
  956. if ($size == "0") {
  957. return "0";
  958. }
  959. return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
  960. }
  961. function update_sogo_static_view() {
  962. if (getenv('SKIP_SOGO') == "y") {
  963. return true;
  964. }
  965. global $pdo;
  966. global $lang;
  967. $stmt = $pdo->query("SELECT 'OK' FROM INFORMATION_SCHEMA.TABLES
  968. WHERE TABLE_NAME = 'sogo_view'");
  969. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  970. if ($num_results != 0) {
  971. $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`)
  972. SELECT `c_uid`, `domain`, `c_name`, `c_password`, `c_cn`, `mail`, `aliases`, `ad_aliases`, `ext_acl`, `kind`, `multiple_bookings` from sogo_view");
  973. $stmt = $pdo->query("DELETE FROM _sogo_static_view WHERE `c_uid` NOT IN (SELECT `username` FROM `mailbox` WHERE `active` = '1');");
  974. }
  975. flush_memcached();
  976. }
  977. function edit_user_account($_data) {
  978. global $lang;
  979. global $pdo;
  980. $_data_log = $_data;
  981. !isset($_data_log['user_new_pass']) ?: $_data_log['user_new_pass'] = '*';
  982. !isset($_data_log['user_new_pass2']) ?: $_data_log['user_new_pass2'] = '*';
  983. !isset($_data_log['user_old_pass']) ?: $_data_log['user_old_pass'] = '*';
  984. $username = $_SESSION['mailcow_cc_username'];
  985. $role = $_SESSION['mailcow_cc_role'];
  986. $password_old = $_data['user_old_pass'];
  987. if (filter_var($username, FILTER_VALIDATE_EMAIL === false) || $role != 'user') {
  988. $_SESSION['return'][] = array(
  989. 'type' => 'danger',
  990. 'log' => array(__FUNCTION__, $_data_log),
  991. 'msg' => 'access_denied'
  992. );
  993. return false;
  994. }
  995. $stmt = $pdo->prepare("SELECT `password` FROM `mailbox`
  996. WHERE `kind` NOT REGEXP 'location|thing|group'
  997. AND `username` = :user");
  998. $stmt->execute(array(':user' => $username));
  999. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1000. if (!verify_hash($row['password'], $password_old)) {
  1001. $_SESSION['return'][] = array(
  1002. 'type' => 'danger',
  1003. 'log' => array(__FUNCTION__, $_data_log),
  1004. 'msg' => 'access_denied'
  1005. );
  1006. return false;
  1007. }
  1008. if (!empty($_data['user_new_pass']) && !empty($_data['user_new_pass2'])) {
  1009. $password_new = $_data['user_new_pass'];
  1010. $password_new2 = $_data['user_new_pass2'];
  1011. if (password_check($password_new, $password_new2) !== true) {
  1012. return false;
  1013. }
  1014. $password_hashed = hash_password($password_new);
  1015. $stmt = $pdo->prepare("UPDATE `mailbox` SET `password` = :password_hashed,
  1016. `attributes` = JSON_SET(`attributes`, '$.force_pw_update', '0'),
  1017. `attributes` = JSON_SET(`attributes`, '$.passwd_update', NOW())
  1018. WHERE `username` = :username");
  1019. $stmt->execute(array(
  1020. ':password_hashed' => $password_hashed,
  1021. ':username' => $username
  1022. ));
  1023. }
  1024. update_sogo_static_view();
  1025. $_SESSION['return'][] = array(
  1026. 'type' => 'success',
  1027. 'log' => array(__FUNCTION__, $_data_log),
  1028. 'msg' => array('mailbox_modified', htmlspecialchars($username))
  1029. );
  1030. }
  1031. function user_get_alias_details($username) {
  1032. global $pdo;
  1033. global $lang;
  1034. $data['direct_aliases'] = array();
  1035. $data['shared_aliases'] = array();
  1036. if ($_SESSION['mailcow_cc_role'] == "user") {
  1037. $username = $_SESSION['mailcow_cc_username'];
  1038. }
  1039. if (!filter_var($username, FILTER_VALIDATE_EMAIL)) {
  1040. return false;
  1041. }
  1042. if (!hasMailboxObjectAccess($username, $_SESSION['mailcow_cc_role'], $username)) {
  1043. return false;
  1044. }
  1045. $data['address'] = $username;
  1046. $stmt = $pdo->prepare("SELECT `address` AS `shared_aliases`, `public_comment` FROM `alias`
  1047. WHERE `goto` REGEXP :username_goto
  1048. AND `address` NOT LIKE '@%'
  1049. AND `goto` != :username_goto2
  1050. AND `address` != :username_address");
  1051. $stmt->execute(array(
  1052. ':username_goto' => '(^|,)'.$username.'($|,)',
  1053. ':username_goto2' => $username,
  1054. ':username_address' => $username
  1055. ));
  1056. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1057. while ($row = array_shift($run)) {
  1058. $data['shared_aliases'][$row['shared_aliases']]['public_comment'] = htmlspecialchars($row['public_comment']);
  1059. //$data['shared_aliases'][] = $row['shared_aliases'];
  1060. }
  1061. $stmt = $pdo->prepare("SELECT `address` AS `direct_aliases`, `public_comment` FROM `alias`
  1062. WHERE `goto` = :username_goto
  1063. AND `address` NOT LIKE '@%'
  1064. AND `address` != :username_address");
  1065. $stmt->execute(
  1066. array(
  1067. ':username_goto' => $username,
  1068. ':username_address' => $username
  1069. ));
  1070. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1071. while ($row = array_shift($run)) {
  1072. $data['direct_aliases'][$row['direct_aliases']]['public_comment'] = htmlspecialchars($row['public_comment']);
  1073. }
  1074. $stmt = $pdo->prepare("SELECT CONCAT(local_part, '@', alias_domain) AS `ad_alias`, `alias_domain` FROM `mailbox`
  1075. LEFT OUTER JOIN `alias_domain` on `target_domain` = `domain`
  1076. WHERE `username` = :username ;");
  1077. $stmt->execute(array(':username' => $username));
  1078. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1079. while ($row = array_shift($run)) {
  1080. if (empty($row['ad_alias'])) {
  1081. continue;
  1082. }
  1083. $data['direct_aliases'][$row['ad_alias']]['public_comment'] = $lang['add']['alias_domain'];
  1084. $data['alias_domains'][] = $row['alias_domain'];
  1085. }
  1086. $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 '@%';");
  1087. $stmt->execute(array(':username' => $username));
  1088. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1089. while ($row = array_shift($run)) {
  1090. $data['aliases_also_send_as'] = $row['send_as'];
  1091. }
  1092. $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 '@%';");
  1093. $stmt->execute(array(':username' => $username));
  1094. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1095. while ($row = array_shift($run)) {
  1096. $data['aliases_send_as_all'] = $row['send_as'];
  1097. }
  1098. $stmt = $pdo->prepare("SELECT IFNULL(GROUP_CONCAT(`address` SEPARATOR ', '), '') as `address` FROM `alias` WHERE `goto` REGEXP :username AND `address` LIKE '@%';");
  1099. $stmt->execute(array(':username' => '(^|,)'.$username.'($|,)'));
  1100. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1101. while ($row = array_shift($run)) {
  1102. $data['is_catch_all'] = $row['address'];
  1103. }
  1104. return $data;
  1105. }
  1106. function is_valid_domain_name($domain_name) {
  1107. if (empty($domain_name)) {
  1108. return false;
  1109. }
  1110. $domain_name = idn_to_ascii($domain_name, 0, INTL_IDNA_VARIANT_UTS46);
  1111. return (preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $domain_name)
  1112. && preg_match("/^.{1,253}$/", $domain_name)
  1113. && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $domain_name));
  1114. }
  1115. function set_tfa($_data) {
  1116. global $pdo;
  1117. global $yubi;
  1118. global $tfa;
  1119. $_data_log = $_data;
  1120. $access_denied = null;
  1121. !isset($_data_log['confirm_password']) ?: $_data_log['confirm_password'] = '*';
  1122. $username = $_SESSION['mailcow_cc_username'];
  1123. // check for empty user and role
  1124. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) $access_denied = true;
  1125. // check admin confirm password
  1126. if ($access_denied === null) {
  1127. $stmt = $pdo->prepare("SELECT `password` FROM `admin`
  1128. WHERE `username` = :username");
  1129. $stmt->execute(array(':username' => $username));
  1130. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1131. if ($row) {
  1132. if (!verify_hash($row['password'], $_data["confirm_password"])) $access_denied = true;
  1133. else $access_denied = false;
  1134. }
  1135. }
  1136. // check mailbox confirm password
  1137. if ($access_denied === null) {
  1138. $stmt = $pdo->prepare("SELECT `password` FROM `mailbox`
  1139. WHERE `username` = :username");
  1140. $stmt->execute(array(':username' => $username));
  1141. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1142. if ($row) {
  1143. if (!verify_hash($row['password'], $_data["confirm_password"])) $access_denied = true;
  1144. else $access_denied = false;
  1145. }
  1146. }
  1147. // set access_denied error
  1148. if ($access_denied){
  1149. $_SESSION['return'][] = array(
  1150. 'type' => 'danger',
  1151. 'log' => array(__FUNCTION__, $_data_log),
  1152. 'msg' => 'access_denied'
  1153. );
  1154. return false;
  1155. }
  1156. switch ($_data["tfa_method"]) {
  1157. case "yubi_otp":
  1158. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  1159. $yubico_id = $_data['yubico_id'];
  1160. $yubico_key = $_data['yubico_key'];
  1161. $yubi = new Auth_Yubico($yubico_id, $yubico_key);
  1162. if (!$yubi) {
  1163. $_SESSION['return'][] = array(
  1164. 'type' => 'danger',
  1165. 'log' => array(__FUNCTION__, $_data_log),
  1166. 'msg' => 'access_denied'
  1167. );
  1168. return false;
  1169. }
  1170. if (!ctype_alnum($_data["otp_token"]) || strlen($_data["otp_token"]) != 44) {
  1171. $_SESSION['return'][] = array(
  1172. 'type' => 'danger',
  1173. 'log' => array(__FUNCTION__, $_data_log),
  1174. 'msg' => 'tfa_token_invalid'
  1175. );
  1176. return false;
  1177. }
  1178. $yauth = $yubi->verify($_data["otp_token"]);
  1179. if (PEAR::isError($yauth)) {
  1180. $_SESSION['return'][] = array(
  1181. 'type' => 'danger',
  1182. 'log' => array(__FUNCTION__, $_data_log),
  1183. 'msg' => array('yotp_verification_failed', $yauth->getMessage())
  1184. );
  1185. return false;
  1186. }
  1187. try {
  1188. // We could also do a modhex translation here
  1189. $yubico_modhex_id = substr($_data["otp_token"], 0, 12);
  1190. $stmt = $pdo->prepare("DELETE FROM `tfa`
  1191. WHERE `username` = :username
  1192. AND (`authmech` != 'yubi_otp')
  1193. OR (`authmech` = 'yubi_otp' AND `secret` LIKE :modhex)");
  1194. $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id));
  1195. $stmt = $pdo->prepare("INSERT INTO `tfa` (`key_id`, `username`, `authmech`, `active`, `secret`) VALUES
  1196. (:key_id, :username, 'yubi_otp', '1', :secret)");
  1197. $stmt->execute(array(':key_id' => $key_id, ':username' => $username, ':secret' => $yubico_id . ':' . $yubico_key . ':' . $yubico_modhex_id));
  1198. }
  1199. catch (PDOException $e) {
  1200. $_SESSION['return'][] = array(
  1201. 'type' => 'danger',
  1202. 'log' => array(__FUNCTION__, $_data_log),
  1203. 'msg' => array('mysql_error', $e)
  1204. );
  1205. return false;
  1206. }
  1207. $_SESSION['return'][] = array(
  1208. 'type' => 'success',
  1209. 'log' => array(__FUNCTION__, $_data_log),
  1210. 'msg' => array('object_modified', htmlspecialchars($username))
  1211. );
  1212. break;
  1213. case "totp":
  1214. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  1215. if ($tfa->verifyCode($_POST['totp_secret'], $_POST['totp_confirm_token']) === true) {
  1216. //$stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
  1217. //$stmt->execute(array(':username' => $username));
  1218. $stmt = $pdo->prepare("INSERT INTO `tfa` (`username`, `key_id`, `authmech`, `secret`, `active`) VALUES (?, ?, 'totp', ?, '1')");
  1219. $stmt->execute(array($username, $key_id, $_POST['totp_secret']));
  1220. $_SESSION['return'][] = array(
  1221. 'type' => 'success',
  1222. 'log' => array(__FUNCTION__, $_data_log),
  1223. 'msg' => array('object_modified', $username)
  1224. );
  1225. }
  1226. else {
  1227. $_SESSION['return'][] = array(
  1228. 'type' => 'danger',
  1229. 'log' => array(__FUNCTION__, $_data_log),
  1230. 'msg' => 'totp_verification_failed'
  1231. );
  1232. }
  1233. break;
  1234. case "webauthn":
  1235. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  1236. $stmt = $pdo->prepare("INSERT INTO `tfa` (`username`, `key_id`, `authmech`, `keyHandle`, `publicKey`, `certificate`, `counter`, `active`)
  1237. VALUES (?, ?, 'webauthn', ?, ?, ?, ?, '1')");
  1238. $stmt->execute(array(
  1239. $username,
  1240. $key_id,
  1241. base64_encode($_data['registration']->credentialId),
  1242. $_data['registration']->credentialPublicKey,
  1243. $_data['registration']->certificate,
  1244. 0
  1245. ));
  1246. $_SESSION['return'][] = array(
  1247. 'type' => 'success',
  1248. 'log' => array(__FUNCTION__, $_data_log),
  1249. 'msg' => array('object_modified', $username)
  1250. );
  1251. break;
  1252. case "none":
  1253. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
  1254. $stmt->execute(array(':username' => $username));
  1255. $_SESSION['return'][] = array(
  1256. 'type' => 'success',
  1257. 'log' => array(__FUNCTION__, $_data_log),
  1258. 'msg' => array('object_modified', htmlspecialchars($username))
  1259. );
  1260. break;
  1261. }
  1262. }
  1263. function fido2($_data) {
  1264. global $pdo;
  1265. $_data_log = $_data;
  1266. // Not logging registration data, only actions
  1267. // Silent errors for "get" requests
  1268. switch ($_data["action"]) {
  1269. case "register":
  1270. $username = $_SESSION['mailcow_cc_username'];
  1271. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1272. $_SESSION['return'][] = array(
  1273. 'type' => 'danger',
  1274. 'log' => array(__FUNCTION__, $_data["action"]),
  1275. 'msg' => 'access_denied'
  1276. );
  1277. return false;
  1278. }
  1279. $stmt = $pdo->prepare("INSERT INTO `fido2` (`username`, `rpId`, `credentialPublicKey`, `certificateChain`, `certificate`, `certificateIssuer`, `certificateSubject`, `signatureCounter`, `AAGUID`, `credentialId`)
  1280. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
  1281. $stmt->execute(array(
  1282. $username,
  1283. $_data['registration']->rpId,
  1284. $_data['registration']->credentialPublicKey,
  1285. $_data['registration']->certificateChain,
  1286. $_data['registration']->certificate,
  1287. $_data['registration']->certificateIssuer,
  1288. $_data['registration']->certificateSubject,
  1289. $_data['registration']->signatureCounter,
  1290. $_data['registration']->AAGUID,
  1291. $_data['registration']->credentialId)
  1292. );
  1293. $_SESSION['return'][] = array(
  1294. 'type' => 'success',
  1295. 'log' => array(__FUNCTION__, $_data["action"]),
  1296. 'msg' => array('object_modified', $username)
  1297. );
  1298. break;
  1299. case "get_user_cids":
  1300. // Used to exclude existing CredentialIds while registering
  1301. $username = $_SESSION['mailcow_cc_username'];
  1302. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1303. return false;
  1304. }
  1305. $stmt = $pdo->prepare("SELECT `credentialId` FROM `fido2` WHERE `username` = :username");
  1306. $stmt->execute(array(':username' => $username));
  1307. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1308. while($row = array_shift($rows)) {
  1309. $cids[] = $row['credentialId'];
  1310. }
  1311. return $cids;
  1312. break;
  1313. case "get_all_cids":
  1314. // Only needed when using fido2 with username
  1315. $stmt = $pdo->query("SELECT `credentialId` FROM `fido2`");
  1316. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1317. while($row = array_shift($rows)) {
  1318. $cids[] = $row['credentialId'];
  1319. }
  1320. return $cids;
  1321. break;
  1322. case "get_by_b64cid":
  1323. if (!isset($_data['cid']) || empty($_data['cid'])) {
  1324. return false;
  1325. }
  1326. $stmt = $pdo->prepare("SELECT `certificateSubject`, `username`, `credentialPublicKey`, SHA2(`credentialId`, 256) AS `cid` FROM `fido2` WHERE `credentialId` = :cid");
  1327. $stmt->execute(array(':cid' => base64_decode($_data['cid'])));
  1328. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1329. if (empty($row) || empty($row['credentialPublicKey']) || empty($row['username'])) {
  1330. return false;
  1331. }
  1332. $data['pub_key'] = $row['credentialPublicKey'];
  1333. $data['username'] = $row['username'];
  1334. $data['subject'] = $row['certificateSubject'];
  1335. $data['cid'] = $row['cid'];
  1336. return $data;
  1337. break;
  1338. case "get_friendly_names":
  1339. $username = $_SESSION['mailcow_cc_username'];
  1340. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1341. return false;
  1342. }
  1343. $stmt = $pdo->prepare("SELECT SHA2(`credentialId`, 256) AS `cid`, `created`, `certificateSubject`, `friendlyName` FROM `fido2` WHERE `username` = :username");
  1344. $stmt->execute(array(':username' => $username));
  1345. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1346. while($row = array_shift($rows)) {
  1347. $fns[] = array(
  1348. "subject" => (empty($row['certificateSubject']) ? 'Unknown (' . $row['created'] . ')' : $row['certificateSubject']),
  1349. "fn" => $row['friendlyName'],
  1350. "cid" => $row['cid']
  1351. );
  1352. }
  1353. return $fns;
  1354. break;
  1355. case "unset_fido2_key":
  1356. $username = $_SESSION['mailcow_cc_username'];
  1357. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1358. $_SESSION['return'][] = array(
  1359. 'type' => 'danger',
  1360. 'log' => array(__FUNCTION__, $_data["action"]),
  1361. 'msg' => 'access_denied'
  1362. );
  1363. return false;
  1364. }
  1365. $stmt = $pdo->prepare("DELETE FROM `fido2` WHERE `username` = :username AND SHA2(`credentialId`, 256) = :cid");
  1366. $stmt->execute(array(
  1367. ':username' => $username,
  1368. ':cid' => $_data['post_data']['unset_fido2_key']
  1369. ));
  1370. $_SESSION['return'][] = array(
  1371. 'type' => 'success',
  1372. 'log' => array(__FUNCTION__, $_data_log),
  1373. 'msg' => array('object_modified', htmlspecialchars($username))
  1374. );
  1375. break;
  1376. case "edit_fn":
  1377. $username = $_SESSION['mailcow_cc_username'];
  1378. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1379. $_SESSION['return'][] = array(
  1380. 'type' => 'danger',
  1381. 'log' => array(__FUNCTION__, $_data["action"]),
  1382. 'msg' => 'access_denied'
  1383. );
  1384. return false;
  1385. }
  1386. $stmt = $pdo->prepare("UPDATE `fido2` SET `friendlyName` = :friendlyName WHERE SHA2(`credentialId`, 256) = :cid AND `username` = :username");
  1387. $stmt->execute(array(
  1388. ':username' => $username,
  1389. ':friendlyName' => $_data['fido2_attrs']['fido2_fn'],
  1390. ':cid' => $_data['fido2_attrs']['fido2_cid']
  1391. ));
  1392. $_SESSION['return'][] = array(
  1393. 'type' => 'success',
  1394. 'log' => array(__FUNCTION__, $_data_log),
  1395. 'msg' => array('object_modified', htmlspecialchars($username))
  1396. );
  1397. break;
  1398. }
  1399. }
  1400. function unset_tfa_key($_data) {
  1401. // Can only unset own keys
  1402. // Needs at least one key left
  1403. global $pdo;
  1404. global $lang;
  1405. $_data_log = $_data;
  1406. $access_denied = null;
  1407. $id = intval($_data['unset_tfa_key']);
  1408. $username = $_SESSION['mailcow_cc_username'];
  1409. // check for empty user and role
  1410. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) $access_denied = true;
  1411. try {
  1412. if (!is_numeric($id)) $access_denied = true;
  1413. // set access_denied error
  1414. if ($access_denied){
  1415. $_SESSION['return'][] = array(
  1416. 'type' => 'danger',
  1417. 'log' => array(__FUNCTION__, $_data_log),
  1418. 'msg' => 'access_denied'
  1419. );
  1420. return false;
  1421. }
  1422. // check if it's last key
  1423. $stmt = $pdo->prepare("SELECT COUNT(*) AS `keys` FROM `tfa`
  1424. WHERE `username` = :username AND `active` = '1'");
  1425. $stmt->execute(array(':username' => $username));
  1426. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1427. if ($row['keys'] == "1") {
  1428. $_SESSION['return'][] = array(
  1429. 'type' => 'danger',
  1430. 'log' => array(__FUNCTION__, $_data_log),
  1431. 'msg' => 'last_key'
  1432. );
  1433. return false;
  1434. }
  1435. // delete key
  1436. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username AND `id` = :id");
  1437. $stmt->execute(array(':username' => $username, ':id' => $id));
  1438. $_SESSION['return'][] = array(
  1439. 'type' => 'success',
  1440. 'log' => array(__FUNCTION__, $_data_log),
  1441. 'msg' => array('object_modified', $username)
  1442. );
  1443. }
  1444. catch (PDOException $e) {
  1445. $_SESSION['return'][] = array(
  1446. 'type' => 'danger',
  1447. 'log' => array(__FUNCTION__, $_data_log),
  1448. 'msg' => array('mysql_error', $e)
  1449. );
  1450. return false;
  1451. }
  1452. }
  1453. function get_tfa($username = null, $id = null) {
  1454. global $pdo;
  1455. if (isset($_SESSION['mailcow_cc_username'])) {
  1456. $username = $_SESSION['mailcow_cc_username'];
  1457. }
  1458. elseif (empty($username)) {
  1459. return false;
  1460. }
  1461. if (!isset($id)){
  1462. // fetch all tfa methods - just get information about possible authenticators
  1463. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `authmech` FROM `tfa`
  1464. WHERE `username` = :username AND `active` = '1'");
  1465. $stmt->execute(array(':username' => $username));
  1466. $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1467. // no tfa methods found
  1468. if (count($results) == 0) {
  1469. $data['name'] = 'none';
  1470. $data['pretty'] = "-";
  1471. $data['additional'] = array();
  1472. return $data;
  1473. }
  1474. $data['additional'] = $results;
  1475. return $data;
  1476. } else {
  1477. // fetch specific authenticator details by id
  1478. $stmt = $pdo->prepare("SELECT * FROM `tfa`
  1479. WHERE `username` = :username AND `id` = :id AND `active` = '1'");
  1480. $stmt->execute(array(':username' => $username, ':id' => $id));
  1481. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1482. if (isset($row["authmech"])) {
  1483. switch ($row["authmech"]) {
  1484. case "yubi_otp":
  1485. $data['name'] = "yubi_otp";
  1486. $data['pretty'] = "Yubico OTP";
  1487. $stmt = $pdo->prepare("SELECT `id`, `key_id`, RIGHT(`secret`, 12) AS 'modhex' FROM `tfa` WHERE `authmech` = 'yubi_otp' AND `username` = :username AND `id` = :id");
  1488. $stmt->execute(array(
  1489. ':username' => $username,
  1490. ':id' => $id
  1491. ));
  1492. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1493. while($row = array_shift($rows)) {
  1494. $data['additional'][] = $row;
  1495. }
  1496. return $data;
  1497. break;
  1498. // u2f - deprecated, should be removed
  1499. case "u2f":
  1500. $data['name'] = "u2f";
  1501. $data['pretty'] = "Fido U2F";
  1502. $stmt = $pdo->prepare("SELECT `id`, `key_id` FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username AND `id` = :id");
  1503. $stmt->execute(array(
  1504. ':username' => $username,
  1505. ':id' => $id
  1506. ));
  1507. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1508. while($row = array_shift($rows)) {
  1509. $data['additional'][] = $row;
  1510. }
  1511. return $data;
  1512. break;
  1513. case "hotp":
  1514. $data['name'] = "hotp";
  1515. $data['pretty'] = "HMAC-based OTP";
  1516. return $data;
  1517. break;
  1518. case "totp":
  1519. $data['name'] = "totp";
  1520. $data['pretty'] = "Time-based OTP";
  1521. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `secret` FROM `tfa` WHERE `authmech` = 'totp' AND `username` = :username AND `id` = :id");
  1522. $stmt->execute(array(
  1523. ':username' => $username,
  1524. ':id' => $id
  1525. ));
  1526. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1527. while($row = array_shift($rows)) {
  1528. $data['additional'][] = $row;
  1529. }
  1530. return $data;
  1531. break;
  1532. case "webauthn":
  1533. $data['name'] = "webauthn";
  1534. $data['pretty'] = "WebAuthn";
  1535. $stmt = $pdo->prepare("SELECT `id`, `key_id` FROM `tfa` WHERE `authmech` = 'webauthn' AND `username` = :username AND `id` = :id");
  1536. $stmt->execute(array(
  1537. ':username' => $username,
  1538. ':id' => $id
  1539. ));
  1540. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1541. while($row = array_shift($rows)) {
  1542. $data['additional'][] = $row;
  1543. }
  1544. return $data;
  1545. break;
  1546. default:
  1547. $data['name'] = 'none';
  1548. $data['pretty'] = "-";
  1549. return $data;
  1550. break;
  1551. }
  1552. }
  1553. else {
  1554. $data['name'] = 'none';
  1555. $data['pretty'] = "-";
  1556. return $data;
  1557. }
  1558. }
  1559. }
  1560. function verify_tfa_login($username, $_data) {
  1561. global $pdo;
  1562. global $yubi;
  1563. global $u2f;
  1564. global $tfa;
  1565. global $WebAuthn;
  1566. if ($_data['tfa_method'] != 'u2f'){
  1567. $stmt = $pdo->prepare("SELECT `authmech` FROM `tfa`
  1568. WHERE `username` = :username AND `id` = :id AND `active` = '1'");
  1569. $stmt->execute(array(':username' => $username, ':id' => $_data['id']));
  1570. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1571. switch ($row["authmech"]) {
  1572. case "yubi_otp":
  1573. if (!ctype_alnum($_data['token']) || strlen($_data['token']) != 44) {
  1574. $_SESSION['return'][] = array(
  1575. 'type' => 'danger',
  1576. 'log' => array(__FUNCTION__, $username, '*'),
  1577. 'msg' => array('yotp_verification_failed', 'token length error')
  1578. );
  1579. return false;
  1580. }
  1581. $yubico_modhex_id = substr($_data['token'], 0, 12);
  1582. $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
  1583. WHERE `username` = :username
  1584. AND `authmech` = 'yubi_otp'
  1585. AND `id` = ':id'
  1586. AND `active`='1'
  1587. AND `secret` LIKE :modhex");
  1588. $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id, ':id' => $_data['id']));
  1589. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1590. $yubico_auth = explode(':', $row['secret']);
  1591. $yubi = new Auth_Yubico($yubico_auth[0], $yubico_auth[1]);
  1592. $yauth = $yubi->verify($_data['token']);
  1593. if (PEAR::isError($yauth)) {
  1594. $_SESSION['return'][] = array(
  1595. 'type' => 'danger',
  1596. 'log' => array(__FUNCTION__, $username, '*'),
  1597. 'msg' => array('yotp_verification_failed', $yauth->getMessage())
  1598. );
  1599. return false;
  1600. }
  1601. else {
  1602. $_SESSION['tfa_id'] = $row['id'];
  1603. $_SESSION['return'][] = array(
  1604. 'type' => 'success',
  1605. 'log' => array(__FUNCTION__, $username, '*'),
  1606. 'msg' => 'verified_yotp_login'
  1607. );
  1608. return true;
  1609. }
  1610. $_SESSION['return'][] = array(
  1611. 'type' => 'danger',
  1612. 'log' => array(__FUNCTION__, $username, '*'),
  1613. 'msg' => array('yotp_verification_failed', 'unknown')
  1614. );
  1615. return false;
  1616. break;
  1617. case "hotp":
  1618. return false;
  1619. break;
  1620. case "totp":
  1621. try {
  1622. $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
  1623. WHERE `username` = :username
  1624. AND `authmech` = 'totp'
  1625. AND `id` = :id
  1626. AND `active`='1'");
  1627. $stmt->execute(array(':username' => $username, ':id' => $_data['id']));
  1628. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1629. foreach ($rows as $row) {
  1630. if ($tfa->verifyCode($row['secret'], $_data['token']) === true) {
  1631. $_SESSION['tfa_id'] = $row['id'];
  1632. $_SESSION['return'][] = array(
  1633. 'type' => 'success',
  1634. 'log' => array(__FUNCTION__, $username, '*'),
  1635. 'msg' => 'verified_totp_login'
  1636. );
  1637. return true;
  1638. }
  1639. }
  1640. $_SESSION['return'][] = array(
  1641. 'type' => 'danger',
  1642. 'log' => array(__FUNCTION__, $username, '*'),
  1643. 'msg' => 'totp_verification_failed'
  1644. );
  1645. return false;
  1646. }
  1647. catch (PDOException $e) {
  1648. $_SESSION['return'][] = array(
  1649. 'type' => 'danger',
  1650. 'log' => array(__FUNCTION__, $username, '*'),
  1651. 'msg' => array('mysql_error', $e)
  1652. );
  1653. return false;
  1654. }
  1655. break;
  1656. case "webauthn":
  1657. $tokenData = json_decode($_data['token']);
  1658. $clientDataJSON = base64_decode($tokenData->clientDataJSON);
  1659. $authenticatorData = base64_decode($tokenData->authenticatorData);
  1660. $signature = base64_decode($tokenData->signature);
  1661. $id = base64_decode($tokenData->id);
  1662. $challenge = $_SESSION['challenge'];
  1663. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `keyHandle`, `username`, `publicKey` FROM `tfa` WHERE `id` = :id");
  1664. $stmt->execute(array(':id' => $_data['id']));
  1665. $process_webauthn = $stmt->fetch(PDO::FETCH_ASSOC);
  1666. if (empty($process_webauthn)){
  1667. $_SESSION['return'][] = array(
  1668. 'type' => 'danger',
  1669. 'log' => array(__FUNCTION__, $username, '*'),
  1670. 'msg' => array('webauthn_verification_failed', 'authenticator not found')
  1671. );
  1672. return false;
  1673. }
  1674. if (empty($process_webauthn['publicKey']) || $process_webauthn['publicKey'] === false) {
  1675. $_SESSION['return'][] = array(
  1676. 'type' => 'danger',
  1677. 'log' => array(__FUNCTION__, $username, '*'),
  1678. 'msg' => array('webauthn_verification_failed', 'publicKey not found')
  1679. );
  1680. return false;
  1681. }
  1682. try {
  1683. $WebAuthn->processGet($clientDataJSON, $authenticatorData, $signature, $process_webauthn['publicKey'], $challenge, null, $GLOBALS['WEBAUTHN_UV_FLAG_LOGIN'], $GLOBALS['WEBAUTHN_USER_PRESENT_FLAG']);
  1684. }
  1685. catch (Throwable $ex) {
  1686. $_SESSION['return'][] = array(
  1687. 'type' => 'danger',
  1688. 'log' => array(__FUNCTION__, $username, '*'),
  1689. 'msg' => array('webauthn_verification_failed', $ex->getMessage())
  1690. );
  1691. return false;
  1692. }
  1693. $stmt = $pdo->prepare("SELECT `superadmin` FROM `admin` WHERE `username` = :username");
  1694. $stmt->execute(array(':username' => $process_webauthn['username']));
  1695. $obj_props = $stmt->fetch(PDO::FETCH_ASSOC);
  1696. if ($obj_props['superadmin'] === 1) {
  1697. $_SESSION["mailcow_cc_role"] = "admin";
  1698. }
  1699. elseif ($obj_props['superadmin'] === 0) {
  1700. $_SESSION["mailcow_cc_role"] = "domainadmin";
  1701. }
  1702. else {
  1703. $stmt = $pdo->prepare("SELECT `username` FROM `mailbox` WHERE `username` = :username");
  1704. $stmt->execute(array(':username' => $process_webauthn['username']));
  1705. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1706. if ($row['username'] == $process_webauthn['username']) {
  1707. $_SESSION["mailcow_cc_role"] = "user";
  1708. }
  1709. }
  1710. if ($process_webauthn['username'] != $_SESSION['pending_mailcow_cc_username']){
  1711. $_SESSION['return'][] = array(
  1712. 'type' => 'danger',
  1713. 'log' => array(__FUNCTION__, $username, '*'),
  1714. 'msg' => array('webauthn_verification_failed', 'user who requests does not match with sql entry')
  1715. );
  1716. return false;
  1717. }
  1718. $_SESSION["mailcow_cc_username"] = $process_webauthn['username'];
  1719. $_SESSION['tfa_id'] = $process_webauthn['id'];
  1720. $_SESSION['authReq'] = null;
  1721. unset($_SESSION["challenge"]);
  1722. $_SESSION['return'][] = array(
  1723. 'type' => 'success',
  1724. 'log' => array("webauthn_login"),
  1725. 'msg' => array('logged_in_as', $process_webauthn['username'])
  1726. );
  1727. return true;
  1728. break;
  1729. default:
  1730. $_SESSION['return'][] = array(
  1731. 'type' => 'danger',
  1732. 'log' => array(__FUNCTION__, $username, '*'),
  1733. 'msg' => 'unknown_tfa_method'
  1734. );
  1735. return false;
  1736. break;
  1737. }
  1738. return false;
  1739. } else {
  1740. // delete old keys that used u2f
  1741. $stmt = $pdo->prepare("SELECT * FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username");
  1742. $stmt->execute(array(':username' => $username));
  1743. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1744. if (count($rows) == 0) return false;
  1745. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username");
  1746. $stmt->execute(array(':username' => $username));
  1747. return true;
  1748. }
  1749. }
  1750. function admin_api($access, $action, $data = null) {
  1751. global $pdo;
  1752. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1753. $_SESSION['return'][] = array(
  1754. 'type' => 'danger',
  1755. 'log' => array(__FUNCTION__),
  1756. 'msg' => 'access_denied'
  1757. );
  1758. return false;
  1759. }
  1760. if ($access !== "ro" && $access !== "rw") {
  1761. $_SESSION['return'][] = array(
  1762. 'type' => 'danger',
  1763. 'log' => array(__FUNCTION__),
  1764. 'msg' => 'invalid access type'
  1765. );
  1766. return false;
  1767. }
  1768. if ($action == "edit") {
  1769. $active = (!empty($data['active'])) ? 1 : 0;
  1770. $skip_ip_check = (isset($data['skip_ip_check'])) ? 1 : 0;
  1771. $allow_from = array();
  1772. if (isset($data['allow_from'])) {
  1773. $allow_from = array_map('trim', preg_split( "/( |,|;|\n)/", $data['allow_from']));
  1774. }
  1775. foreach ($allow_from as $key => $val) {
  1776. if (empty($val)) {
  1777. unset($allow_from[$key]);
  1778. continue;
  1779. }
  1780. if (valid_network($val) !== true) {
  1781. $_SESSION['return'][] = array(
  1782. 'type' => 'warning',
  1783. 'log' => array(__FUNCTION__, $data),
  1784. 'msg' => array('ip_invalid', htmlspecialchars($allow_from[$key]))
  1785. );
  1786. unset($allow_from[$key]);
  1787. continue;
  1788. }
  1789. }
  1790. $allow_from = implode(',', array_unique(array_filter($allow_from)));
  1791. if (empty($allow_from) && $skip_ip_check == 0) {
  1792. $_SESSION['return'][] = array(
  1793. 'type' => 'danger',
  1794. 'log' => array(__FUNCTION__, $data),
  1795. 'msg' => 'ip_list_empty'
  1796. );
  1797. return false;
  1798. }
  1799. $api_key = implode('-', array(
  1800. strtoupper(bin2hex(random_bytes(3))),
  1801. strtoupper(bin2hex(random_bytes(3))),
  1802. strtoupper(bin2hex(random_bytes(3))),
  1803. strtoupper(bin2hex(random_bytes(3))),
  1804. strtoupper(bin2hex(random_bytes(3)))
  1805. ));
  1806. $stmt = $pdo->query("SELECT `api_key` FROM `api` WHERE `access` = '" . $access . "'");
  1807. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  1808. if (empty($num_results)) {
  1809. $stmt = $pdo->prepare("INSERT INTO `api` (`api_key`, `skip_ip_check`, `active`, `allow_from`, `access`)
  1810. VALUES (:api_key, :skip_ip_check, :active, :allow_from, :access);");
  1811. $stmt->execute(array(
  1812. ':api_key' => $api_key,
  1813. ':skip_ip_check' => $skip_ip_check,
  1814. ':active' => $active,
  1815. ':allow_from' => $allow_from,
  1816. ':access' => $access
  1817. ));
  1818. }
  1819. else {
  1820. if ($skip_ip_check == 0) {
  1821. $stmt = $pdo->prepare("UPDATE `api` SET `skip_ip_check` = :skip_ip_check,
  1822. `active` = :active,
  1823. `allow_from` = :allow_from
  1824. WHERE `access` = :access;");
  1825. $stmt->execute(array(
  1826. ':active' => $active,
  1827. ':skip_ip_check' => $skip_ip_check,
  1828. ':allow_from' => $allow_from,
  1829. ':access' => $access
  1830. ));
  1831. }
  1832. else {
  1833. $stmt = $pdo->prepare("UPDATE `api` SET `skip_ip_check` = :skip_ip_check,
  1834. `active` = :active
  1835. WHERE `access` = :access;");
  1836. $stmt->execute(array(
  1837. ':active' => $active,
  1838. ':skip_ip_check' => $skip_ip_check,
  1839. ':access' => $access
  1840. ));
  1841. }
  1842. }
  1843. }
  1844. elseif ($action == "regen_key") {
  1845. $api_key = implode('-', array(
  1846. strtoupper(bin2hex(random_bytes(3))),
  1847. strtoupper(bin2hex(random_bytes(3))),
  1848. strtoupper(bin2hex(random_bytes(3))),
  1849. strtoupper(bin2hex(random_bytes(3))),
  1850. strtoupper(bin2hex(random_bytes(3)))
  1851. ));
  1852. $stmt = $pdo->prepare("UPDATE `api` SET `api_key` = :api_key WHERE `access` = :access");
  1853. $stmt->execute(array(
  1854. ':api_key' => $api_key,
  1855. ':access' => $access
  1856. ));
  1857. }
  1858. elseif ($action == "get") {
  1859. $stmt = $pdo->query("SELECT * FROM `api` WHERE `access` = '" . $access . "'");
  1860. $apidata = $stmt->fetch(PDO::FETCH_ASSOC);
  1861. if ($apidata !== false) {
  1862. $apidata['allow_from'] = str_replace(',', PHP_EOL, $apidata['allow_from']);
  1863. }
  1864. return $apidata;
  1865. }
  1866. $_SESSION['return'][] = array(
  1867. 'type' => 'success',
  1868. 'log' => array(__FUNCTION__, $data),
  1869. 'msg' => 'admin_api_modified'
  1870. );
  1871. }
  1872. function license($action, $data = null) {
  1873. global $pdo;
  1874. global $redis;
  1875. global $lang;
  1876. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1877. $_SESSION['return'][] = array(
  1878. 'type' => 'danger',
  1879. 'log' => array(__FUNCTION__),
  1880. 'msg' => 'access_denied'
  1881. );
  1882. return false;
  1883. }
  1884. switch ($action) {
  1885. case "verify":
  1886. // Keep result until revalidate button is pressed or session expired
  1887. $stmt = $pdo->query("SELECT `version` FROM `versions` WHERE `application` = 'GUID'");
  1888. $versions = $stmt->fetch(PDO::FETCH_ASSOC);
  1889. $post = array('guid' => $versions['version']);
  1890. $curl = curl_init('https://verify.mailcow.email');
  1891. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  1892. curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
  1893. curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
  1894. $response = curl_exec($curl);
  1895. curl_close($curl);
  1896. $json_return = json_decode($response, true);
  1897. if ($response && $json_return) {
  1898. if ($json_return['response'] === "ok") {
  1899. $_SESSION['gal']['valid'] = "true";
  1900. $_SESSION['gal']['c'] = $json_return['c'];
  1901. $_SESSION['gal']['s'] = $json_return['s'];
  1902. if ($json_return['m'] == 'NoMoore') {
  1903. $_SESSION['gal']['m'] = '🐄';
  1904. }
  1905. else {
  1906. $_SESSION['gal']['m'] = str_repeat('🐄', substr_count($json_return['m'], 'o'));
  1907. }
  1908. }
  1909. elseif ($json_return['response'] === "invalid") {
  1910. $_SESSION['gal']['valid'] = "false";
  1911. $_SESSION['gal']['c'] = $lang['mailbox']['no'];
  1912. $_SESSION['gal']['s'] = $lang['mailbox']['no'];
  1913. $_SESSION['gal']['m'] = $lang['mailbox']['no'];
  1914. }
  1915. }
  1916. else {
  1917. $_SESSION['gal']['valid'] = "false";
  1918. $_SESSION['gal']['c'] = $lang['danger']['temp_error'];
  1919. $_SESSION['gal']['s'] = $lang['danger']['temp_error'];
  1920. $_SESSION['gal']['m'] = $lang['danger']['temp_error'];
  1921. }
  1922. try {
  1923. // json_encode needs "true"/"false" instead of true/false, to not encode it to 0 or 1
  1924. $redis->Set('LICENSE_STATUS_CACHE', json_encode($_SESSION['gal']));
  1925. }
  1926. catch (RedisException $e) {
  1927. $_SESSION['return'][] = array(
  1928. 'type' => 'danger',
  1929. 'log' => array(__FUNCTION__, $_action, $_data_log),
  1930. 'msg' => array('redis_error', $e)
  1931. );
  1932. return false;
  1933. }
  1934. return $_SESSION['gal']['valid'];
  1935. break;
  1936. case "guid":
  1937. $stmt = $pdo->query("SELECT `version` FROM `versions` WHERE `application` = 'GUID'");
  1938. $versions = $stmt->fetch(PDO::FETCH_ASSOC);
  1939. return $versions['version'];
  1940. break;
  1941. }
  1942. }
  1943. function rspamd_ui($action, $data = null) {
  1944. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1945. $_SESSION['return'][] = array(
  1946. 'type' => 'danger',
  1947. 'log' => array(__FUNCTION__),
  1948. 'msg' => 'access_denied'
  1949. );
  1950. return false;
  1951. }
  1952. switch ($action) {
  1953. case "edit":
  1954. $rspamd_ui_pass = $data['rspamd_ui_pass'];
  1955. $rspamd_ui_pass2 = $data['rspamd_ui_pass2'];
  1956. if (empty($rspamd_ui_pass) || empty($rspamd_ui_pass2)) {
  1957. $_SESSION['return'][] = array(
  1958. 'type' => 'danger',
  1959. 'log' => array(__FUNCTION__, '*', '*'),
  1960. 'msg' => 'password_empty'
  1961. );
  1962. return false;
  1963. }
  1964. if ($rspamd_ui_pass != $rspamd_ui_pass2) {
  1965. $_SESSION['return'][] = array(
  1966. 'type' => 'danger',
  1967. 'log' => array(__FUNCTION__, '*', '*'),
  1968. 'msg' => 'password_mismatch'
  1969. );
  1970. return false;
  1971. }
  1972. if (strlen($rspamd_ui_pass) < 6) {
  1973. $_SESSION['return'][] = array(
  1974. 'type' => 'danger',
  1975. 'log' => array(__FUNCTION__, '*', '*'),
  1976. 'msg' => 'rspamd_ui_pw_length'
  1977. );
  1978. return false;
  1979. }
  1980. $docker_return = docker('post', 'rspamd-mailcow', 'exec', array('cmd' => 'rspamd', 'task' => 'worker_password', 'raw' => $rspamd_ui_pass), array('Content-Type: application/json'));
  1981. if ($docker_return_array = json_decode($docker_return, true)) {
  1982. if ($docker_return_array['type'] == 'success') {
  1983. $_SESSION['return'][] = array(
  1984. 'type' => 'success',
  1985. 'log' => array(__FUNCTION__, '*', '*'),
  1986. 'msg' => 'rspamd_ui_pw_set'
  1987. );
  1988. return true;
  1989. }
  1990. else {
  1991. $_SESSION['return'][] = array(
  1992. 'type' => $docker_return_array['type'],
  1993. 'log' => array(__FUNCTION__, '*', '*'),
  1994. 'msg' => $docker_return_array['msg']
  1995. );
  1996. return false;
  1997. }
  1998. }
  1999. else {
  2000. $_SESSION['return'][] = array(
  2001. 'type' => 'danger',
  2002. 'log' => array(__FUNCTION__, '*', '*'),
  2003. 'msg' => 'unknown'
  2004. );
  2005. return false;
  2006. }
  2007. break;
  2008. }
  2009. }
  2010. function get_logs($application, $lines = false) {
  2011. if ($lines === false) {
  2012. $lines = $GLOBALS['LOG_LINES'] - 1;
  2013. }
  2014. elseif(is_numeric($lines) && $lines >= 1) {
  2015. $lines = abs(intval($lines) - 1);
  2016. }
  2017. else {
  2018. list ($from, $to) = explode('-', $lines);
  2019. $from = intval($from);
  2020. $to = intval($to);
  2021. if ($from < 1 || $to < $from) { return false; }
  2022. }
  2023. global $redis;
  2024. global $pdo;
  2025. if ($_SESSION['mailcow_cc_role'] != "admin") {
  2026. return false;
  2027. }
  2028. // SQL
  2029. if ($application == "mailcow-ui") {
  2030. if (isset($from) && isset($to)) {
  2031. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :from, :to");
  2032. $stmt->execute(array(
  2033. ':from' => $from - 1,
  2034. ':to' => $to
  2035. ));
  2036. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2037. }
  2038. else {
  2039. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :lines");
  2040. $stmt->execute(array(
  2041. ':lines' => $lines + 1,
  2042. ));
  2043. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2044. }
  2045. if (is_array($data)) {
  2046. return $data;
  2047. }
  2048. }
  2049. if ($application == "sasl") {
  2050. if (isset($from) && isset($to)) {
  2051. $stmt = $pdo->prepare("SELECT * FROM `sasl_log` ORDER BY `datetime` DESC LIMIT :from, :to");
  2052. $stmt->execute(array(
  2053. ':from' => $from - 1,
  2054. ':to' => $to
  2055. ));
  2056. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2057. }
  2058. else {
  2059. $stmt = $pdo->prepare("SELECT * FROM `sasl_log` ORDER BY `datetime` DESC LIMIT :lines");
  2060. $stmt->execute(array(
  2061. ':lines' => $lines + 1,
  2062. ));
  2063. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2064. }
  2065. if (is_array($data)) {
  2066. return $data;
  2067. }
  2068. }
  2069. // Redis
  2070. if ($application == "dovecot-mailcow") {
  2071. if (isset($from) && isset($to)) {
  2072. $data = $redis->lRange('DOVECOT_MAILLOG', $from - 1, $to - 1);
  2073. }
  2074. else {
  2075. $data = $redis->lRange('DOVECOT_MAILLOG', 0, $lines);
  2076. }
  2077. if ($data) {
  2078. foreach ($data as $json_line) {
  2079. $data_array[] = json_decode($json_line, true);
  2080. }
  2081. return $data_array;
  2082. }
  2083. }
  2084. if ($application == "postfix-mailcow") {
  2085. if (isset($from) && isset($to)) {
  2086. $data = $redis->lRange('POSTFIX_MAILLOG', $from - 1, $to - 1);
  2087. }
  2088. else {
  2089. $data = $redis->lRange('POSTFIX_MAILLOG', 0, $lines);
  2090. }
  2091. if ($data) {
  2092. foreach ($data as $json_line) {
  2093. $data_array[] = json_decode($json_line, true);
  2094. }
  2095. return $data_array;
  2096. }
  2097. }
  2098. if ($application == "sogo-mailcow") {
  2099. if (isset($from) && isset($to)) {
  2100. $data = $redis->lRange('SOGO_LOG', $from - 1, $to - 1);
  2101. }
  2102. else {
  2103. $data = $redis->lRange('SOGO_LOG', 0, $lines);
  2104. }
  2105. if ($data) {
  2106. foreach ($data as $json_line) {
  2107. $data_array[] = json_decode($json_line, true);
  2108. }
  2109. return $data_array;
  2110. }
  2111. }
  2112. if ($application == "watchdog-mailcow") {
  2113. if (isset($from) && isset($to)) {
  2114. $data = $redis->lRange('WATCHDOG_LOG', $from - 1, $to - 1);
  2115. }
  2116. else {
  2117. $data = $redis->lRange('WATCHDOG_LOG', 0, $lines);
  2118. }
  2119. if ($data) {
  2120. foreach ($data as $json_line) {
  2121. $data_array[] = json_decode($json_line, true);
  2122. }
  2123. return $data_array;
  2124. }
  2125. }
  2126. if ($application == "acme-mailcow") {
  2127. if (isset($from) && isset($to)) {
  2128. $data = $redis->lRange('ACME_LOG', $from - 1, $to - 1);
  2129. }
  2130. else {
  2131. $data = $redis->lRange('ACME_LOG', 0, $lines);
  2132. }
  2133. if ($data) {
  2134. foreach ($data as $json_line) {
  2135. $data_array[] = json_decode($json_line, true);
  2136. }
  2137. return $data_array;
  2138. }
  2139. }
  2140. if ($application == "ratelimited") {
  2141. if (isset($from) && isset($to)) {
  2142. $data = $redis->lRange('RL_LOG', $from - 1, $to - 1);
  2143. }
  2144. else {
  2145. $data = $redis->lRange('RL_LOG', 0, $lines);
  2146. }
  2147. if ($data) {
  2148. foreach ($data as $json_line) {
  2149. $data_array[] = json_decode($json_line, true);
  2150. }
  2151. return $data_array;
  2152. }
  2153. }
  2154. if ($application == "api-mailcow") {
  2155. if (isset($from) && isset($to)) {
  2156. $data = $redis->lRange('API_LOG', $from - 1, $to - 1);
  2157. }
  2158. else {
  2159. $data = $redis->lRange('API_LOG', 0, $lines);
  2160. }
  2161. if ($data) {
  2162. foreach ($data as $json_line) {
  2163. $data_array[] = json_decode($json_line, true);
  2164. }
  2165. return $data_array;
  2166. }
  2167. }
  2168. if ($application == "netfilter-mailcow") {
  2169. if (isset($from) && isset($to)) {
  2170. $data = $redis->lRange('NETFILTER_LOG', $from - 1, $to - 1);
  2171. }
  2172. else {
  2173. $data = $redis->lRange('NETFILTER_LOG', 0, $lines);
  2174. }
  2175. if ($data) {
  2176. foreach ($data as $json_line) {
  2177. $data_array[] = json_decode($json_line, true);
  2178. }
  2179. return $data_array;
  2180. }
  2181. }
  2182. if ($application == "autodiscover-mailcow") {
  2183. if (isset($from) && isset($to)) {
  2184. $data = $redis->lRange('AUTODISCOVER_LOG', $from - 1, $to - 1);
  2185. }
  2186. else {
  2187. $data = $redis->lRange('AUTODISCOVER_LOG', 0, $lines);
  2188. }
  2189. if ($data) {
  2190. foreach ($data as $json_line) {
  2191. $data_array[] = json_decode($json_line, true);
  2192. }
  2193. return $data_array;
  2194. }
  2195. }
  2196. if ($application == "rspamd-history") {
  2197. $curl = curl_init();
  2198. curl_setopt($curl, CURLOPT_UNIX_SOCKET_PATH, '/var/lib/rspamd/rspamd.sock');
  2199. if (!is_numeric($lines)) {
  2200. list ($from, $to) = explode('-', $lines);
  2201. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?from=" . intval($from) . "&to=" . intval($to));
  2202. }
  2203. else {
  2204. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?to=" . intval($lines));
  2205. }
  2206. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2207. $history = curl_exec($curl);
  2208. if (!curl_errno($curl)) {
  2209. $data_array = json_decode($history, true);
  2210. curl_close($curl);
  2211. return $data_array['rows'];
  2212. }
  2213. curl_close($curl);
  2214. return false;
  2215. }
  2216. if ($application == "rspamd-stats") {
  2217. $curl = curl_init();
  2218. curl_setopt($curl, CURLOPT_UNIX_SOCKET_PATH, '/var/lib/rspamd/rspamd.sock');
  2219. curl_setopt($curl, CURLOPT_URL,"http://rspamd/stat");
  2220. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2221. $stats = curl_exec($curl);
  2222. if (!curl_errno($curl)) {
  2223. $data_array = json_decode($stats, true);
  2224. curl_close($curl);
  2225. return $data_array;
  2226. }
  2227. curl_close($curl);
  2228. return false;
  2229. }
  2230. return false;
  2231. }
  2232. function getGUID() {
  2233. if (function_exists('com_create_guid')) {
  2234. return com_create_guid();
  2235. }
  2236. mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
  2237. $charid = strtoupper(md5(uniqid(rand(), true)));
  2238. $hyphen = chr(45);// "-"
  2239. return substr($charid, 0, 8).$hyphen
  2240. .substr($charid, 8, 4).$hyphen
  2241. .substr($charid,12, 4).$hyphen
  2242. .substr($charid,16, 4).$hyphen
  2243. .substr($charid,20,12);
  2244. }
  2245. function solr_status() {
  2246. $curl = curl_init();
  2247. $endpoint = 'http://solr:8983/solr/admin/cores';
  2248. $params = array(
  2249. 'action' => 'STATUS',
  2250. 'core' => 'dovecot-fts',
  2251. 'indexInfo' => 'true'
  2252. );
  2253. $url = $endpoint . '?' . http_build_query($params);
  2254. curl_setopt($curl, CURLOPT_URL, $url);
  2255. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  2256. curl_setopt($curl, CURLOPT_POST, 0);
  2257. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  2258. $response_core = curl_exec($curl);
  2259. if ($response_core === false) {
  2260. $err = curl_error($curl);
  2261. curl_close($curl);
  2262. return false;
  2263. }
  2264. else {
  2265. curl_close($curl);
  2266. $curl = curl_init();
  2267. $status_core = json_decode($response_core, true);
  2268. $url = 'http://solr:8983/solr/admin/info/system';
  2269. curl_setopt($curl, CURLOPT_URL, $url);
  2270. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  2271. curl_setopt($curl, CURLOPT_POST, 0);
  2272. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  2273. $response_sysinfo = curl_exec($curl);
  2274. if ($response_sysinfo === false) {
  2275. $err = curl_error($curl);
  2276. curl_close($curl);
  2277. return false;
  2278. }
  2279. else {
  2280. curl_close($curl);
  2281. $status_sysinfo = json_decode($response_sysinfo, true);
  2282. $status = array_merge($status_core, $status_sysinfo);
  2283. return (!empty($status['status']['dovecot-fts']) && !empty($status['jvm']['memory'])) ? $status : false;
  2284. }
  2285. return (!empty($status['status']['dovecot-fts'])) ? $status['status']['dovecot-fts'] : false;
  2286. }
  2287. return false;
  2288. }
  2289. function cleanupJS($ignore = '', $folder = '/tmp/*.js') {
  2290. $now = time();
  2291. foreach (glob($folder) as $filename) {
  2292. if(strpos($filename, $ignore) !== false) {
  2293. continue;
  2294. }
  2295. if (is_file($filename)) {
  2296. if ($now - filemtime($filename) >= 60 * 60) {
  2297. unlink($filename);
  2298. }
  2299. }
  2300. }
  2301. }
  2302. function cleanupCSS($ignore = '', $folder = '/tmp/*.css') {
  2303. $now = time();
  2304. foreach (glob($folder) as $filename) {
  2305. if(strpos($filename, $ignore) !== false) {
  2306. continue;
  2307. }
  2308. if (is_file($filename)) {
  2309. if ($now - filemtime($filename) >= 60 * 60) {
  2310. unlink($filename);
  2311. }
  2312. }
  2313. }
  2314. }
  2315. ?>