functions.inc.php 77 KB

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