functions.inc.php 86 KB

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