functions.inc.php 105 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874
  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, $ui_offset = 1) {
  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 :offset');
  318. $stmt->execute(array(
  319. ':username' => $username,
  320. ':offset' => $ui_offset
  321. ));
  322. $ui = $stmt->fetch(PDO::FETCH_ASSOC);
  323. }
  324. else {
  325. $ui = array();
  326. }
  327. return array('ui' => $ui, 'sasl' => $sasl);
  328. break;
  329. case 'reset':
  330. if (filter_var($username, FILTER_VALIDATE_EMAIL) && hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $username)) {
  331. $stmt = $pdo->prepare('DELETE FROM `sasl_log`
  332. WHERE `username` = :username');
  333. $stmt->execute(array(':username' => $username));
  334. }
  335. if ($_SESSION['mailcow_cc_role'] == "admin" || $username == $_SESSION['mailcow_cc_username']) {
  336. $stmt = $pdo->prepare('DELETE FROM `logs`
  337. WHERE JSON_EXTRACT(`call`, "$[0]") = "check_login"
  338. AND JSON_EXTRACT(`call`, "$[1]") = :username
  339. AND `type` = "success"');
  340. $stmt->execute(array(':username' => $username));
  341. }
  342. return true;
  343. break;
  344. }
  345. }
  346. function flush_memcached() {
  347. try {
  348. $m = new Memcached();
  349. $m->addServer('memcached', 11211);
  350. $m->flush();
  351. }
  352. catch ( Exception $e ) {
  353. // Dunno
  354. }
  355. }
  356. function sys_mail($_data) {
  357. if ($_SESSION['mailcow_cc_role'] != "admin") {
  358. $_SESSION['return'][] = array(
  359. 'type' => 'danger',
  360. 'log' => array(__FUNCTION__),
  361. 'msg' => 'access_denied'
  362. );
  363. return false;
  364. }
  365. $excludes = $_data['mass_exclude'];
  366. $includes = $_data['mass_include'];
  367. $mailboxes = array();
  368. $mass_from = $_data['mass_from'];
  369. $mass_text = $_data['mass_text'];
  370. $mass_html = $_data['mass_html'];
  371. $mass_subject = $_data['mass_subject'];
  372. if (!filter_var($mass_from, FILTER_VALIDATE_EMAIL)) {
  373. $_SESSION['return'][] = array(
  374. 'type' => 'danger',
  375. 'log' => array(__FUNCTION__),
  376. 'msg' => 'from_invalid'
  377. );
  378. return false;
  379. }
  380. if (empty($mass_subject)) {
  381. $_SESSION['return'][] = array(
  382. 'type' => 'danger',
  383. 'log' => array(__FUNCTION__),
  384. 'msg' => 'subject_empty'
  385. );
  386. return false;
  387. }
  388. if (empty($mass_text)) {
  389. $_SESSION['return'][] = array(
  390. 'type' => 'danger',
  391. 'log' => array(__FUNCTION__),
  392. 'msg' => 'text_empty'
  393. );
  394. return false;
  395. }
  396. $domains = array_merge(mailbox('get', 'domains'), mailbox('get', 'alias_domains'));
  397. foreach ($domains as $domain) {
  398. foreach (mailbox('get', 'mailboxes', $domain) as $mailbox) {
  399. $mailboxes[] = $mailbox;
  400. }
  401. }
  402. if (!empty($includes)) {
  403. $rcpts = array_intersect($mailboxes, $includes);
  404. }
  405. elseif (!empty($excludes)) {
  406. $rcpts = array_diff($mailboxes, $excludes);
  407. }
  408. else {
  409. $rcpts = $mailboxes;
  410. }
  411. if (!empty($rcpts)) {
  412. ini_set('max_execution_time', 0);
  413. ini_set('max_input_time', 0);
  414. $mail = new PHPMailer;
  415. $mail->Timeout = 10;
  416. $mail->SMTPOptions = array(
  417. 'ssl' => array(
  418. 'verify_peer' => false,
  419. 'verify_peer_name' => false,
  420. 'allow_self_signed' => true
  421. )
  422. );
  423. $mail->isSMTP();
  424. $mail->Host = 'dovecot-mailcow';
  425. $mail->SMTPAuth = false;
  426. $mail->Port = 24;
  427. $mail->setFrom($mass_from);
  428. $mail->Subject = $mass_subject;
  429. $mail->CharSet ="UTF-8";
  430. if (!empty($mass_html)) {
  431. $mail->Body = $mass_html;
  432. $mail->AltBody = $mass_text;
  433. }
  434. else {
  435. $mail->Body = $mass_text;
  436. }
  437. $mail->XMailer = 'MooMassMail';
  438. foreach ($rcpts as $rcpt) {
  439. $mail->AddAddress($rcpt);
  440. if (!$mail->send()) {
  441. $_SESSION['return'][] = array(
  442. 'type' => 'warning',
  443. 'log' => array(__FUNCTION__),
  444. 'msg' => 'Mailer error (RCPT "' . htmlspecialchars($rcpt) . '"): ' . str_replace('https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting', '', $mail->ErrorInfo)
  445. );
  446. }
  447. $mail->ClearAllRecipients();
  448. }
  449. }
  450. $_SESSION['return'][] = array(
  451. 'type' => 'success',
  452. 'log' => array(__FUNCTION__),
  453. 'msg' => 'Mass mail job completed, sent ' . count($rcpts) . ' mails'
  454. );
  455. }
  456. function logger($_data = false) {
  457. /*
  458. logger() will be called as last function
  459. To manually log a message, logger needs to be called like below.
  460. logger(array(
  461. 'return' => array(
  462. array(
  463. 'type' => 'danger',
  464. 'log' => array(__FUNCTION__),
  465. 'msg' => $err
  466. )
  467. )
  468. ));
  469. These messages will not be printed as alert box.
  470. To do so, push them to $_SESSION['return'] and do not call logger as they will be included automatically:
  471. $_SESSION['return'][] = array(
  472. 'type' => 'danger',
  473. 'log' => array(__FUNCTION__, $user, '*'),
  474. 'msg' => $err
  475. );
  476. */
  477. global $pdo;
  478. if (!$_data) {
  479. $_data = $_SESSION;
  480. }
  481. if (!empty($_data['return'])) {
  482. $task = substr(strtoupper(md5(uniqid(rand(), true))), 0, 6);
  483. foreach ($_data['return'] as $return) {
  484. $type = $return['type'];
  485. $msg = null;
  486. if (isset($return['msg'])) {
  487. $msg = json_encode($return['msg'], JSON_UNESCAPED_UNICODE);
  488. }
  489. $call = null;
  490. if (isset($return['log'])) {
  491. $call = json_encode($return['log'], JSON_UNESCAPED_UNICODE);
  492. }
  493. if (!empty($_SESSION["dual-login"]["username"])) {
  494. $user = $_SESSION["dual-login"]["username"] . ' => ' . $_SESSION['mailcow_cc_username'];
  495. $role = $_SESSION["dual-login"]["role"] . ' => ' . $_SESSION['mailcow_cc_role'];
  496. }
  497. elseif (!empty($_SESSION['mailcow_cc_username'])) {
  498. $user = $_SESSION['mailcow_cc_username'];
  499. $role = $_SESSION['mailcow_cc_role'];
  500. }
  501. else {
  502. $user = 'unauthenticated';
  503. $role = 'unauthenticated';
  504. }
  505. // We cannot log when logs is missing...
  506. try {
  507. $stmt = $pdo->prepare("INSERT INTO `logs` (`type`, `task`, `msg`, `call`, `user`, `role`, `remote`, `time`) VALUES
  508. (:type, :task, :msg, :call, :user, :role, :remote, UNIX_TIMESTAMP())");
  509. $stmt->execute(array(
  510. ':type' => $type,
  511. ':task' => $task,
  512. ':call' => $call,
  513. ':msg' => $msg,
  514. ':user' => $user,
  515. ':role' => $role,
  516. ':remote' => get_remote_ip()
  517. ));
  518. }
  519. catch (PDOException $e) {
  520. # handle the exception here, as the exception handler function results in a white page
  521. error_log($e->getMessage(), 0);
  522. }
  523. }
  524. }
  525. else {
  526. return true;
  527. }
  528. }
  529. function hasDomainAccess($username, $role, $domain) {
  530. global $pdo;
  531. if (!filter_var($username, FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $username))) {
  532. return false;
  533. }
  534. if (empty($domain) || !is_valid_domain_name($domain)) {
  535. return false;
  536. }
  537. if ($role != 'admin' && $role != 'domainadmin') {
  538. return false;
  539. }
  540. if ($role == 'admin') {
  541. $stmt = $pdo->prepare("SELECT `domain` FROM `domain`
  542. WHERE `domain` = :domain");
  543. $stmt->execute(array(':domain' => $domain));
  544. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  545. $stmt = $pdo->prepare("SELECT `alias_domain` FROM `alias_domain`
  546. WHERE `alias_domain` = :domain");
  547. $stmt->execute(array(':domain' => $domain));
  548. $num_results = $num_results + count($stmt->fetchAll(PDO::FETCH_ASSOC));
  549. if ($num_results != 0) {
  550. return true;
  551. }
  552. }
  553. elseif ($role == 'domainadmin') {
  554. $stmt = $pdo->prepare("SELECT `domain` FROM `domain_admins`
  555. WHERE (
  556. `active`='1'
  557. AND `username` = :username
  558. AND (`domain` = :domain1 OR `domain` = (SELECT `target_domain` FROM `alias_domain` WHERE `alias_domain` = :domain2))
  559. )");
  560. $stmt->execute(array(':username' => $username, ':domain1' => $domain, ':domain2' => $domain));
  561. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  562. if (!empty($num_results)) {
  563. return true;
  564. }
  565. }
  566. return false;
  567. }
  568. function hasMailboxObjectAccess($username, $role, $object) {
  569. global $pdo;
  570. if (empty($username) || empty($role) || empty($object)) {
  571. return false;
  572. }
  573. if (!filter_var(html_entity_decode(rawurldecode($username)), FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $username))) {
  574. return false;
  575. }
  576. if ($role != 'admin' && $role != 'domainadmin' && $role != 'user') {
  577. return false;
  578. }
  579. if ($username == $object) {
  580. return true;
  581. }
  582. $stmt = $pdo->prepare("SELECT `domain` FROM `mailbox` WHERE `username` = :object");
  583. $stmt->execute(array(':object' => $object));
  584. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  585. if (isset($row['domain']) && hasDomainAccess($username, $role, $row['domain'])) {
  586. return true;
  587. }
  588. return false;
  589. }
  590. // does also verify mailboxes as a mailbox is a alias == goto
  591. function hasAliasObjectAccess($username, $role, $object) {
  592. global $pdo;
  593. if (empty($username) || empty($role) || empty($object)) {
  594. return false;
  595. }
  596. if (!filter_var(html_entity_decode(rawurldecode($username)), FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $username))) {
  597. return false;
  598. }
  599. if ($role != 'admin' && $role != 'domainadmin' && $role != 'user') {
  600. return false;
  601. }
  602. $stmt = $pdo->prepare("SELECT `domain` FROM `alias` WHERE `address` = :object");
  603. $stmt->execute(array(':object' => $object));
  604. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  605. if (isset($row['domain']) && hasDomainAccess($username, $role, $row['domain'])) {
  606. return true;
  607. }
  608. return false;
  609. }
  610. function pem_to_der($pem_key) {
  611. // Need to remove BEGIN/END PUBLIC KEY
  612. $lines = explode("\n", trim($pem_key));
  613. unset($lines[count($lines)-1]);
  614. unset($lines[0]);
  615. return base64_decode(implode('', $lines));
  616. }
  617. function expand_ipv6($ip) {
  618. $hex = unpack("H*hex", inet_pton($ip));
  619. $ip = substr(preg_replace("/([A-f0-9]{4})/", "$1:", $hex['hex']), 0, -1);
  620. return $ip;
  621. }
  622. function generate_tlsa_digest($hostname, $port, $starttls = null) {
  623. if (!is_valid_domain_name($hostname)) {
  624. return "Not a valid hostname";
  625. }
  626. if (empty($starttls)) {
  627. $context = stream_context_create(array("ssl" => array("capture_peer_cert" => true, 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true)));
  628. $stream = stream_socket_client('ssl://' . $hostname . ':' . $port, $error_nr, $error_msg, 5, STREAM_CLIENT_CONNECT, $context);
  629. if (!$stream) {
  630. $error_msg = isset($error_msg) ? $error_msg : '-';
  631. return $error_nr . ': ' . $error_msg;
  632. }
  633. }
  634. else {
  635. $stream = stream_socket_client('tcp://' . $hostname . ':' . $port, $error_nr, $error_msg, 5);
  636. if (!$stream) {
  637. return $error_nr . ': ' . $error_msg;
  638. }
  639. $banner = fread($stream, 512 );
  640. if (preg_match("/^220/i", $banner)) { // SMTP
  641. fwrite($stream,"HELO tlsa.generator.local\r\n");
  642. fread($stream, 512);
  643. fwrite($stream,"STARTTLS\r\n");
  644. fread($stream, 512);
  645. }
  646. elseif (preg_match("/imap.+starttls/i", $banner)) { // IMAP
  647. fwrite($stream,"A1 STARTTLS\r\n");
  648. fread($stream, 512);
  649. }
  650. elseif (preg_match("/^\+OK/", $banner)) { // POP3
  651. fwrite($stream,"STLS\r\n");
  652. fread($stream, 512);
  653. }
  654. elseif (preg_match("/^OK/m", $banner)) { // Sieve
  655. fwrite($stream,"STARTTLS\r\n");
  656. fread($stream, 512);
  657. }
  658. else {
  659. return 'Unknown banner: "' . htmlspecialchars(trim($banner)) . '"';
  660. }
  661. // Upgrade connection
  662. stream_set_blocking($stream, true);
  663. stream_context_set_option($stream, 'ssl', 'capture_peer_cert', true);
  664. stream_context_set_option($stream, 'ssl', 'verify_peer', false);
  665. stream_context_set_option($stream, 'ssl', 'verify_peer_name', false);
  666. stream_context_set_option($stream, 'ssl', 'allow_self_signed', true);
  667. stream_socket_enable_crypto($stream, true, STREAM_CRYPTO_METHOD_ANY_CLIENT);
  668. stream_set_blocking($stream, false);
  669. }
  670. $params = stream_context_get_params($stream);
  671. if (!empty($params['options']['ssl']['peer_certificate'])) {
  672. $key_resource = openssl_pkey_get_public($params['options']['ssl']['peer_certificate']);
  673. // We cannot get ['rsa']['n'], the binary data would contain BEGIN/END PUBLIC KEY
  674. $key_data = openssl_pkey_get_details($key_resource)['key'];
  675. return '3 1 1 ' . openssl_digest(pem_to_der($key_data), 'sha256');
  676. }
  677. else {
  678. return 'Error: Cannot read peer certificate';
  679. }
  680. }
  681. function alertbox_log_parser($_data) {
  682. global $lang;
  683. if (isset($_data['return'])) {
  684. foreach ($_data['return'] as $return) {
  685. // Get type
  686. $type = $return['type'];
  687. // If a lang[type][msg] string exists, use it as message
  688. if (isset($return['type']) && isset($return['msg']) && !is_array($return['msg'])) {
  689. if (isset($lang[$return['type']][$return['msg']])) {
  690. $msg = $lang[$return['type']][$return['msg']];
  691. }
  692. else {
  693. $msg = $return['msg'];
  694. }
  695. }
  696. // If msg is an array, use first element as language string and run printf on it with remaining array elements
  697. elseif (is_array($return['msg'])) {
  698. $msg = array_shift($return['msg']);
  699. $msg = vsprintf(
  700. $lang[$return['type']][$msg],
  701. $return['msg']
  702. );
  703. }
  704. else {
  705. $msg = '-';
  706. }
  707. $log_array[] = array('msg' => $msg, 'type' => json_encode($type));
  708. }
  709. if (!empty($log_array)) {
  710. return $log_array;
  711. }
  712. }
  713. return false;
  714. }
  715. function verify_salted_hash($hash, $password, $algo, $salt_length) {
  716. // Decode hash
  717. $dhash = base64_decode($hash);
  718. // Get first n bytes of binary which equals a SSHA hash
  719. $ohash = substr($dhash, 0, $salt_length);
  720. // Remove SSHA hash from decoded hash to get original salt string
  721. $osalt = str_replace($ohash, '', $dhash);
  722. // Check single salted SSHA hash against extracted hash
  723. if (hash_equals(hash($algo, $password . $osalt, true), $ohash)) {
  724. return true;
  725. }
  726. return false;
  727. }
  728. function verify_hash($hash, $password) {
  729. if (preg_match('/^{(.+)}(.+)/i', $hash, $hash_array)) {
  730. $scheme = strtoupper($hash_array[1]);
  731. $hash = $hash_array[2];
  732. switch ($scheme) {
  733. case "ARGON2I":
  734. case "ARGON2ID":
  735. case "BLF-CRYPT":
  736. case "CRYPT":
  737. case "DES-CRYPT":
  738. case "MD5-CRYPT":
  739. case "MD5":
  740. case "SHA256-CRYPT":
  741. case "SHA512-CRYPT":
  742. return password_verify($password, $hash);
  743. case "CLEAR":
  744. case "CLEARTEXT":
  745. case "PLAIN":
  746. return $password == $hash;
  747. case "LDAP-MD5":
  748. $hash = base64_decode($hash);
  749. return hash_equals(hash('md5', $password, true), $hash);
  750. case "PBKDF2":
  751. $components = explode('$', $hash);
  752. $salt = $components[2];
  753. $rounds = $components[3];
  754. $hash = $components[4];
  755. return hash_equals(hash_pbkdf2('sha1', $password, $salt, $rounds), $hash);
  756. case "PLAIN-MD4":
  757. return hash_equals(hash('md4', $password), $hash);
  758. case "PLAIN-MD5":
  759. return md5($password) == $hash;
  760. case "PLAIN-TRUNC":
  761. $components = explode('-', $hash);
  762. if (count($components) > 1) {
  763. $trunc_len = $components[0];
  764. $trunc_password = $components[1];
  765. return substr($password, 0, $trunc_len) == $trunc_password;
  766. } else {
  767. return $password == $hash;
  768. }
  769. case "SHA":
  770. case "SHA1":
  771. case "SHA256":
  772. case "SHA512":
  773. // SHA is an alias for SHA1
  774. $scheme = $scheme == "SHA" ? "sha1" : strtolower($scheme);
  775. $hash = base64_decode($hash);
  776. return hash_equals(hash($scheme, $password, true), $hash);
  777. case "SMD5":
  778. return verify_salted_hash($hash, $password, 'md5', 16);
  779. case "SSHA":
  780. return verify_salted_hash($hash, $password, 'sha1', 20);
  781. case "SSHA256":
  782. return verify_salted_hash($hash, $password, 'sha256', 32);
  783. case "SSHA512":
  784. return verify_salted_hash($hash, $password, 'sha512', 64);
  785. default:
  786. return false;
  787. }
  788. }
  789. return false;
  790. }
  791. function formatBytes($size, $precision = 2) {
  792. if(!is_numeric($size)) {
  793. return "0";
  794. }
  795. $base = log($size, 1024);
  796. $suffixes = array(' Byte', ' KiB', ' MiB', ' GiB', ' TiB');
  797. if ($size == "0") {
  798. return "0";
  799. }
  800. return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
  801. }
  802. function update_sogo_static_view($mailbox = null) {
  803. if (getenv('SKIP_SOGO') == "y") {
  804. return true;
  805. }
  806. global $pdo;
  807. global $lang;
  808. $mailbox_exists = false;
  809. if ($mailbox !== null) {
  810. // Check if the mailbox exists
  811. $stmt = $pdo->prepare("SELECT username FROM mailbox WHERE username = :mailbox AND active = '1'");
  812. $stmt->execute(array(':mailbox' => $mailbox));
  813. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  814. if ($row){
  815. $mailbox_exists = true;
  816. }
  817. }
  818. $subquery = "GROUP BY mailbox.username";
  819. if ($mailbox_exists) {
  820. $subquery = "AND mailbox.username = :mailbox";
  821. }
  822. $query = "INSERT INTO _sogo_static_view (`c_uid`, `domain`, `c_name`, `c_password`, `c_cn`, `mail`, `aliases`, `ad_aliases`, `ext_acl`, `kind`, `multiple_bookings`)
  823. SELECT
  824. mailbox.username,
  825. mailbox.domain,
  826. mailbox.username,
  827. CASE
  828. WHEN mailbox.authsource IS NOT NULL AND mailbox.authsource <> 'mailcow' THEN '{SSHA256}A123A123A321A321A321B321B321B123B123B321B432F123E321123123321321'
  829. ELSE
  830. IF(JSON_UNQUOTE(JSON_VALUE(attributes, '$.force_pw_update')) = '0',
  831. IF(JSON_UNQUOTE(JSON_VALUE(attributes, '$.sogo_access')) = 1, password, '{SSHA256}A123A123A321A321A321B321B321B123B123B321B432F123E321123123321321'),
  832. '{SSHA256}A123A123A321A321A321B321B321B123B123B321B432F123E321123123321321')
  833. END AS c_password,
  834. mailbox.name,
  835. mailbox.username,
  836. IFNULL(GROUP_CONCAT(ga.aliases ORDER BY ga.aliases SEPARATOR ' '), ''),
  837. IFNULL(gda.ad_alias, ''),
  838. IFNULL(external_acl.send_as_acl, ''),
  839. mailbox.kind,
  840. mailbox.multiple_bookings
  841. FROM
  842. mailbox
  843. LEFT OUTER JOIN grouped_mail_aliases ga ON ga.username REGEXP CONCAT('(^|,)', mailbox.username, '($|,)')
  844. LEFT OUTER JOIN grouped_domain_alias_address gda ON gda.username = mailbox.username
  845. LEFT OUTER JOIN grouped_sender_acl_external external_acl ON external_acl.username = mailbox.username
  846. WHERE
  847. mailbox.active = '1'
  848. $subquery
  849. ON DUPLICATE KEY UPDATE
  850. `domain` = VALUES(`domain`),
  851. `c_name` = VALUES(`c_name`),
  852. `c_password` = VALUES(`c_password`),
  853. `c_cn` = VALUES(`c_cn`),
  854. `mail` = VALUES(`mail`),
  855. `aliases` = VALUES(`aliases`),
  856. `ad_aliases` = VALUES(`ad_aliases`),
  857. `ext_acl` = VALUES(`ext_acl`),
  858. `kind` = VALUES(`kind`),
  859. `multiple_bookings` = VALUES(`multiple_bookings`)";
  860. if ($mailbox_exists) {
  861. $stmt = $pdo->prepare($query);
  862. $stmt->execute(array(':mailbox' => $mailbox));
  863. } else {
  864. $stmt = $pdo->query($query);
  865. }
  866. $stmt = $pdo->query("DELETE FROM _sogo_static_view WHERE `c_uid` NOT IN (SELECT `username` FROM `mailbox` WHERE `active` = '1');");
  867. flush_memcached();
  868. }
  869. function edit_user_account($_data) {
  870. global $lang;
  871. global $pdo;
  872. $_data_log = $_data;
  873. !isset($_data_log['user_new_pass']) ?: $_data_log['user_new_pass'] = '*';
  874. !isset($_data_log['user_new_pass2']) ?: $_data_log['user_new_pass2'] = '*';
  875. !isset($_data_log['user_old_pass']) ?: $_data_log['user_old_pass'] = '*';
  876. $username = $_SESSION['mailcow_cc_username'];
  877. $role = $_SESSION['mailcow_cc_role'];
  878. $password_old = $_data['user_old_pass'];
  879. if (filter_var($username, FILTER_VALIDATE_EMAIL === false) || $role != 'user') {
  880. $_SESSION['return'][] = array(
  881. 'type' => 'danger',
  882. 'log' => array(__FUNCTION__, $_data_log),
  883. 'msg' => 'access_denied'
  884. );
  885. return false;
  886. }
  887. $stmt = $pdo->prepare("SELECT `password` FROM `mailbox`
  888. WHERE `kind` NOT REGEXP 'location|thing|group'
  889. AND `username` = :user AND authsource = 'mailcow'");
  890. $stmt->execute(array(':user' => $username));
  891. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  892. if (!verify_hash($row['password'], $password_old)) {
  893. $_SESSION['return'][] = array(
  894. 'type' => 'danger',
  895. 'log' => array(__FUNCTION__, $_data_log),
  896. 'msg' => 'access_denied'
  897. );
  898. return false;
  899. }
  900. if (!empty($_data['user_new_pass']) && !empty($_data['user_new_pass2'])) {
  901. $password_new = $_data['user_new_pass'];
  902. $password_new2 = $_data['user_new_pass2'];
  903. if (password_check($password_new, $password_new2) !== true) {
  904. return false;
  905. }
  906. $password_hashed = hash_password($password_new);
  907. $stmt = $pdo->prepare("UPDATE `mailbox` SET `password` = :password_hashed,
  908. `attributes` = JSON_SET(`attributes`, '$.force_pw_update', '0'),
  909. `attributes` = JSON_SET(`attributes`, '$.passwd_update', NOW())
  910. WHERE `username` = :username AND authsource = 'mailcow'");
  911. $stmt->execute(array(
  912. ':password_hashed' => $password_hashed,
  913. ':username' => $username
  914. ));
  915. }
  916. update_sogo_static_view();
  917. $_SESSION['return'][] = array(
  918. 'type' => 'success',
  919. 'log' => array(__FUNCTION__, $_data_log),
  920. 'msg' => array('mailbox_modified', htmlspecialchars($username))
  921. );
  922. }
  923. function user_get_alias_details($username) {
  924. global $pdo;
  925. global $lang;
  926. $data['direct_aliases'] = array();
  927. $data['shared_aliases'] = array();
  928. if ($_SESSION['mailcow_cc_role'] == "user") {
  929. $username = $_SESSION['mailcow_cc_username'];
  930. }
  931. if (!filter_var($username, FILTER_VALIDATE_EMAIL)) {
  932. return false;
  933. }
  934. if (!hasMailboxObjectAccess($username, $_SESSION['mailcow_cc_role'], $username)) {
  935. return false;
  936. }
  937. $data['address'] = $username;
  938. $stmt = $pdo->prepare("SELECT `address` AS `shared_aliases`, `public_comment` FROM `alias`
  939. WHERE `goto` REGEXP :username_goto
  940. AND `address` NOT LIKE '@%'
  941. AND `goto` != :username_goto2
  942. AND `address` != :username_address");
  943. $stmt->execute(array(
  944. ':username_goto' => '(^|,)'.$username.'($|,)',
  945. ':username_goto2' => $username,
  946. ':username_address' => $username
  947. ));
  948. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  949. while ($row = array_shift($run)) {
  950. $data['shared_aliases'][$row['shared_aliases']]['public_comment'] = htmlspecialchars($row['public_comment']);
  951. //$data['shared_aliases'][] = $row['shared_aliases'];
  952. }
  953. $stmt = $pdo->prepare("SELECT `address` AS `direct_aliases`, `public_comment` FROM `alias`
  954. WHERE `goto` = :username_goto
  955. AND `address` NOT LIKE '@%'
  956. AND `address` != :username_address");
  957. $stmt->execute(
  958. array(
  959. ':username_goto' => $username,
  960. ':username_address' => $username
  961. ));
  962. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  963. while ($row = array_shift($run)) {
  964. $data['direct_aliases'][$row['direct_aliases']]['public_comment'] = htmlspecialchars($row['public_comment']);
  965. }
  966. $stmt = $pdo->prepare("SELECT CONCAT(local_part, '@', alias_domain) AS `ad_alias`, `alias_domain` FROM `mailbox`
  967. LEFT OUTER JOIN `alias_domain` on `target_domain` = `domain`
  968. WHERE `username` = :username ;");
  969. $stmt->execute(array(':username' => $username));
  970. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  971. while ($row = array_shift($run)) {
  972. if (empty($row['ad_alias'])) {
  973. continue;
  974. }
  975. $data['direct_aliases'][$row['ad_alias']]['public_comment'] = $lang['add']['alias_domain'];
  976. $data['alias_domains'][] = $row['alias_domain'];
  977. }
  978. $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 '@%';");
  979. $stmt->execute(array(':username' => $username));
  980. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  981. while ($row = array_shift($run)) {
  982. $data['aliases_also_send_as'] = $row['send_as'];
  983. }
  984. $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 '@%';");
  985. $stmt->execute(array(':username' => $username));
  986. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  987. while ($row = array_shift($run)) {
  988. $data['aliases_send_as_all'] = $row['send_as'];
  989. }
  990. $stmt = $pdo->prepare("SELECT IFNULL(GROUP_CONCAT(`address` SEPARATOR ', '), '') as `address` FROM `alias` WHERE `goto` REGEXP :username AND `address` LIKE '@%';");
  991. $stmt->execute(array(':username' => '(^|,)'.$username.'($|,)'));
  992. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  993. while ($row = array_shift($run)) {
  994. $data['is_catch_all'] = $row['address'];
  995. }
  996. return $data;
  997. }
  998. function is_valid_domain_name($domain_name) {
  999. if (empty($domain_name)) {
  1000. return false;
  1001. }
  1002. $domain_name = idn_to_ascii($domain_name, 0, INTL_IDNA_VARIANT_UTS46);
  1003. return (preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $domain_name)
  1004. && preg_match("/^.{1,253}$/", $domain_name)
  1005. && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $domain_name));
  1006. }
  1007. function set_tfa($_data) {
  1008. global $pdo;
  1009. global $yubi;
  1010. global $tfa;
  1011. $_data_log = $_data;
  1012. $access_denied = null;
  1013. !isset($_data_log['confirm_password']) ?: $_data_log['confirm_password'] = '*';
  1014. $username = $_SESSION['mailcow_cc_username'];
  1015. // check for empty user and role
  1016. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) $access_denied = true;
  1017. // check admin confirm password
  1018. if ($access_denied === null) {
  1019. $stmt = $pdo->prepare("SELECT `password` FROM `admin`
  1020. WHERE `username` = :username");
  1021. $stmt->execute(array(':username' => $username));
  1022. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1023. if ($row) {
  1024. if (!verify_hash($row['password'], $_data["confirm_password"])) $access_denied = true;
  1025. else $access_denied = false;
  1026. }
  1027. }
  1028. // check mailbox confirm password
  1029. if ($access_denied === null) {
  1030. $stmt = $pdo->prepare("SELECT `password` FROM `mailbox`
  1031. WHERE `username` = :username");
  1032. $stmt->execute(array(':username' => $username));
  1033. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1034. if ($row) {
  1035. if (!verify_hash($row['password'], $_data["confirm_password"])) $access_denied = true;
  1036. else $access_denied = false;
  1037. }
  1038. }
  1039. // set access_denied error
  1040. if ($access_denied){
  1041. $_SESSION['return'][] = array(
  1042. 'type' => 'danger',
  1043. 'log' => array(__FUNCTION__, $_data_log),
  1044. 'msg' => 'access_denied'
  1045. );
  1046. return false;
  1047. }
  1048. switch ($_data["tfa_method"]) {
  1049. case "yubi_otp":
  1050. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  1051. $yubico_id = $_data['yubico_id'];
  1052. $yubico_key = $_data['yubico_key'];
  1053. $yubi = new Auth_Yubico($yubico_id, $yubico_key);
  1054. if (!$yubi) {
  1055. $_SESSION['return'][] = array(
  1056. 'type' => 'danger',
  1057. 'log' => array(__FUNCTION__, $_data_log),
  1058. 'msg' => 'access_denied'
  1059. );
  1060. return false;
  1061. }
  1062. if (!ctype_alnum($_data["otp_token"]) || strlen($_data["otp_token"]) != 44) {
  1063. $_SESSION['return'][] = array(
  1064. 'type' => 'danger',
  1065. 'log' => array(__FUNCTION__, $_data_log),
  1066. 'msg' => 'tfa_token_invalid'
  1067. );
  1068. return false;
  1069. }
  1070. $yauth = $yubi->verify($_data["otp_token"]);
  1071. if (PEAR::isError($yauth)) {
  1072. $_SESSION['return'][] = array(
  1073. 'type' => 'danger',
  1074. 'log' => array(__FUNCTION__, $_data_log),
  1075. 'msg' => array('yotp_verification_failed', $yauth->getMessage())
  1076. );
  1077. return false;
  1078. }
  1079. try {
  1080. // We could also do a modhex translation here
  1081. $yubico_modhex_id = substr($_data["otp_token"], 0, 12);
  1082. $stmt = $pdo->prepare("DELETE FROM `tfa`
  1083. WHERE `username` = :username
  1084. AND (`authmech` = 'yubi_otp' AND `secret` LIKE :modhex)");
  1085. $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id));
  1086. $stmt = $pdo->prepare("INSERT INTO `tfa` (`key_id`, `username`, `authmech`, `active`, `secret`) VALUES
  1087. (:key_id, :username, 'yubi_otp', '1', :secret)");
  1088. $stmt->execute(array(':key_id' => $key_id, ':username' => $username, ':secret' => $yubico_id . ':' . $yubico_key . ':' . $yubico_modhex_id));
  1089. }
  1090. catch (PDOException $e) {
  1091. $_SESSION['return'][] = array(
  1092. 'type' => 'danger',
  1093. 'log' => array(__FUNCTION__, $_data_log),
  1094. 'msg' => array('mysql_error', $e)
  1095. );
  1096. return false;
  1097. }
  1098. $_SESSION['return'][] = array(
  1099. 'type' => 'success',
  1100. 'log' => array(__FUNCTION__, $_data_log),
  1101. 'msg' => array('object_modified', htmlspecialchars($username))
  1102. );
  1103. break;
  1104. case "totp":
  1105. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  1106. if ($tfa->verifyCode($_POST['totp_secret'], $_POST['totp_confirm_token']) === true) {
  1107. //$stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
  1108. //$stmt->execute(array(':username' => $username));
  1109. $stmt = $pdo->prepare("INSERT INTO `tfa` (`username`, `key_id`, `authmech`, `secret`, `active`) VALUES (?, ?, 'totp', ?, '1')");
  1110. $stmt->execute(array($username, $key_id, $_POST['totp_secret']));
  1111. $_SESSION['return'][] = array(
  1112. 'type' => 'success',
  1113. 'log' => array(__FUNCTION__, $_data_log),
  1114. 'msg' => array('object_modified', $username)
  1115. );
  1116. }
  1117. else {
  1118. $_SESSION['return'][] = array(
  1119. 'type' => 'danger',
  1120. 'log' => array(__FUNCTION__, $_data_log),
  1121. 'msg' => 'totp_verification_failed'
  1122. );
  1123. }
  1124. break;
  1125. case "webauthn":
  1126. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  1127. $stmt = $pdo->prepare("INSERT INTO `tfa` (`username`, `key_id`, `authmech`, `keyHandle`, `publicKey`, `certificate`, `counter`, `active`)
  1128. VALUES (?, ?, 'webauthn', ?, ?, ?, ?, '1')");
  1129. $stmt->execute(array(
  1130. $username,
  1131. $key_id,
  1132. base64_encode($_data['registration']->credentialId),
  1133. $_data['registration']->credentialPublicKey,
  1134. $_data['registration']->certificate,
  1135. 0
  1136. ));
  1137. $_SESSION['return'][] = array(
  1138. 'type' => 'success',
  1139. 'log' => array(__FUNCTION__, $_data_log),
  1140. 'msg' => array('object_modified', $username)
  1141. );
  1142. break;
  1143. case "none":
  1144. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
  1145. $stmt->execute(array(':username' => $username));
  1146. $_SESSION['return'][] = array(
  1147. 'type' => 'success',
  1148. 'log' => array(__FUNCTION__, $_data_log),
  1149. 'msg' => array('object_modified', htmlspecialchars($username))
  1150. );
  1151. break;
  1152. }
  1153. }
  1154. function fido2($_data) {
  1155. global $pdo;
  1156. $_data_log = $_data;
  1157. // Not logging registration data, only actions
  1158. // Silent errors for "get" requests
  1159. switch ($_data["action"]) {
  1160. case "register":
  1161. $username = $_SESSION['mailcow_cc_username'];
  1162. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1163. $_SESSION['return'][] = array(
  1164. 'type' => 'danger',
  1165. 'log' => array(__FUNCTION__, $_data["action"]),
  1166. 'msg' => 'access_denied'
  1167. );
  1168. return false;
  1169. }
  1170. $stmt = $pdo->prepare("INSERT INTO `fido2` (`username`, `rpId`, `credentialPublicKey`, `certificateChain`, `certificate`, `certificateIssuer`, `certificateSubject`, `signatureCounter`, `AAGUID`, `credentialId`)
  1171. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
  1172. $stmt->execute(array(
  1173. $username,
  1174. $_data['registration']->rpId,
  1175. $_data['registration']->credentialPublicKey,
  1176. $_data['registration']->certificateChain,
  1177. $_data['registration']->certificate,
  1178. $_data['registration']->certificateIssuer,
  1179. $_data['registration']->certificateSubject,
  1180. $_data['registration']->signatureCounter,
  1181. $_data['registration']->AAGUID,
  1182. $_data['registration']->credentialId)
  1183. );
  1184. $_SESSION['return'][] = array(
  1185. 'type' => 'success',
  1186. 'log' => array(__FUNCTION__, $_data["action"]),
  1187. 'msg' => array('object_modified', $username)
  1188. );
  1189. break;
  1190. case "get_user_cids":
  1191. // Used to exclude existing CredentialIds while registering
  1192. $username = $_SESSION['mailcow_cc_username'];
  1193. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1194. return false;
  1195. }
  1196. $stmt = $pdo->prepare("SELECT `credentialId` FROM `fido2` WHERE `username` = :username");
  1197. $stmt->execute(array(':username' => $username));
  1198. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1199. while($row = array_shift($rows)) {
  1200. $cids[] = $row['credentialId'];
  1201. }
  1202. return $cids;
  1203. break;
  1204. case "get_all_cids":
  1205. // Only needed when using fido2 with username
  1206. $stmt = $pdo->query("SELECT `credentialId` FROM `fido2`");
  1207. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1208. while($row = array_shift($rows)) {
  1209. $cids[] = $row['credentialId'];
  1210. }
  1211. return $cids;
  1212. break;
  1213. case "get_by_b64cid":
  1214. if (!isset($_data['cid']) || empty($_data['cid'])) {
  1215. return false;
  1216. }
  1217. $stmt = $pdo->prepare("SELECT `certificateSubject`, `username`, `credentialPublicKey`, SHA2(`credentialId`, 256) AS `cid` FROM `fido2` WHERE `credentialId` = :cid");
  1218. $stmt->execute(array(':cid' => base64_decode($_data['cid'])));
  1219. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1220. if (empty($row) || empty($row['credentialPublicKey']) || empty($row['username'])) {
  1221. return false;
  1222. }
  1223. $data['pub_key'] = $row['credentialPublicKey'];
  1224. $data['username'] = $row['username'];
  1225. $data['subject'] = $row['certificateSubject'];
  1226. $data['cid'] = $row['cid'];
  1227. return $data;
  1228. break;
  1229. case "get_friendly_names":
  1230. $username = $_SESSION['mailcow_cc_username'];
  1231. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1232. return false;
  1233. }
  1234. $stmt = $pdo->prepare("SELECT SHA2(`credentialId`, 256) AS `cid`, `created`, `certificateSubject`, `friendlyName` FROM `fido2` WHERE `username` = :username");
  1235. $stmt->execute(array(':username' => $username));
  1236. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1237. while($row = array_shift($rows)) {
  1238. $fns[] = array(
  1239. "subject" => (empty($row['certificateSubject']) ? 'Unknown (' . $row['created'] . ')' : $row['certificateSubject']),
  1240. "fn" => $row['friendlyName'],
  1241. "cid" => $row['cid']
  1242. );
  1243. }
  1244. return $fns;
  1245. break;
  1246. case "unset_fido2_key":
  1247. $username = $_SESSION['mailcow_cc_username'];
  1248. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1249. $_SESSION['return'][] = array(
  1250. 'type' => 'danger',
  1251. 'log' => array(__FUNCTION__, $_data["action"]),
  1252. 'msg' => 'access_denied'
  1253. );
  1254. return false;
  1255. }
  1256. $stmt = $pdo->prepare("DELETE FROM `fido2` WHERE `username` = :username AND SHA2(`credentialId`, 256) = :cid");
  1257. $stmt->execute(array(
  1258. ':username' => $username,
  1259. ':cid' => $_data['post_data']['unset_fido2_key']
  1260. ));
  1261. $_SESSION['return'][] = array(
  1262. 'type' => 'success',
  1263. 'log' => array(__FUNCTION__, $_data_log),
  1264. 'msg' => array('object_modified', htmlspecialchars($username))
  1265. );
  1266. break;
  1267. case "edit_fn":
  1268. $username = $_SESSION['mailcow_cc_username'];
  1269. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) {
  1270. $_SESSION['return'][] = array(
  1271. 'type' => 'danger',
  1272. 'log' => array(__FUNCTION__, $_data["action"]),
  1273. 'msg' => 'access_denied'
  1274. );
  1275. return false;
  1276. }
  1277. $stmt = $pdo->prepare("UPDATE `fido2` SET `friendlyName` = :friendlyName WHERE SHA2(`credentialId`, 256) = :cid AND `username` = :username");
  1278. $stmt->execute(array(
  1279. ':username' => $username,
  1280. ':friendlyName' => $_data['fido2_attrs']['fido2_fn'],
  1281. ':cid' => $_data['fido2_attrs']['fido2_cid']
  1282. ));
  1283. $_SESSION['return'][] = array(
  1284. 'type' => 'success',
  1285. 'log' => array(__FUNCTION__, $_data_log),
  1286. 'msg' => array('object_modified', htmlspecialchars($username))
  1287. );
  1288. break;
  1289. }
  1290. }
  1291. function unset_tfa_key($_data) {
  1292. // Can only unset own keys
  1293. // Needs at least one key left
  1294. global $pdo;
  1295. global $lang;
  1296. $_data_log = $_data;
  1297. $access_denied = null;
  1298. $id = intval($_data['unset_tfa_key']);
  1299. $username = $_SESSION['mailcow_cc_username'];
  1300. // check for empty user and role
  1301. if (!isset($_SESSION['mailcow_cc_role']) || empty($username)) $access_denied = true;
  1302. try {
  1303. if (!is_numeric($id)) $access_denied = true;
  1304. // set access_denied error
  1305. if ($access_denied){
  1306. $_SESSION['return'][] = array(
  1307. 'type' => 'danger',
  1308. 'log' => array(__FUNCTION__, $_data_log),
  1309. 'msg' => 'access_denied'
  1310. );
  1311. return false;
  1312. }
  1313. // check if it's last key
  1314. $stmt = $pdo->prepare("SELECT COUNT(*) AS `keys` FROM `tfa`
  1315. WHERE `username` = :username AND `active` = '1'");
  1316. $stmt->execute(array(':username' => $username));
  1317. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1318. if ($row['keys'] == "1") {
  1319. $_SESSION['return'][] = array(
  1320. 'type' => 'danger',
  1321. 'log' => array(__FUNCTION__, $_data_log),
  1322. 'msg' => 'last_key'
  1323. );
  1324. return false;
  1325. }
  1326. // delete key
  1327. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username AND `id` = :id");
  1328. $stmt->execute(array(':username' => $username, ':id' => $id));
  1329. $_SESSION['return'][] = array(
  1330. 'type' => 'success',
  1331. 'log' => array(__FUNCTION__, $_data_log),
  1332. 'msg' => array('object_modified', $username)
  1333. );
  1334. }
  1335. catch (PDOException $e) {
  1336. $_SESSION['return'][] = array(
  1337. 'type' => 'danger',
  1338. 'log' => array(__FUNCTION__, $_data_log),
  1339. 'msg' => array('mysql_error', $e)
  1340. );
  1341. return false;
  1342. }
  1343. }
  1344. function get_tfa($username = null, $id = null) {
  1345. global $pdo;
  1346. if (isset($_SESSION['mailcow_cc_username'])) {
  1347. $username = $_SESSION['mailcow_cc_username'];
  1348. }
  1349. elseif (empty($username)) {
  1350. return false;
  1351. }
  1352. if (!isset($id)){
  1353. // fetch all tfa methods - just get information about possible authenticators
  1354. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `authmech` FROM `tfa`
  1355. WHERE `username` = :username AND `active` = '1'");
  1356. $stmt->execute(array(':username' => $username));
  1357. $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1358. // no tfa methods found
  1359. if (count($results) == 0) {
  1360. $data['name'] = 'none';
  1361. $data['pretty'] = "-";
  1362. $data['additional'] = array();
  1363. return $data;
  1364. }
  1365. $data['additional'] = $results;
  1366. return $data;
  1367. } else {
  1368. // fetch specific authenticator details by id
  1369. $stmt = $pdo->prepare("SELECT * FROM `tfa`
  1370. WHERE `username` = :username AND `id` = :id AND `active` = '1'");
  1371. $stmt->execute(array(':username' => $username, ':id' => $id));
  1372. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1373. if (isset($row["authmech"])) {
  1374. switch ($row["authmech"]) {
  1375. case "yubi_otp":
  1376. $data['name'] = "yubi_otp";
  1377. $data['pretty'] = "Yubico OTP";
  1378. $stmt = $pdo->prepare("SELECT `id`, `key_id`, RIGHT(`secret`, 12) AS 'modhex' FROM `tfa` WHERE `authmech` = 'yubi_otp' AND `username` = :username AND `id` = :id");
  1379. $stmt->execute(array(
  1380. ':username' => $username,
  1381. ':id' => $id
  1382. ));
  1383. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1384. while($row = array_shift($rows)) {
  1385. $data['additional'][] = $row;
  1386. }
  1387. return $data;
  1388. break;
  1389. // u2f - deprecated, should be removed
  1390. case "u2f":
  1391. $data['name'] = "u2f";
  1392. $data['pretty'] = "Fido U2F";
  1393. $stmt = $pdo->prepare("SELECT `id`, `key_id` FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username AND `id` = :id");
  1394. $stmt->execute(array(
  1395. ':username' => $username,
  1396. ':id' => $id
  1397. ));
  1398. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1399. while($row = array_shift($rows)) {
  1400. $data['additional'][] = $row;
  1401. }
  1402. return $data;
  1403. break;
  1404. case "hotp":
  1405. $data['name'] = "hotp";
  1406. $data['pretty'] = "HMAC-based OTP";
  1407. return $data;
  1408. break;
  1409. case "totp":
  1410. $data['name'] = "totp";
  1411. $data['pretty'] = "Time-based OTP";
  1412. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `secret` FROM `tfa` WHERE `authmech` = 'totp' AND `username` = :username AND `id` = :id");
  1413. $stmt->execute(array(
  1414. ':username' => $username,
  1415. ':id' => $id
  1416. ));
  1417. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1418. while($row = array_shift($rows)) {
  1419. $data['additional'][] = $row;
  1420. }
  1421. return $data;
  1422. break;
  1423. case "webauthn":
  1424. $data['name'] = "webauthn";
  1425. $data['pretty'] = "WebAuthn";
  1426. $stmt = $pdo->prepare("SELECT `id`, `key_id` FROM `tfa` WHERE `authmech` = 'webauthn' AND `username` = :username AND `id` = :id");
  1427. $stmt->execute(array(
  1428. ':username' => $username,
  1429. ':id' => $id
  1430. ));
  1431. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1432. while($row = array_shift($rows)) {
  1433. $data['additional'][] = $row;
  1434. }
  1435. return $data;
  1436. break;
  1437. default:
  1438. $data['name'] = 'none';
  1439. $data['pretty'] = "-";
  1440. return $data;
  1441. break;
  1442. }
  1443. }
  1444. else {
  1445. $data['name'] = 'none';
  1446. $data['pretty'] = "-";
  1447. return $data;
  1448. }
  1449. }
  1450. }
  1451. function verify_tfa_login($username, $_data) {
  1452. global $pdo;
  1453. global $yubi;
  1454. global $u2f;
  1455. global $tfa;
  1456. global $WebAuthn;
  1457. if ($_data['tfa_method'] != 'u2f'){
  1458. switch ($_data["tfa_method"]) {
  1459. case "yubi_otp":
  1460. if (!ctype_alnum($_data['token']) || strlen($_data['token']) != 44) {
  1461. $_SESSION['return'][] = array(
  1462. 'type' => 'danger',
  1463. 'log' => array(__FUNCTION__, $username, '*'),
  1464. 'msg' => array('yotp_verification_failed', 'token length error')
  1465. );
  1466. return false;
  1467. }
  1468. $yubico_modhex_id = substr($_data['token'], 0, 12);
  1469. $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
  1470. WHERE `username` = :username
  1471. AND `authmech` = 'yubi_otp'
  1472. AND `active` = '1'
  1473. AND `secret` LIKE :modhex");
  1474. $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id));
  1475. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1476. $yubico_auth = explode(':', $row['secret']);
  1477. $yubi = new Auth_Yubico($yubico_auth[0], $yubico_auth[1]);
  1478. $yauth = $yubi->verify($_data['token']);
  1479. if (PEAR::isError($yauth)) {
  1480. $_SESSION['return'][] = array(
  1481. 'type' => 'danger',
  1482. 'log' => array(__FUNCTION__, $username, '*'),
  1483. 'msg' => array('yotp_verification_failed', $yauth->getMessage())
  1484. );
  1485. return false;
  1486. }
  1487. else {
  1488. $_SESSION['tfa_id'] = $row['id'];
  1489. $_SESSION['return'][] = array(
  1490. 'type' => 'success',
  1491. 'log' => array(__FUNCTION__, $username, '*'),
  1492. 'msg' => 'verified_yotp_login'
  1493. );
  1494. return true;
  1495. }
  1496. $_SESSION['return'][] = array(
  1497. 'type' => 'danger',
  1498. 'log' => array(__FUNCTION__, $username, '*'),
  1499. 'msg' => array('yotp_verification_failed', 'unknown')
  1500. );
  1501. return false;
  1502. break;
  1503. case "hotp":
  1504. return false;
  1505. break;
  1506. case "totp":
  1507. try {
  1508. $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
  1509. WHERE `username` = :username
  1510. AND `authmech` = 'totp'
  1511. AND `id` = :id
  1512. AND `active`='1'");
  1513. $stmt->execute(array(':username' => $username, ':id' => $_data['id']));
  1514. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1515. foreach ($rows as $row) {
  1516. if ($tfa->verifyCode($row['secret'], $_data['token']) === true) {
  1517. $_SESSION['tfa_id'] = $row['id'];
  1518. $_SESSION['return'][] = array(
  1519. 'type' => 'success',
  1520. 'log' => array(__FUNCTION__, $username, '*'),
  1521. 'msg' => 'verified_totp_login'
  1522. );
  1523. return true;
  1524. }
  1525. }
  1526. $_SESSION['return'][] = array(
  1527. 'type' => 'danger',
  1528. 'log' => array(__FUNCTION__, $username, '*'),
  1529. 'msg' => 'totp_verification_failed'
  1530. );
  1531. return false;
  1532. }
  1533. catch (PDOException $e) {
  1534. $_SESSION['return'][] = array(
  1535. 'type' => 'danger',
  1536. 'log' => array(__FUNCTION__, $username, '*'),
  1537. 'msg' => array('mysql_error', $e)
  1538. );
  1539. return false;
  1540. }
  1541. break;
  1542. case "webauthn":
  1543. $tokenData = json_decode($_data['token']);
  1544. $clientDataJSON = base64_decode($tokenData->clientDataJSON);
  1545. $authenticatorData = base64_decode($tokenData->authenticatorData);
  1546. $signature = base64_decode($tokenData->signature);
  1547. $id = base64_decode($tokenData->id);
  1548. $challenge = $_SESSION['challenge'];
  1549. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `keyHandle`, `username`, `publicKey` FROM `tfa` WHERE `id` = :id AND `active`='1'");
  1550. $stmt->execute(array(':id' => $_data['id']));
  1551. $process_webauthn = $stmt->fetch(PDO::FETCH_ASSOC);
  1552. if (empty($process_webauthn)){
  1553. $_SESSION['return'][] = array(
  1554. 'type' => 'danger',
  1555. 'log' => array(__FUNCTION__, $username, '*'),
  1556. 'msg' => array('webauthn_authenticator_failed')
  1557. );
  1558. return false;
  1559. }
  1560. if (empty($process_webauthn['publicKey']) || $process_webauthn['publicKey'] === false) {
  1561. $_SESSION['return'][] = array(
  1562. 'type' => 'danger',
  1563. 'log' => array(__FUNCTION__, $username, '*'),
  1564. 'msg' => array('webauthn_publickey_failed')
  1565. );
  1566. return false;
  1567. }
  1568. if ($process_webauthn['username'] != $_SESSION['pending_mailcow_cc_username']){
  1569. $_SESSION['return'][] = array(
  1570. 'type' => 'danger',
  1571. 'log' => array(__FUNCTION__, $username, '*'),
  1572. 'msg' => array('webauthn_username_failed')
  1573. );
  1574. return false;
  1575. }
  1576. try {
  1577. $WebAuthn->processGet($clientDataJSON, $authenticatorData, $signature, $process_webauthn['publicKey'], $challenge, null, $GLOBALS['WEBAUTHN_UV_FLAG_LOGIN'], $GLOBALS['WEBAUTHN_USER_PRESENT_FLAG']);
  1578. }
  1579. catch (Throwable $ex) {
  1580. $_SESSION['return'][] = array(
  1581. 'type' => 'danger',
  1582. 'log' => array(__FUNCTION__, $username, '*'),
  1583. 'msg' => array('webauthn_verification_failed', $ex->getMessage())
  1584. );
  1585. return false;
  1586. }
  1587. $stmt = $pdo->prepare("SELECT `superadmin` FROM `admin` WHERE `username` = :username");
  1588. $stmt->execute(array(':username' => $process_webauthn['username']));
  1589. $obj_props = $stmt->fetch(PDO::FETCH_ASSOC);
  1590. if ($obj_props['superadmin'] === 1) {
  1591. $_SESSION["mailcow_cc_role"] = "admin";
  1592. }
  1593. elseif ($obj_props['superadmin'] === 0) {
  1594. $_SESSION["mailcow_cc_role"] = "domainadmin";
  1595. }
  1596. else {
  1597. $stmt = $pdo->prepare("SELECT `username` FROM `mailbox` WHERE `username` = :username");
  1598. $stmt->execute(array(':username' => $process_webauthn['username']));
  1599. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1600. if (!empty($row['username'])) {
  1601. $_SESSION["mailcow_cc_role"] = "user";
  1602. } else {
  1603. $_SESSION['return'][] = array(
  1604. 'type' => 'danger',
  1605. 'log' => array(__FUNCTION__, $username, '*'),
  1606. 'msg' => array('webauthn_role_failed')
  1607. );
  1608. return false;
  1609. }
  1610. }
  1611. $_SESSION["mailcow_cc_username"] = $process_webauthn['username'];
  1612. $_SESSION['tfa_id'] = $process_webauthn['id'];
  1613. $_SESSION['authReq'] = null;
  1614. unset($_SESSION["challenge"]);
  1615. $_SESSION['return'][] = array(
  1616. 'type' => 'success',
  1617. 'log' => array("webauthn_login"),
  1618. 'msg' => array('logged_in_as', $process_webauthn['username'])
  1619. );
  1620. return true;
  1621. break;
  1622. default:
  1623. $_SESSION['return'][] = array(
  1624. 'type' => 'danger',
  1625. 'log' => array(__FUNCTION__, $username, '*'),
  1626. 'msg' => 'unknown_tfa_method'
  1627. );
  1628. return false;
  1629. break;
  1630. }
  1631. return false;
  1632. } else {
  1633. // delete old keys that used u2f
  1634. $stmt = $pdo->prepare("SELECT * FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username");
  1635. $stmt->execute(array(':username' => $username));
  1636. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1637. if (count($rows) == 0) return false;
  1638. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username");
  1639. $stmt->execute(array(':username' => $username));
  1640. return true;
  1641. }
  1642. }
  1643. function admin_api($access, $action, $data = null) {
  1644. global $pdo;
  1645. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1646. $_SESSION['return'][] = array(
  1647. 'type' => 'danger',
  1648. 'log' => array(__FUNCTION__),
  1649. 'msg' => 'access_denied'
  1650. );
  1651. return false;
  1652. }
  1653. if ($access !== "ro" && $access !== "rw") {
  1654. $_SESSION['return'][] = array(
  1655. 'type' => 'danger',
  1656. 'log' => array(__FUNCTION__),
  1657. 'msg' => 'invalid access type'
  1658. );
  1659. return false;
  1660. }
  1661. if ($action == "edit") {
  1662. $active = (!empty($data['active'])) ? 1 : 0;
  1663. $skip_ip_check = (isset($data['skip_ip_check'])) ? 1 : 0;
  1664. $allow_from = array();
  1665. if (isset($data['allow_from'])) {
  1666. $allow_from = array_map('trim', preg_split( "/( |,|;|\n)/", $data['allow_from']));
  1667. }
  1668. foreach ($allow_from as $key => $val) {
  1669. if (empty($val)) {
  1670. unset($allow_from[$key]);
  1671. continue;
  1672. }
  1673. if (valid_network($val) !== true) {
  1674. $_SESSION['return'][] = array(
  1675. 'type' => 'warning',
  1676. 'log' => array(__FUNCTION__, $data),
  1677. 'msg' => array('ip_invalid', htmlspecialchars($allow_from[$key]))
  1678. );
  1679. unset($allow_from[$key]);
  1680. continue;
  1681. }
  1682. }
  1683. $allow_from = implode(',', array_unique(array_filter($allow_from)));
  1684. if (empty($allow_from) && $skip_ip_check == 0) {
  1685. $_SESSION['return'][] = array(
  1686. 'type' => 'danger',
  1687. 'log' => array(__FUNCTION__, $data),
  1688. 'msg' => 'ip_list_empty'
  1689. );
  1690. return false;
  1691. }
  1692. $api_key = implode('-', array(
  1693. strtoupper(bin2hex(random_bytes(3))),
  1694. strtoupper(bin2hex(random_bytes(3))),
  1695. strtoupper(bin2hex(random_bytes(3))),
  1696. strtoupper(bin2hex(random_bytes(3))),
  1697. strtoupper(bin2hex(random_bytes(3)))
  1698. ));
  1699. $stmt = $pdo->query("SELECT `api_key` FROM `api` WHERE `access` = '" . $access . "'");
  1700. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  1701. if (empty($num_results)) {
  1702. $stmt = $pdo->prepare("INSERT INTO `api` (`api_key`, `skip_ip_check`, `active`, `allow_from`, `access`)
  1703. VALUES (:api_key, :skip_ip_check, :active, :allow_from, :access);");
  1704. $stmt->execute(array(
  1705. ':api_key' => $api_key,
  1706. ':skip_ip_check' => $skip_ip_check,
  1707. ':active' => $active,
  1708. ':allow_from' => $allow_from,
  1709. ':access' => $access
  1710. ));
  1711. }
  1712. else {
  1713. if ($skip_ip_check == 0) {
  1714. $stmt = $pdo->prepare("UPDATE `api` SET `skip_ip_check` = :skip_ip_check,
  1715. `active` = :active,
  1716. `allow_from` = :allow_from
  1717. WHERE `access` = :access;");
  1718. $stmt->execute(array(
  1719. ':active' => $active,
  1720. ':skip_ip_check' => $skip_ip_check,
  1721. ':allow_from' => $allow_from,
  1722. ':access' => $access
  1723. ));
  1724. }
  1725. else {
  1726. $stmt = $pdo->prepare("UPDATE `api` SET `skip_ip_check` = :skip_ip_check,
  1727. `active` = :active
  1728. WHERE `access` = :access;");
  1729. $stmt->execute(array(
  1730. ':active' => $active,
  1731. ':skip_ip_check' => $skip_ip_check,
  1732. ':access' => $access
  1733. ));
  1734. }
  1735. }
  1736. }
  1737. elseif ($action == "regen_key") {
  1738. $api_key = implode('-', array(
  1739. strtoupper(bin2hex(random_bytes(3))),
  1740. strtoupper(bin2hex(random_bytes(3))),
  1741. strtoupper(bin2hex(random_bytes(3))),
  1742. strtoupper(bin2hex(random_bytes(3))),
  1743. strtoupper(bin2hex(random_bytes(3)))
  1744. ));
  1745. $stmt = $pdo->prepare("UPDATE `api` SET `api_key` = :api_key WHERE `access` = :access");
  1746. $stmt->execute(array(
  1747. ':api_key' => $api_key,
  1748. ':access' => $access
  1749. ));
  1750. }
  1751. elseif ($action == "get") {
  1752. $stmt = $pdo->query("SELECT * FROM `api` WHERE `access` = '" . $access . "'");
  1753. $apidata = $stmt->fetch(PDO::FETCH_ASSOC);
  1754. if ($apidata !== false) {
  1755. $apidata['allow_from'] = str_replace(',', PHP_EOL, $apidata['allow_from']);
  1756. }
  1757. return $apidata;
  1758. }
  1759. $_SESSION['return'][] = array(
  1760. 'type' => 'success',
  1761. 'log' => array(__FUNCTION__, $data),
  1762. 'msg' => 'admin_api_modified'
  1763. );
  1764. }
  1765. function license($action, $data = null) {
  1766. global $pdo;
  1767. global $redis;
  1768. global $lang;
  1769. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1770. $_SESSION['return'][] = array(
  1771. 'type' => 'danger',
  1772. 'log' => array(__FUNCTION__),
  1773. 'msg' => 'access_denied'
  1774. );
  1775. return false;
  1776. }
  1777. switch ($action) {
  1778. case "verify":
  1779. // Keep result until revalidate button is pressed or session expired
  1780. $stmt = $pdo->query("SELECT `version` FROM `versions` WHERE `application` = 'GUID'");
  1781. $versions = $stmt->fetch(PDO::FETCH_ASSOC);
  1782. $post = array('guid' => $versions['version']);
  1783. $curl = curl_init('https://verify.mailcow.email');
  1784. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  1785. curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
  1786. curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
  1787. $response = curl_exec($curl);
  1788. curl_close($curl);
  1789. $json_return = json_decode($response, true);
  1790. if ($response && $json_return) {
  1791. if ($json_return['response'] === "ok") {
  1792. $_SESSION['gal']['valid'] = "true";
  1793. $_SESSION['gal']['c'] = $json_return['c'];
  1794. $_SESSION['gal']['s'] = $json_return['s'];
  1795. if ($json_return['m'] == 'NoMoore') {
  1796. $_SESSION['gal']['m'] = '🐄';
  1797. }
  1798. else {
  1799. $_SESSION['gal']['m'] = str_repeat('🐄', substr_count($json_return['m'], 'o'));
  1800. }
  1801. }
  1802. elseif ($json_return['response'] === "invalid") {
  1803. $_SESSION['gal']['valid'] = "false";
  1804. $_SESSION['gal']['c'] = $lang['mailbox']['no'];
  1805. $_SESSION['gal']['s'] = $lang['mailbox']['no'];
  1806. $_SESSION['gal']['m'] = $lang['mailbox']['no'];
  1807. }
  1808. }
  1809. else {
  1810. $_SESSION['gal']['valid'] = "false";
  1811. $_SESSION['gal']['c'] = $lang['danger']['temp_error'];
  1812. $_SESSION['gal']['s'] = $lang['danger']['temp_error'];
  1813. $_SESSION['gal']['m'] = $lang['danger']['temp_error'];
  1814. }
  1815. try {
  1816. // json_encode needs "true"/"false" instead of true/false, to not encode it to 0 or 1
  1817. $redis->Set('LICENSE_STATUS_CACHE', json_encode($_SESSION['gal']));
  1818. }
  1819. catch (RedisException $e) {
  1820. $_SESSION['return'][] = array(
  1821. 'type' => 'danger',
  1822. 'log' => array(__FUNCTION__, $_action, $_data_log),
  1823. 'msg' => array('redis_error', $e)
  1824. );
  1825. return false;
  1826. }
  1827. return $_SESSION['gal']['valid'];
  1828. break;
  1829. case "guid":
  1830. $stmt = $pdo->query("SELECT `version` FROM `versions` WHERE `application` = 'GUID'");
  1831. $versions = $stmt->fetch(PDO::FETCH_ASSOC);
  1832. return $versions['version'];
  1833. break;
  1834. }
  1835. }
  1836. function rspamd_ui($action, $data = null) {
  1837. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1838. $_SESSION['return'][] = array(
  1839. 'type' => 'danger',
  1840. 'log' => array(__FUNCTION__),
  1841. 'msg' => 'access_denied'
  1842. );
  1843. return false;
  1844. }
  1845. switch ($action) {
  1846. case "edit":
  1847. $rspamd_ui_pass = $data['rspamd_ui_pass'];
  1848. $rspamd_ui_pass2 = $data['rspamd_ui_pass2'];
  1849. if (empty($rspamd_ui_pass) || empty($rspamd_ui_pass2)) {
  1850. $_SESSION['return'][] = array(
  1851. 'type' => 'danger',
  1852. 'log' => array(__FUNCTION__, '*', '*'),
  1853. 'msg' => 'password_empty'
  1854. );
  1855. return false;
  1856. }
  1857. if ($rspamd_ui_pass != $rspamd_ui_pass2) {
  1858. $_SESSION['return'][] = array(
  1859. 'type' => 'danger',
  1860. 'log' => array(__FUNCTION__, '*', '*'),
  1861. 'msg' => 'password_mismatch'
  1862. );
  1863. return false;
  1864. }
  1865. if (strlen($rspamd_ui_pass) < 6) {
  1866. $_SESSION['return'][] = array(
  1867. 'type' => 'danger',
  1868. 'log' => array(__FUNCTION__, '*', '*'),
  1869. 'msg' => 'rspamd_ui_pw_length'
  1870. );
  1871. return false;
  1872. }
  1873. $docker_return = docker('post', 'rspamd-mailcow', 'exec', array('cmd' => 'rspamd', 'task' => 'worker_password', 'raw' => $rspamd_ui_pass), array('Content-Type: application/json'));
  1874. if ($docker_return_array = json_decode($docker_return, true)) {
  1875. if ($docker_return_array['type'] == 'success') {
  1876. $_SESSION['return'][] = array(
  1877. 'type' => 'success',
  1878. 'log' => array(__FUNCTION__, '*', '*'),
  1879. 'msg' => 'rspamd_ui_pw_set'
  1880. );
  1881. return true;
  1882. }
  1883. else {
  1884. $_SESSION['return'][] = array(
  1885. 'type' => $docker_return_array['type'],
  1886. 'log' => array(__FUNCTION__, '*', '*'),
  1887. 'msg' => $docker_return_array['msg']
  1888. );
  1889. return false;
  1890. }
  1891. }
  1892. else {
  1893. $_SESSION['return'][] = array(
  1894. 'type' => 'danger',
  1895. 'log' => array(__FUNCTION__, '*', '*'),
  1896. 'msg' => 'unknown'
  1897. );
  1898. return false;
  1899. }
  1900. break;
  1901. }
  1902. }
  1903. function cors($action, $data = null) {
  1904. global $redis;
  1905. switch ($action) {
  1906. case "edit":
  1907. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1908. $_SESSION['return'][] = array(
  1909. 'type' => 'danger',
  1910. 'log' => array(__FUNCTION__, $action, $data),
  1911. 'msg' => 'access_denied'
  1912. );
  1913. return false;
  1914. }
  1915. $allowed_origins = isset($data['allowed_origins']) ? $data['allowed_origins'] : array($_SERVER['SERVER_NAME']);
  1916. $allowed_origins = !is_array($allowed_origins) ? array_filter(array_map('trim', explode("\n", $allowed_origins))) : $allowed_origins;
  1917. foreach ($allowed_origins as $origin) {
  1918. if (!filter_var($origin, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) && $origin != '*') {
  1919. $_SESSION['return'][] = array(
  1920. 'type' => 'danger',
  1921. 'log' => array(__FUNCTION__, $action, $data),
  1922. 'msg' => 'cors_invalid_origin'
  1923. );
  1924. return false;
  1925. }
  1926. }
  1927. $allowed_methods = isset($data['allowed_methods']) ? $data['allowed_methods'] : array('GET', 'POST', 'PUT', 'DELETE');
  1928. $allowed_methods = !is_array($allowed_methods) ? array_map('trim', preg_split( "/( |,|;|\n)/", $allowed_methods)) : $allowed_methods;
  1929. $available_methods = array('GET', 'POST', 'PUT', 'DELETE');
  1930. foreach ($allowed_methods as $method) {
  1931. if (!in_array($method, $available_methods)) {
  1932. $_SESSION['return'][] = array(
  1933. 'type' => 'danger',
  1934. 'log' => array(__FUNCTION__, $action, $data),
  1935. 'msg' => 'cors_invalid_method'
  1936. );
  1937. return false;
  1938. }
  1939. }
  1940. try {
  1941. $redis->hMSet('CORS_SETTINGS', array(
  1942. 'allowed_origins' => implode(', ', $allowed_origins),
  1943. 'allowed_methods' => implode(', ', $allowed_methods)
  1944. ));
  1945. } catch (RedisException $e) {
  1946. $_SESSION['return'][] = array(
  1947. 'type' => 'danger',
  1948. 'log' => array(__FUNCTION__, $action, $data),
  1949. 'msg' => array('redis_error', $e)
  1950. );
  1951. return false;
  1952. }
  1953. $_SESSION['return'][] = array(
  1954. 'type' => 'success',
  1955. 'log' => array(__FUNCTION__, $action, $data),
  1956. 'msg' => 'cors_headers_edited'
  1957. );
  1958. return true;
  1959. break;
  1960. case "get":
  1961. try {
  1962. $cors_settings = $redis->hMGet('CORS_SETTINGS', array('allowed_origins', 'allowed_methods'));
  1963. } catch (RedisException $e) {
  1964. $_SESSION['return'][] = array(
  1965. 'type' => 'danger',
  1966. 'log' => array(__FUNCTION__, $action, $data),
  1967. 'msg' => array('redis_error', $e)
  1968. );
  1969. }
  1970. $cors_settings = !$cors_settings ? array('allowed_origins' => $_SERVER['SERVER_NAME'], 'allowed_methods' => 'GET, POST, PUT, DELETE') : $cors_settings;
  1971. $cors_settings['allowed_origins'] = empty($cors_settings['allowed_origins']) ? $_SERVER['SERVER_NAME'] : $cors_settings['allowed_origins'];
  1972. $cors_settings['allowed_methods'] = empty($cors_settings['allowed_methods']) ? 'GET, POST, PUT, DELETE, OPTION' : $cors_settings['allowed_methods'];
  1973. return $cors_settings;
  1974. break;
  1975. case "set_headers":
  1976. $cors_settings = cors('get');
  1977. // check if requested origin is in allowed origins
  1978. $allowed_origins = explode(', ', $cors_settings['allowed_origins']);
  1979. $cors_settings['allowed_origins'] = $allowed_origins[0];
  1980. if (in_array('*', $allowed_origins)){
  1981. $cors_settings['allowed_origins'] = '*';
  1982. } else if (in_array($_SERVER['HTTP_ORIGIN'], $allowed_origins)) {
  1983. $cors_settings['allowed_origins'] = $_SERVER['HTTP_ORIGIN'];
  1984. }
  1985. // always allow OPTIONS for preflight request
  1986. $cors_settings["allowed_methods"] = empty($cors_settings["allowed_methods"]) ? 'OPTIONS' : $cors_settings["allowed_methods"] . ', ' . 'OPTIONS';
  1987. header('Access-Control-Allow-Origin: ' . $cors_settings['allowed_origins']);
  1988. header('Access-Control-Allow-Methods: '. $cors_settings['allowed_methods']);
  1989. header('Access-Control-Allow-Headers: Accept, Content-Type, X-Api-Key, Origin');
  1990. // Access-Control settings requested, this is just a preflight request
  1991. if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS' &&
  1992. isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']) &&
  1993. isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
  1994. $allowed_methods = explode(', ', $cors_settings["allowed_methods"]);
  1995. if (in_array($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'], $allowed_methods, true))
  1996. // method allowed send 200 OK
  1997. http_response_code(200);
  1998. else
  1999. // method not allowed send 405 METHOD NOT ALLOWED
  2000. http_response_code(405);
  2001. exit;
  2002. }
  2003. break;
  2004. }
  2005. }
  2006. function getBaseURL() {
  2007. $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
  2008. $host = $_SERVER['HTTP_HOST'];
  2009. $base_url = $protocol . '://' . $host;
  2010. return $base_url;
  2011. }
  2012. function uuid4() {
  2013. $data = openssl_random_pseudo_bytes(16);
  2014. $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
  2015. $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
  2016. return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
  2017. }
  2018. function identity_provider($_action, $_data = null, $_extra = null) {
  2019. global $pdo;
  2020. $data_log = $_data;
  2021. if (isset($data_log['client_secret'])) $data_log['client_secret'] = '*';
  2022. if (isset($data_log['access_token'])) $data_log['access_token'] = '*';
  2023. switch ($_action) {
  2024. case 'get':
  2025. $settings = array();
  2026. $stmt = $pdo->prepare("SELECT * FROM `identity_provider`;");
  2027. $stmt->execute();
  2028. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2029. foreach($rows as $row){
  2030. if ($row["key"] == 'mappers' || $row["key"] == 'templates'){
  2031. $settings[$row["key"]] = json_decode($row["value"]);
  2032. } else {
  2033. $settings[$row["key"]] = $row["value"];
  2034. }
  2035. }
  2036. // return default client_scopes for generic-oidc if none is set
  2037. if ($settings["authsource"] == "generic-oidc" && empty($settings["client_scopes"])){
  2038. $settings["client_scopes"] = "openid profile email";
  2039. }
  2040. if ($_extra['hide_sensitive']){
  2041. $settings['client_secret'] = '';
  2042. $settings['access_token'] = '';
  2043. }
  2044. return $settings;
  2045. break;
  2046. case 'edit':
  2047. if ($_SESSION['mailcow_cc_role'] != "admin") {
  2048. $_SESSION['return'][] = array(
  2049. 'type' => 'danger',
  2050. 'log' => array(__FUNCTION__, $_action, $_data),
  2051. 'msg' => 'access_denied'
  2052. );
  2053. return false;
  2054. }
  2055. if (!isset($_data['authsource'])){
  2056. $_SESSION['return'][] = array(
  2057. 'type' => 'danger',
  2058. 'log' => array(__FUNCTION__, $_action, $data_log),
  2059. 'msg' => array('required_data_missing', $setting)
  2060. );
  2061. return false;
  2062. }
  2063. $_data['authsource'] = strtolower($_data['authsource']);
  2064. if ($_data['authsource'] != "keycloak" && $_data['authsource'] != "generic-oidc"){
  2065. $_SESSION['return'][] = array(
  2066. 'type' => 'danger',
  2067. 'log' => array(__FUNCTION__, $_action, $data_log),
  2068. 'msg' => array('invalid_authsource', $setting)
  2069. );
  2070. return false;
  2071. }
  2072. $stmt = $pdo->prepare("SELECT * FROM `mailbox`
  2073. WHERE `authsource` != 'mailcow'
  2074. AND `authsource` IS NOT NULL
  2075. AND `authsource` != :authsource");
  2076. $stmt->execute(array(':authsource' => $_data['authsource']));
  2077. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2078. if ($rows) {
  2079. $_SESSION['return'][] = array(
  2080. 'type' => 'danger',
  2081. 'log' => array(__FUNCTION__, $_action, $data_log),
  2082. 'msg' => array('authsource_in_use', $setting)
  2083. );
  2084. return false;
  2085. }
  2086. if ($_data['authsource'] == "keycloak") {
  2087. $_data['server_url'] = (!empty($_data['server_url'])) ? rtrim($_data['server_url'], '/') : null;
  2088. $_data['mailpassword_flow'] = isset($_data['mailpassword_flow']) ? intval($_data['mailpassword_flow']) : 0;
  2089. $_data['periodic_sync'] = isset($_data['periodic_sync']) ? intval($_data['periodic_sync']) : 0;
  2090. $_data['import_users'] = isset($_data['import_users']) ? intval($_data['import_users']) : 0;
  2091. $_data['sync_interval'] = isset($_data['sync_interval']) ? intval($_data['sync_interval']) : 15;
  2092. $_data['sync_interval'] = $_data['sync_interval'] < 1 ? 1 : $_data['sync_interval'];
  2093. $required_settings = array('authsource', 'server_url', 'realm', 'client_id', 'client_secret', 'redirect_url', 'version', 'mailpassword_flow', 'periodic_sync', 'import_users', 'sync_interval');
  2094. } else if ($_data['authsource'] == "generic-oidc") {
  2095. $_data['authorize_url'] = (!empty($_data['authorize_url'])) ? $_data['authorize_url'] : null;
  2096. $_data['token_url'] = (!empty($_data['token_url'])) ? $_data['token_url'] : null;
  2097. $_data['userinfo_url'] = (!empty($_data['userinfo_url'])) ? $_data['userinfo_url'] : null;
  2098. $_data['client_scopes'] = (!empty($_data['client_scopes'])) ? $_data['client_scopes'] : "openid profile email";
  2099. $required_settings = array('authsource', 'authorize_url', 'token_url', 'client_id', 'client_secret', 'redirect_url', 'userinfo_url', 'client_scopes');
  2100. }
  2101. $pdo->beginTransaction();
  2102. $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES (:key, :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
  2103. // add connection settings
  2104. foreach($required_settings as $setting){
  2105. if (!isset($_data[$setting])){
  2106. $_SESSION['return'][] = array(
  2107. 'type' => 'danger',
  2108. 'log' => array(__FUNCTION__, $_action, $data_log),
  2109. 'msg' => array('required_data_missing', $setting)
  2110. );
  2111. $pdo->rollback();
  2112. return false;
  2113. }
  2114. $stmt->bindParam(':key', $setting);
  2115. $stmt->bindParam(':value', $_data[$setting]);
  2116. $stmt->execute();
  2117. }
  2118. $pdo->commit();
  2119. // add mappers
  2120. if ($_data['mappers'] && $_data['templates']){
  2121. $_data['mappers'] = (!is_array($_data['mappers'])) ? array($_data['mappers']) : $_data['mappers'];
  2122. $_data['templates'] = (!is_array($_data['templates'])) ? array($_data['templates']) : $_data['templates'];
  2123. $mappers = array_filter($_data['mappers']);
  2124. $templates = array_filter($_data['templates']);
  2125. if (count($mappers) == count($templates)){
  2126. $mappers = json_encode($mappers);
  2127. $templates = json_encode($templates);
  2128. $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES ('mappers', :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
  2129. $stmt->bindParam(':value', $mappers);
  2130. $stmt->execute();
  2131. $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES ('templates', :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
  2132. $stmt->bindParam(':value', $templates);
  2133. $stmt->execute();
  2134. }
  2135. }
  2136. // delete old access_token
  2137. $stmt = $pdo->query("INSERT INTO identity_provider (`key`, `value`) VALUES ('access_token', '') ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
  2138. $_SESSION['return'][] = array(
  2139. 'type' => 'success',
  2140. 'log' => array(__FUNCTION__, $_action, $data_log),
  2141. 'msg' => array('object_modified', '')
  2142. );
  2143. return true;
  2144. break;
  2145. case 'test':
  2146. if ($_SESSION['mailcow_cc_role'] != "admin") {
  2147. $_SESSION['return'][] = array(
  2148. 'type' => 'danger',
  2149. 'log' => array(__FUNCTION__, $_action, $_data),
  2150. 'msg' => 'access_denied'
  2151. );
  2152. return false;
  2153. }
  2154. if ($_data['authsource'] == 'keycloak') {
  2155. $url = "{$_data['server_url']}/realms/{$_data['realm']}/protocol/openid-connect/token";
  2156. } else {
  2157. $url = $_data['token_url'];
  2158. }
  2159. $req = http_build_query(array(
  2160. 'grant_type' => 'client_credentials',
  2161. 'client_id' => $_data['client_id'],
  2162. 'client_secret' => $_data['client_secret']
  2163. ));
  2164. $curl = curl_init();
  2165. curl_setopt($curl, CURLOPT_URL, $url);
  2166. curl_setopt($curl, CURLOPT_TIMEOUT, 7);
  2167. curl_setopt($curl, CURLOPT_POST, 1);
  2168. curl_setopt($curl, CURLOPT_POSTFIELDS, $req);
  2169. curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
  2170. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2171. $res = curl_exec($curl);
  2172. $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  2173. curl_close ($curl);
  2174. if ($code != 200) {
  2175. return false;
  2176. }
  2177. return true;
  2178. break;
  2179. case "delete":
  2180. if ($_SESSION['mailcow_cc_role'] != "admin") {
  2181. $_SESSION['return'][] = array(
  2182. 'type' => 'danger',
  2183. 'log' => array(__FUNCTION__, $_action, $_data),
  2184. 'msg' => 'access_denied'
  2185. );
  2186. return false;
  2187. }
  2188. $stmt = $pdo->query("SELECT * FROM `mailbox`
  2189. WHERE `authsource` != 'mailcow'
  2190. AND `authsource` IS NOT NULL");
  2191. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2192. if ($rows) {
  2193. $_SESSION['return'][] = array(
  2194. 'type' => 'danger',
  2195. 'log' => array(__FUNCTION__, $_action, $data_log),
  2196. 'msg' => array('authsource_in_use', $setting)
  2197. );
  2198. return false;
  2199. }
  2200. $stmt = $pdo->query("DELETE FROM identity_provider;");
  2201. $_SESSION['return'][] = array(
  2202. 'type' => 'success',
  2203. 'log' => array(__FUNCTION__, $_action, $data_log),
  2204. 'msg' => array('item_deleted', '')
  2205. );
  2206. return true;
  2207. break;
  2208. case "init":
  2209. $iam_settings = identity_provider('get');
  2210. $provider = null;
  2211. if ($iam_settings['authsource'] == 'keycloak'){
  2212. if ($iam_settings['server_url'] && $iam_settings['realm'] && $iam_settings['client_id'] &&
  2213. $iam_settings['client_secret'] && $iam_settings['redirect_url'] && $iam_settings['version']){
  2214. $provider = new Stevenmaguire\OAuth2\Client\Provider\Keycloak([
  2215. 'authServerUrl' => $iam_settings['server_url'],
  2216. 'realm' => $iam_settings['realm'],
  2217. 'clientId' => $iam_settings['client_id'],
  2218. 'clientSecret' => $iam_settings['client_secret'],
  2219. 'redirectUri' => $iam_settings['redirect_url'],
  2220. 'version' => $iam_settings['version'],
  2221. // 'encryptionAlgorithm' => 'RS256', // optional
  2222. // 'encryptionKeyPath' => '../key.pem' // optional
  2223. // 'encryptionKey' => 'contents_of_key_or_certificate' // optional
  2224. ]);
  2225. }
  2226. }
  2227. else if ($iam_settings['authsource'] == 'generic-oidc'){
  2228. if ($iam_settings['client_id'] && $iam_settings['client_secret'] && $iam_settings['redirect_url'] &&
  2229. $iam_settings['authorize_url'] && $iam_settings['token_url'] && $iam_settings['userinfo_url']){
  2230. $provider = new \League\OAuth2\Client\Provider\GenericProvider([
  2231. 'clientId' => $iam_settings['client_id'],
  2232. 'clientSecret' => $iam_settings['client_secret'],
  2233. 'redirectUri' => $iam_settings['redirect_url'],
  2234. 'urlAuthorize' => $iam_settings['authorize_url'],
  2235. 'urlAccessToken' => $iam_settings['token_url'],
  2236. 'urlResourceOwnerDetails' => $iam_settings['userinfo_url'],
  2237. 'scopes' => $iam_settings['client_scopes']
  2238. ]);
  2239. }
  2240. }
  2241. return $provider;
  2242. break;
  2243. case "verify-sso":
  2244. $provider = $_data['iam_provider'];
  2245. try {
  2246. $token = $provider->getAccessToken('authorization_code', ['code' => $_GET['code']]);
  2247. $_SESSION['iam_token'] = $token->getToken();
  2248. $_SESSION['iam_refresh_token'] = $token->getRefreshToken();
  2249. $info = $provider->getResourceOwner($token)->toArray();
  2250. } catch (Throwable $e) {
  2251. $_SESSION['return'][] = array(
  2252. 'type' => 'danger',
  2253. 'log' => array(__FUNCTION__),
  2254. 'msg' => array('login_failed', $e->getMessage())
  2255. );
  2256. return false;
  2257. }
  2258. // check if email address is given
  2259. if (empty($info['email'])) return false;
  2260. // token valid, get mailbox
  2261. $stmt = $pdo->prepare("SELECT * FROM `mailbox`
  2262. INNER JOIN domain on mailbox.domain = domain.domain
  2263. WHERE `kind` NOT REGEXP 'location|thing|group'
  2264. AND `mailbox`.`active`='1'
  2265. AND `domain`.`active`='1'
  2266. AND `username` = :user
  2267. AND (`authsource`='keycloak' OR `authsource`='generic-oidc')");
  2268. $stmt->execute(array(':user' => $info['email']));
  2269. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  2270. if ($row){
  2271. // success
  2272. $_SESSION['mailcow_cc_username'] = $info['email'];
  2273. $_SESSION['mailcow_cc_role'] = "user";
  2274. $_SESSION['return'][] = array(
  2275. 'type' => 'success',
  2276. 'log' => array(__FUNCTION__, $_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role']),
  2277. 'msg' => array('logged_in_as', $_SESSION['mailcow_cc_username'])
  2278. );
  2279. return true;
  2280. }
  2281. // get mapped template, if not set return false
  2282. // also return false if no mappers were defined
  2283. $provider = identity_provider('get');
  2284. $user_template = $info['mailcow_template'];
  2285. if (empty($provider['mappers']) || empty($user_template)){
  2286. clear_session();
  2287. $_SESSION['return'][] = array(
  2288. 'type' => 'danger',
  2289. 'log' => array(__FUNCTION__, $info['email']),
  2290. 'msg' => array('login_failed', 'empty attribute mapping or missing template attribute')
  2291. );
  2292. return false;
  2293. }
  2294. // check if matching attribute exist
  2295. $mapper_key = array_search($user_template, $provider['mappers']);
  2296. if ($mapper_key === false) {
  2297. clear_session();
  2298. $_SESSION['return'][] = array(
  2299. 'type' => 'danger',
  2300. 'log' => array(__FUNCTION__, $info['email']),
  2301. 'msg' => array('login_failed', 'specified template not found')
  2302. );
  2303. return false;
  2304. }
  2305. // create mailbox
  2306. $create_res = mailbox('add', 'mailbox_from_template', array(
  2307. 'domain' => explode('@', $info['email'])[1],
  2308. 'local_part' => explode('@', $info['email'])[0],
  2309. 'authsource' => identity_provider('get')['authsource'],
  2310. 'template' => $provider['templates'][$mapper_key]
  2311. ));
  2312. if (!$create_res){
  2313. clear_session();
  2314. $_SESSION['return'][] = array(
  2315. 'type' => 'danger',
  2316. 'log' => array(__FUNCTION__, $info['email']),
  2317. 'msg' => array('login_failed', 'mailbox creation failed')
  2318. );
  2319. return false;
  2320. }
  2321. $_SESSION['mailcow_cc_username'] = $info['email'];
  2322. $_SESSION['mailcow_cc_role'] = "user";
  2323. $_SESSION['return'][] = array(
  2324. 'type' => 'success',
  2325. 'log' => array(__FUNCTION__, $_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role']),
  2326. 'msg' => array('logged_in_as', $_SESSION['mailcow_cc_username'])
  2327. );
  2328. return true;
  2329. break;
  2330. case "refresh-token":
  2331. $provider = $_data['iam_provider'];
  2332. try {
  2333. $token = $provider->getAccessToken('refresh_token', ['refresh_token' => $_SESSION['iam_refresh_token']]);
  2334. $_SESSION['iam_token'] = $token->getToken();
  2335. $_SESSION['iam_refresh_token'] = $token->getRefreshToken();
  2336. $info = $provider->getResourceOwner($token)->toArray();
  2337. } catch (Throwable $e) {
  2338. $_SESSION['return'][] = array(
  2339. 'type' => 'danger',
  2340. 'log' => array(__FUNCTION__),
  2341. 'msg' => array('login_failed', $e->getMessage())
  2342. );
  2343. return false;
  2344. }
  2345. if (empty($info['email'])){
  2346. clear_session();
  2347. $_SESSION['return'][] = array(
  2348. 'type' => 'danger',
  2349. 'log' => array(__FUNCTION__, $_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role']),
  2350. 'msg' => 'refresh_login_failed'
  2351. );
  2352. return false;
  2353. }
  2354. $_SESSION['mailcow_cc_username'] = $info['email'];
  2355. $_SESSION['mailcow_cc_role'] = "user";
  2356. return true;
  2357. break;
  2358. case "get-redirect":
  2359. $provider = $_data['iam_provider'];
  2360. $authUrl = $provider->getAuthorizationUrl();
  2361. $_SESSION['oauth2state'] = $provider->getState();
  2362. return $authUrl;
  2363. break;
  2364. case "get-keycloak-admin-token":
  2365. // get access_token for service account of mailcow client
  2366. $iam_settings = identity_provider('get');
  2367. if ($iam_settings['authsource'] !== 'keycloak') return false;
  2368. if (isset($iam_settings['access_token'])) {
  2369. // check if access_token is valid
  2370. $url = "{$iam_settings['server_url']}/realms/{$iam_settings['realm']}/protocol/openid-connect/token/introspect";
  2371. $req = http_build_query(array(
  2372. 'token' => $iam_settings['access_token'],
  2373. 'client_id' => $iam_settings['client_id'],
  2374. 'client_secret' => $iam_settings['client_secret']
  2375. ));
  2376. $curl = curl_init();
  2377. curl_setopt($curl, CURLOPT_URL, $url);
  2378. curl_setopt($curl, CURLOPT_TIMEOUT, 7);
  2379. curl_setopt($curl, CURLOPT_POST, 1);
  2380. curl_setopt($curl, CURLOPT_POSTFIELDS, $req);
  2381. curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
  2382. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2383. curl_setopt($curl, CURLOPT_TIMEOUT, 5);
  2384. $res = json_decode(curl_exec($curl), true);
  2385. $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  2386. curl_close ($curl);
  2387. if ($code == 200 && $res['active'] == true) {
  2388. // token is valid
  2389. return $iam_settings['access_token'];
  2390. }
  2391. }
  2392. $url = "{$iam_settings['server_url']}/realms/{$iam_settings['realm']}/protocol/openid-connect/token";
  2393. $req = http_build_query(array(
  2394. 'grant_type' => 'client_credentials',
  2395. 'client_id' => $iam_settings['client_id'],
  2396. 'client_secret' => $iam_settings['client_secret']
  2397. ));
  2398. $curl = curl_init();
  2399. curl_setopt($curl, CURLOPT_URL, $url);
  2400. curl_setopt($curl, CURLOPT_TIMEOUT, 7);
  2401. curl_setopt($curl, CURLOPT_POST, 1);
  2402. curl_setopt($curl, CURLOPT_POSTFIELDS, $req);
  2403. curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
  2404. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2405. curl_setopt($curl, CURLOPT_TIMEOUT, 5);
  2406. $res = json_decode(curl_exec($curl), true);
  2407. $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  2408. curl_close ($curl);
  2409. if ($code != 200) {
  2410. return false;
  2411. }
  2412. $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES (:key, :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);");
  2413. $stmt->execute(array(
  2414. ':key' => 'access_token',
  2415. ':value' => $res['access_token']
  2416. ));
  2417. return $res['access_token'];
  2418. break;
  2419. }
  2420. }
  2421. function clear_session(){
  2422. session_regenerate_id(true);
  2423. session_unset();
  2424. session_destroy();
  2425. session_write_close();
  2426. }
  2427. function is_valid_ssl_cert($cert) {
  2428. if (empty($cert)) {
  2429. return false;
  2430. }
  2431. $cert_res = openssl_x509_read($cert);
  2432. if ($cert_res === false) {
  2433. return false;
  2434. }
  2435. openssl_x509_free($cert_res);
  2436. return true;
  2437. }
  2438. function has_ssl_client_auth() {
  2439. global $pdo;
  2440. $stmt = $pdo->query("SELECT domain FROM `domain`
  2441. WHERE `ssl_client_ca` IS NOT NULL
  2442. AND `ssl_client_issuer` IS NOT NULL");
  2443. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  2444. if (!$row){
  2445. return false;
  2446. }
  2447. return true;
  2448. }
  2449. function get_logs($application, $lines = false) {
  2450. if ($lines === false) {
  2451. $lines = $GLOBALS['LOG_LINES'] - 1;
  2452. }
  2453. elseif(is_numeric($lines) && $lines >= 1) {
  2454. $lines = abs(intval($lines) - 1);
  2455. }
  2456. else {
  2457. list ($from, $to) = explode('-', $lines);
  2458. $from = intval($from);
  2459. $to = intval($to);
  2460. if ($from < 1 || $to < $from) { return false; }
  2461. }
  2462. global $redis;
  2463. global $pdo;
  2464. if ($_SESSION['mailcow_cc_role'] != "admin") {
  2465. return false;
  2466. }
  2467. // SQL
  2468. if ($application == "mailcow-ui") {
  2469. if (isset($from) && isset($to)) {
  2470. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :from, :to");
  2471. $stmt->execute(array(
  2472. ':from' => $from - 1,
  2473. ':to' => $to
  2474. ));
  2475. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2476. }
  2477. else {
  2478. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :lines");
  2479. $stmt->execute(array(
  2480. ':lines' => $lines + 1,
  2481. ));
  2482. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2483. }
  2484. if (is_array($data)) {
  2485. return $data;
  2486. }
  2487. }
  2488. if ($application == "sasl") {
  2489. if (isset($from) && isset($to)) {
  2490. $stmt = $pdo->prepare("SELECT * FROM `sasl_log` ORDER BY `datetime` DESC LIMIT :from, :to");
  2491. $stmt->execute(array(
  2492. ':from' => $from - 1,
  2493. ':to' => $to
  2494. ));
  2495. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2496. }
  2497. else {
  2498. $stmt = $pdo->prepare("SELECT * FROM `sasl_log` ORDER BY `datetime` DESC LIMIT :lines");
  2499. $stmt->execute(array(
  2500. ':lines' => $lines + 1,
  2501. ));
  2502. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2503. }
  2504. if (is_array($data)) {
  2505. return $data;
  2506. }
  2507. }
  2508. // Redis
  2509. if ($application == "dovecot-mailcow") {
  2510. if (isset($from) && isset($to)) {
  2511. $data = $redis->lRange('DOVECOT_MAILLOG', $from - 1, $to - 1);
  2512. }
  2513. else {
  2514. $data = $redis->lRange('DOVECOT_MAILLOG', 0, $lines);
  2515. }
  2516. if ($data) {
  2517. foreach ($data as $json_line) {
  2518. $data_array[] = json_decode($json_line, true);
  2519. }
  2520. return $data_array;
  2521. }
  2522. }
  2523. if ($application == "cron-mailcow") {
  2524. if (isset($from) && isset($to)) {
  2525. $data = $redis->lRange('CRON_LOG', $from - 1, $to - 1);
  2526. }
  2527. else {
  2528. $data = $redis->lRange('CRON_LOG', 0, $lines);
  2529. }
  2530. if ($data) {
  2531. foreach ($data as $json_line) {
  2532. $data_array[] = json_decode($json_line, true);
  2533. }
  2534. return $data_array;
  2535. }
  2536. }
  2537. if ($application == "postfix-mailcow") {
  2538. if (isset($from) && isset($to)) {
  2539. $data = $redis->lRange('POSTFIX_MAILLOG', $from - 1, $to - 1);
  2540. }
  2541. else {
  2542. $data = $redis->lRange('POSTFIX_MAILLOG', 0, $lines);
  2543. }
  2544. if ($data) {
  2545. foreach ($data as $json_line) {
  2546. $data_array[] = json_decode($json_line, true);
  2547. }
  2548. return $data_array;
  2549. }
  2550. }
  2551. if ($application == "sogo-mailcow") {
  2552. if (isset($from) && isset($to)) {
  2553. $data = $redis->lRange('SOGO_LOG', $from - 1, $to - 1);
  2554. }
  2555. else {
  2556. $data = $redis->lRange('SOGO_LOG', 0, $lines);
  2557. }
  2558. if ($data) {
  2559. foreach ($data as $json_line) {
  2560. $data_array[] = json_decode($json_line, true);
  2561. }
  2562. return $data_array;
  2563. }
  2564. }
  2565. if ($application == "watchdog-mailcow") {
  2566. if (isset($from) && isset($to)) {
  2567. $data = $redis->lRange('WATCHDOG_LOG', $from - 1, $to - 1);
  2568. }
  2569. else {
  2570. $data = $redis->lRange('WATCHDOG_LOG', 0, $lines);
  2571. }
  2572. if ($data) {
  2573. foreach ($data as $json_line) {
  2574. $data_array[] = json_decode($json_line, true);
  2575. }
  2576. return $data_array;
  2577. }
  2578. }
  2579. if ($application == "acme-mailcow") {
  2580. if (isset($from) && isset($to)) {
  2581. $data = $redis->lRange('ACME_LOG', $from - 1, $to - 1);
  2582. }
  2583. else {
  2584. $data = $redis->lRange('ACME_LOG', 0, $lines);
  2585. }
  2586. if ($data) {
  2587. foreach ($data as $json_line) {
  2588. $data_array[] = json_decode($json_line, true);
  2589. }
  2590. return $data_array;
  2591. }
  2592. }
  2593. if ($application == "ratelimited") {
  2594. if (isset($from) && isset($to)) {
  2595. $data = $redis->lRange('RL_LOG', $from - 1, $to - 1);
  2596. }
  2597. else {
  2598. $data = $redis->lRange('RL_LOG', 0, $lines);
  2599. }
  2600. if ($data) {
  2601. foreach ($data as $json_line) {
  2602. $data_array[] = json_decode($json_line, true);
  2603. }
  2604. return $data_array;
  2605. }
  2606. }
  2607. if ($application == "api-mailcow") {
  2608. if (isset($from) && isset($to)) {
  2609. $data = $redis->lRange('API_LOG', $from - 1, $to - 1);
  2610. }
  2611. else {
  2612. $data = $redis->lRange('API_LOG', 0, $lines);
  2613. }
  2614. if ($data) {
  2615. foreach ($data as $json_line) {
  2616. $data_array[] = json_decode($json_line, true);
  2617. }
  2618. return $data_array;
  2619. }
  2620. }
  2621. if ($application == "netfilter-mailcow") {
  2622. if (isset($from) && isset($to)) {
  2623. $data = $redis->lRange('NETFILTER_LOG', $from - 1, $to - 1);
  2624. }
  2625. else {
  2626. $data = $redis->lRange('NETFILTER_LOG', 0, $lines);
  2627. }
  2628. if ($data) {
  2629. foreach ($data as $json_line) {
  2630. $data_array[] = json_decode($json_line, true);
  2631. }
  2632. return $data_array;
  2633. }
  2634. }
  2635. if ($application == "autodiscover-mailcow") {
  2636. if (isset($from) && isset($to)) {
  2637. $data = $redis->lRange('AUTODISCOVER_LOG', $from - 1, $to - 1);
  2638. }
  2639. else {
  2640. $data = $redis->lRange('AUTODISCOVER_LOG', 0, $lines);
  2641. }
  2642. if ($data) {
  2643. foreach ($data as $json_line) {
  2644. $data_array[] = json_decode($json_line, true);
  2645. }
  2646. return $data_array;
  2647. }
  2648. }
  2649. if ($application == "rspamd-history") {
  2650. $curl = curl_init();
  2651. curl_setopt($curl, CURLOPT_UNIX_SOCKET_PATH, '/var/lib/rspamd/rspamd.sock');
  2652. if (!is_numeric($lines)) {
  2653. list ($from, $to) = explode('-', $lines);
  2654. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?from=" . intval($from) . "&to=" . intval($to));
  2655. }
  2656. else {
  2657. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?to=" . intval($lines));
  2658. }
  2659. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2660. $history = curl_exec($curl);
  2661. if (!curl_errno($curl)) {
  2662. $data_array = json_decode($history, true);
  2663. curl_close($curl);
  2664. return $data_array['rows'];
  2665. }
  2666. curl_close($curl);
  2667. return false;
  2668. }
  2669. if ($application == "rspamd-stats") {
  2670. $curl = curl_init();
  2671. curl_setopt($curl, CURLOPT_UNIX_SOCKET_PATH, '/var/lib/rspamd/rspamd.sock');
  2672. curl_setopt($curl, CURLOPT_URL,"http://rspamd/stat");
  2673. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2674. $stats = curl_exec($curl);
  2675. if (!curl_errno($curl)) {
  2676. $data_array = json_decode($stats, true);
  2677. curl_close($curl);
  2678. return $data_array;
  2679. }
  2680. curl_close($curl);
  2681. return false;
  2682. }
  2683. return false;
  2684. }
  2685. function getGUID() {
  2686. if (function_exists('com_create_guid')) {
  2687. return com_create_guid();
  2688. }
  2689. mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
  2690. $charid = strtoupper(md5(uniqid(rand(), true)));
  2691. $hyphen = chr(45);// "-"
  2692. return substr($charid, 0, 8).$hyphen
  2693. .substr($charid, 8, 4).$hyphen
  2694. .substr($charid,12, 4).$hyphen
  2695. .substr($charid,16, 4).$hyphen
  2696. .substr($charid,20,12);
  2697. }
  2698. function solr_status() {
  2699. $curl = curl_init();
  2700. $endpoint = 'http://solr:8983/solr/admin/cores';
  2701. $params = array(
  2702. 'action' => 'STATUS',
  2703. 'core' => 'dovecot-fts',
  2704. 'indexInfo' => 'true'
  2705. );
  2706. $url = $endpoint . '?' . http_build_query($params);
  2707. curl_setopt($curl, CURLOPT_URL, $url);
  2708. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  2709. curl_setopt($curl, CURLOPT_POST, 0);
  2710. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  2711. $response_core = curl_exec($curl);
  2712. if ($response_core === false) {
  2713. $err = curl_error($curl);
  2714. curl_close($curl);
  2715. return false;
  2716. }
  2717. else {
  2718. curl_close($curl);
  2719. $curl = curl_init();
  2720. $status_core = json_decode($response_core, true);
  2721. $url = 'http://solr:8983/solr/admin/info/system';
  2722. curl_setopt($curl, CURLOPT_URL, $url);
  2723. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  2724. curl_setopt($curl, CURLOPT_POST, 0);
  2725. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  2726. $response_sysinfo = curl_exec($curl);
  2727. if ($response_sysinfo === false) {
  2728. $err = curl_error($curl);
  2729. curl_close($curl);
  2730. return false;
  2731. }
  2732. else {
  2733. curl_close($curl);
  2734. $status_sysinfo = json_decode($response_sysinfo, true);
  2735. $status = array_merge($status_core, $status_sysinfo);
  2736. return (!empty($status['status']['dovecot-fts']) && !empty($status['jvm']['memory'])) ? $status : false;
  2737. }
  2738. return (!empty($status['status']['dovecot-fts'])) ? $status['status']['dovecot-fts'] : false;
  2739. }
  2740. return false;
  2741. }
  2742. function cleanupJS($ignore = '', $folder = '/tmp/*.js') {
  2743. $now = time();
  2744. foreach (glob($folder) as $filename) {
  2745. if(strpos($filename, $ignore) !== false) {
  2746. continue;
  2747. }
  2748. if (is_file($filename)) {
  2749. if ($now - filemtime($filename) >= 60 * 60) {
  2750. unlink($filename);
  2751. }
  2752. }
  2753. }
  2754. }
  2755. function cleanupCSS($ignore = '', $folder = '/tmp/*.css') {
  2756. $now = time();
  2757. foreach (glob($folder) as $filename) {
  2758. if(strpos($filename, $ignore) !== false) {
  2759. continue;
  2760. }
  2761. if (is_file($filename)) {
  2762. if ($now - filemtime($filename) >= 60 * 60) {
  2763. unlink($filename);
  2764. }
  2765. }
  2766. }
  2767. }
  2768. ?>