functions.inc.php 87 KB

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