functions.inc.php 86 KB

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