* $sql = "SELECT * FROM foo WHERE x = '" . escape_string('fish') . "'";
*
*
* @param int|string $string_or_int parameters to escape
* @return string cleaned data, suitable for use within an SQL statement.
*/
function escape_string($string_or_int)
{
$link = db_connect();
$string_or_int = (string)$string_or_int;
$quoted = $link->quote($string_or_int);
return trim($quoted, "'");
}
/**
* safeget
* Action: get value from $_GET[$param], or $default if $_GET[$param] is not set
* Call: $param = safeget('param') # replaces $param = $_GET['param']
* - or -
* $param = safeget('param', 'default')
*
* @param string $param parameter name.
* @param string $default (optional) - default value if key is not set.
* @return string - can only return a string
*/
function safeget($param, $default = "")
{
$retval = $default;
if (isset($_GET[$param]) && is_string($_GET[$param])) {
$retval = $_GET[$param];
}
return $retval;
}
/**
* safepost - similar to safeget() but for $_POST
* @param string $param parameter name
* @param string $default (optional) default value (defaults to "")
* @return string - value in $_POST[$param] or $default - we do not support array like value(s) etc
* @see safeget()
*/
function safepost($param, $default = "")
{
$retval = $default;
if (isset($_POST[$param]) && is_string($_POST[$param])) {
$retval = $_POST[$param];
}
return $retval;
}
/**
* safecookie
* @param string $param parameter name
* @param string $default (optional) default value (defaults to "")
* @return string value from $_COOKIE[$param] or $default - we do not support array like value(s) etc
* @see safeget()
*/
function safecookie(string $param, $default = ""): string
{
$retval = $default;
if (isset($_COOKIE[$param])) {
$retval = $_COOKIE[$param];
}
return $retval;
}
/**
* safesession
* @param string $param
* @param string $default (optional)
* @return string value from $_SESSION[$param] or $default
* @see safeget()
*/
function safesession($param, $default = "")
{
$retval = $default;
if (isset($_SESSION[$param]) && is_string($_SESSION[$param])) {
$retval = $_SESSION[$param];
}
return $retval;
}
/**
* Action: Get all the properties of a domain.
* @param string $domain
* @return array
*/
function get_domain_properties($domain)
{
$handler = new DomainHandler();
if (!$handler->init($domain)) {
throw new Exception("Error: " . join("\n", $handler->errormsg));
}
if (!$handler->view()) {
throw new Exception("Error: " . join("\n", $handler->errormsg));
}
$result = $handler->result();
return $result;
}
/**
* create_page_browser
* Action: Get page browser for a long list of mailboxes, aliases etc.
*
* @param string $idxfield - database field name to use as title e.g. alias.address
* @param string $querypart - core part of the query (starting at "FROM") e.g. FROM alias WHERE address like ...
* @return array
*/
function create_page_browser($idxfield, $querypart, $sql_params = [])
{
global $CONF;
$page_size = (int)$CONF['page_size'];
$label_len = 2;
$pagebrowser = array();
$count_results = 0;
if ($page_size < 2) { # will break the page browser
throw new Exception('$CONF[\'page_size\'] must be 2 or more!');
}
# get number of rows
$query = "SELECT count(*) as counter FROM (SELECT $idxfield $querypart) AS tmp";
$result = db_query_one($query, $sql_params);
if ($result && isset($result['counter'])) {
$count_results = $result['counter'] - 1; # we start counting at 0, not 1
}
if ($count_results < $page_size) {
return array(); # only one page - no pagebrowser required
}
# init row counter
$initcount = "SET @r=-1";
if (db_pgsql()) {
$initcount = "CREATE TEMPORARY SEQUENCE rowcount MINVALUE 0";
}
if (!db_sqlite()) {
db_execute($initcount);
}
# get labels for relevant rows (first and last of each page)
$page_size_zerobase = $page_size - 1;
$query = "
SELECT * FROM (
SELECT $idxfield AS label, @r := @r + 1 AS 'r' $querypart
) idx WHERE MOD(idx.r, $page_size) IN (0,$page_size_zerobase) OR idx.r = $count_results
";
if (db_pgsql()) {
$query = "
SELECT * FROM (
SELECT $idxfield AS label, nextval('rowcount') AS r $querypart
) idx WHERE MOD(idx.r, $page_size) IN (0,$page_size_zerobase) OR idx.r = $count_results
";
}
if (db_sqlite()) {
$end = $idxfield;
if (strpos($idxfield, '.') !== false) {
$bits = explode('.', $idxfield);
$end = $bits[1];
}
$query = "
WITH idx AS (SELECT * $querypart)
SELECT $end AS label, (SELECT (COUNT(*) - 1) FROM idx t1 WHERE t1.$end <= t2.$end ) AS r
FROM idx t2
WHERE (r % $page_size) IN (0,$page_size_zerobase) OR r = $count_results";
}
# PostgreSQL:
# http://www.postgresql.org/docs/8.1/static/sql-createsequence.html
# http://www.postgresonline.com/journal/archives/79-Simulating-Row-Number-in-PostgreSQL-Pre-8.4.html
# http://www.pg-forum.de/sql/1518-nummerierung-der-abfrageergebnisse.html
# CREATE TEMPORARY SEQUENCE foo MINVALUE 0 MAXVALUE $page_size_zerobase CYCLE
# afterwards: DROP SEQUENCE foo
$result = db_query_all($query, $sql_params);
for ($k = 0; $k < count($result); $k += 2) {
if (isset($result[$k + 1])) {
$label = substr($result[$k]['label'], 0, $label_len) . '-' . substr($result[$k + 1]['label'], 0, $label_len);
} else {
$label = substr($result[$k]['label'], 0, $label_len);
}
$pagebrowser[] = $label;
}
if (db_pgsql()) {
db_execute("DROP SEQUENCE rowcount");
}
return $pagebrowser;
}
/**
* Recalculates the quota e.g. from MBs to bytes (divide, /), using config quota_multiplier
* @param int $quota
* @return float
*/
function divide_quota($quota)
{
if ($quota == -1) {
return $quota;
}
$value = round($quota / (int)Config::read_string('quota_multiplier'), 2);
return $value;
}
/**
* Checks if the admin is the owner of the domain (or global-admin)
*/
function check_owner(string $username, string $domain): bool
{
$table_domain_admins = table_by_key('domain_admins');
$result = db_query_all(
"SELECT 1 FROM $table_domain_admins WHERE username= ? AND (domain = ? OR domain = 'ALL') AND active = ?",
array($username, $domain, true)
);
if (sizeof($result) == 1 || sizeof($result) == 2) { # "ALL" + specific domain permissions is possible
# TODO: if superadmin, check if given domain exists in the database
return true;
} else {
if (sizeof($result) > 2) { # more than 2 results means something really strange happened...
flash_error("Permission check returned multiple results. Please go to 'edit admin' for your username and press the save "
. "button once to fix the database. If this doesn't help, open a bugreport.");
}
return false;
}
}
/**
* List domains for an admin user.
* @param string $username
* @return array of domain names.
*/
function list_domains_for_admin(string $username): array
{
$table_domain = table_by_key('domain');
$table_domain_admins = table_by_key('domain_admins');
$condition = [];
$pvalues = [];
$query = "SELECT $table_domain.domain FROM $table_domain ";
$condition[] = "$table_domain.domain != 'ALL'";
$result = db_query_one("SELECT username FROM $table_domain_admins WHERE username = :username AND domain = 'ALL'", ['username' => $username]);
if (empty($result)) { # not a superadmin
$pvalues['username'] = $username;
$pvalues['active'] = true;
$pvalues['backupmx'] = false;
$query .= " LEFT JOIN $table_domain_admins ON $table_domain.domain=$table_domain_admins.domain ";
$condition[] = "$table_domain_admins.username = :username ";
$condition[] = "$table_domain.active = :active "; # TODO: does it really make sense to exclude inactive...
$condition[] = "$table_domain.backupmx = :backupmx "; # TODO: ... and backupmx domains for non-superadmins?
}
$query .= " WHERE " . join(' AND ', $condition);
$query .= " ORDER BY $table_domain.domain";
$result = db_query_all($query, $pvalues);
return array_column($result, 'domain');
}
/**
* List all available domains.
*
* @return array
*/
function list_domains()
{
$list = array();
$table_domain = table_by_key('domain');
$result = db_query_all("SELECT domain FROM $table_domain WHERE domain!='ALL' ORDER BY domain");
$i = 0;
foreach ($result as $row) {
$list[$i] = $row['domain'];
$i++;
}
return $list;
}
//
// list_admins
// Action: Lists all the admins
// Call: list_admins ()
//
// was admin_list_admins
//
function list_admins()
{
$handler = new AdminHandler();
$handler->getList('');
return $handler->result();
}
//
// encode_header
// Action: Encode a string according to RFC 1522 for use in headers if it contains 8-bit characters.
// Call: encode_header (string header, string charset)
//
function encode_header($string, $default_charset = "utf-8")
{
if (strtolower($default_charset) == 'iso-8859-1') {
$string = str_replace("\240", ' ', $string);
}
$j = strlen($string);
$max_l = 75 - strlen($default_charset) - 7;
$aRet = array();
$ret = '';
$iEncStart = $enc_init = false;
$cur_l = $iOffset = 0;
for ($i = 0; $i < $j; ++$i) {
switch ($string[$i]) {
case '=':
case '<':
case '>':
case ',':
case '?':
case '_':
if ($iEncStart === false) {
$iEncStart = $i;
}
$cur_l += 3;
if ($cur_l > ($max_l - 2)) {
$aRet[] = substr($string, $iOffset, $iEncStart - $iOffset);
$aRet[] = "=?$default_charset?Q?$ret?=";
$iOffset = $i;
$cur_l = 0;
$ret = '';
$iEncStart = false;
} else {
$ret .= sprintf("=%02X", ord($string[$i]));
}
break;
case '(':
case ')':
if ($iEncStart !== false) {
$aRet[] = substr($string, $iOffset, $iEncStart - $iOffset);
$aRet[] = "=?$default_charset?Q?$ret?=";
$iOffset = $i;
$cur_l = 0;
$ret = '';
$iEncStart = false;
}
break;
case ' ':
if ($iEncStart !== false) {
$cur_l++;
if ($cur_l > $max_l) {
$aRet[] = substr($string, $iOffset, $iEncStart - $iOffset);
$aRet[] = "=?$default_charset?Q?$ret?=";
$iOffset = $i;
$cur_l = 0;
$ret = '';
$iEncStart = false;
} else {
$ret .= '_';
}
}
break;
default:
$k = ord($string[$i]);
if ($k > 126) {
if ($iEncStart === false) {
// do not start encoding in the middle of a string, also take the rest of the word.
$sLeadString = substr($string, 0, $i);
$aLeadString = explode(' ', $sLeadString);
$sToBeEncoded = array_pop($aLeadString);
$iEncStart = $i - strlen($sToBeEncoded);
$ret .= $sToBeEncoded;
$cur_l += strlen($sToBeEncoded);
}
$cur_l += 3;
// first we add the encoded string that reached it's max size
if ($cur_l > ($max_l - 2)) {
$aRet[] = substr($string, $iOffset, $iEncStart - $iOffset);
$aRet[] = "=?$default_charset?Q?$ret?= ";
$cur_l = 3;
$ret = '';
$iOffset = $i;
$iEncStart = $i;
}
$enc_init = true;
$ret .= sprintf("=%02X", $k);
} else {
if ($iEncStart !== false) {
$cur_l++;
if ($cur_l > $max_l) {
$aRet[] = substr($string, $iOffset, $iEncStart - $iOffset);
$aRet[] = "=?$default_charset?Q?$ret?=";
$iEncStart = false;
$iOffset = $i;
$cur_l = 0;
$ret = '';
} else {
$ret .= $string[$i];
}
}
}
break;
# end switch
}
}
if ($enc_init) {
if ($iEncStart !== false) {
$aRet[] = substr($string, $iOffset, $iEncStart - $iOffset);
$aRet[] = "=?$default_charset?Q?$ret?=";
} else {
$aRet[] = substr($string, $iOffset);
}
$string = implode('', $aRet);
}
return $string;
}
/**
* Generate a random password of $length characters.
* @param int $length (optional, default: 12)
* @return string
*/
function generate_password(int $length = 12): string
{
// define possible characters
$possible = "2345678923456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ"; # skip 0 and 1 to avoid confusion with O and l
// add random characters to $password until $length is reached
$password = "";
// note this allows for repeated characters (better entropy)
for ($i = 0; $i < $length; $i++) {
$random = random_int(0, strlen($possible) - 1);
$password .= substr($possible, $random, 1);
}
return $password;
}
/**
* Check if a password is strong enough based on the conditions in $CONF['password_validation']
* @param string $password
* @return array of error messages, or empty array if the password is ok
*/
function validate_password(string $password): array
{
$result = array();
$config = Config::getInstance()->getAll();
$val_conf = $config['password_validation'] ?? [];
$minlen = $config['min_password_length'] ?? null;
if (is_numeric($minlen) && $minlen > 0) {
$minlen = (int)$minlen; # used up to 2.3.x -
$val_conf['/.{' . $minlen . '}/'] = "password_too_short $minlen";
}
foreach ($val_conf as $regex => $message) {
if (is_callable($message)) {
$ret = $message($password);
if (!empty($ret)) {
$result[] = $ret;
}
continue;
}
if (!preg_match($regex, $password)) {
$msgparts = preg_split("/ /", $message, 2);
if (count($msgparts) == 1) {
$result[] = Config::lang($msgparts[0]);
} else {
$result[] = sprintf(Config::lang($msgparts[0]), $msgparts[1]);
}
}
}
return $result;
}
/**
* Create/Validate courier authlib style crypt'ed passwords. (md5, md5raw, crypt, sha1)
*
* @param string $pw
* @param string $pw_db (optional)
* @return string crypted password - contains {xxx} prefix to identify mechanism.
*/
function _pacrypt_authlib($pw, $pw_db)
{
global $CONF;
$flavor = $CONF['authlib_default_flavor'];
$salt = substr(create_salt(), 0, 2); # courier-authlib supports only two-character salts
if (preg_match('/^{.*}/', $pw_db)) {
// we have a flavor in the db -> use it instead of default flavor
$result = preg_split('/[{}]/', $pw_db, 3); # split at { and/or }
$flavor = $result[1];
$salt = substr($result[2], 0, 2);
}
if (stripos($flavor, 'md5raw') === 0) {
$password = '{' . $flavor . '}' . md5($pw);
} elseif (stripos($flavor, 'md5') === 0) {
$password = '{' . $flavor . '}' . base64_encode(md5($pw, true));
} elseif (stripos($flavor, 'crypt') === 0) {
$password = '{' . $flavor . '}' . crypt($pw, $salt);
} elseif (stripos($flavor, 'SHA') === 0) {
$password = '{' . $flavor . '}' . base64_encode(sha1($pw, true));
} else {
throw new Exception("authlib_default_flavor '" . $flavor . "' unknown. Valid flavors are 'md5raw', 'md5', 'SHA' and 'crypt'");
}
return $password;
}
/**
* Uses the doveadm pw command, crypted passwords have a {...} prefix to identify type.
*
* @param string $pw - plain text password
* @param string $pw_db - encrypted password, or '' for generation.
* @param string $username
* @return string crypted password
*/
function _pacrypt_dovecot($pw, $pw_db = '', $username = '')
{
global $CONF;
$split_method = preg_split('/:/', $CONF['encrypt']);
$method = strtoupper($split_method[1]);
# If $pw_db starts with {method}, change $method accordingly
if (!empty($pw_db) && preg_match('/^\{([A-Z0-9.-]+)\}.+/', $pw_db, $method_matches)) {
$method = $method_matches[1];
}
if (!preg_match("/^[A-Z0-9.-]+$/", $method)) {
throw new Exception("invalid dovecot encryption method");
}
$doveadm_options = '';
if (strtolower($method) == 'digest-md5') {
if (empty($username)) {
throw new Exception("\$CONF['encrypt'] = 'dovecot:digest-md5' require username.");
}
$doveadm_options = ' -u ' . escapeshellarg($username);
}
$dovecotpw = "doveadm pw";
if (!empty($CONF['dovecotpw'])) {
$dovecotpw = $CONF['dovecotpw'];
}
# Use proc_open call to avoid safe_mode problems and to prevent showing plain password in process table
$spec = array(
0 => array("pipe", "r"), // stdin
1 => array("pipe", "w"), // stdout
2 => array("pipe", "w"), // stderr
);
$nonsaltedtypes = "SHA|SHA1|SHA256|SHA512|CLEAR|CLEARTEXT|PLAIN|PLAIN-TRUNC|CRAM-MD5|HMAC-MD5|PLAIN-MD4|PLAIN-MD5|LDAP-MD5|LANMAN|NTLM|RPA";
$salted = !preg_match("/^($nonsaltedtypes)(\.B64|\.BASE64|\.HEX)?$/", strtoupper($method));
$dovepasstest = '';
if ($salted && (!empty($pw_db))) {
# only use -t for salted passwords to be backward compatible with dovecot < 2.1
$dovepasstest = " -t " . escapeshellarg($pw_db);
}
$pipes = [];
$pipe = proc_open("$dovecotpw -s {$method}{$dovepasstest}{$doveadm_options}", $spec, $pipes);
if (!$pipe) {
throw new Exception("can't proc_open $dovecotpw");
}
// use dovecot's stdin, it uses getpass() twice (except when using -t)
// Write pass in pipe stdin
if (empty($dovepasstest)) {
fwrite($pipes[0], $pw . "\n", 1 + strlen($pw));
usleep(1000);
}
fwrite($pipes[0], $pw . "\n", 1 + strlen($pw));
fclose($pipes[0]);
$stderr_output = stream_get_contents($pipes[2]);
// Read hash from pipe stdout
$password = fread($pipes[1], 200);
if (!empty($stderr_output) || empty($password)) {
error_log("Failed to read password from $dovecotpw ... stderr: $stderr_output, password: $password ");
throw new Exception("$dovecotpw failed, see error log for details");
}
if (empty($dovepasstest)) {
if (!preg_match('/^\{' . $method . '\}/', $password)) {
error_log("dovecotpw password encryption failed (method: $method) . stderr: $stderr_output");
throw new Exception("can't encrypt password with dovecotpw, see error log for details");
}
} else {
if (!preg_match('(verified)', $password)) {
$password = "Thepasswordcannotbeverified";
} else {
$password = rtrim(str_replace('(verified)', '', $password));
}
}
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($pipe);
if ((!empty($pw_db)) && (substr($pw_db, 0, 1) != '{')) {
# for backward compability with "old" dovecot passwords that don't have the {method} prefix
$password = str_replace('{' . $method . '}', '', $password);
}
return rtrim($password);
}
/**
* Supports DES, MD5, BLOWFISH, SHA256, SHA512 methods.
*
* Via config we support an optional prefix (e.g. if you need hashes to start with {SHA256-CRYPT} and optional rounds (hardness) setting.
*
* @param string $pw
* @param string $pw_db (can be empty if setting a new password)
* @return string crypt'ed password; if it matches $pw_db then $pw is the original password.
*/
function _pacrypt_php_crypt($pw, $pw_db)
{
$configEncrypt = Config::read_string('encrypt');
// use PHPs crypt(), which uses the system's crypt()
// same algorithms as used in /etc/shadow
// you can have mixed hash types in the database for authentication, changed passwords get specified hash type
// the algorithm for a new hash is chosen by feeding a salt with correct magic to crypt()
// set $CONF['encrypt'] to 'php_crypt' to use the default SHA512 crypt method
// set $CONF['encrypt'] to 'php_crypt:METHOD' to use another method; methods supported: DES, MD5, BLOWFISH, SHA256, SHA512
// set $CONF['encrypt'] to 'php_crypt:METHOD:difficulty' where difficulty is between 1000-999999999
// set $CONF['encrypt'] to 'php_crypt:METHOD:difficulty:PREFIX' to prefix the hash with the {PREFIX} etc.
// tested on linux
$prefix = '';
if (strlen($pw_db) > 0) {
// existing pw provided. send entire password hash as salt for crypt() to figure out
$salt = $pw_db;
// if there was a prefix in the password, use this (override anything given in the config).
if (preg_match('/^\{([-A-Z0-9]+)\}(.+)$/', $pw_db, $method_matches)) {
$salt = $method_matches[2];
$prefix = "{" . $method_matches[1] . "}";
}
} else {
$salt_method = 'SHA512'; // hopefully a reasonable default (better than MD5)
$hash_difficulty = '';
// no pw provided. create new password hash
if (strpos($configEncrypt, ':') !== false) {
// use specified hash method
$spec = explode(':', $configEncrypt);
$salt_method = $spec[1];
if (isset($spec[2])) {
$hash_difficulty = $spec[2];
}
if (isset($spec[3])) {
$prefix = $spec[3]; // hopefully something like {SHA256-CRYPT}
}
}
// create appropriate salt for selected hash method
$salt = _php_crypt_generate_crypt_salt($salt_method, $hash_difficulty);
}
$password = crypt($pw, $salt);
return "{$prefix}{$password}";
}
/**
* @param string $hash_type must be one of: MD5, DES, BLOWFISH, SHA256 or SHA512 (default)
* @param int hash difficulty
* @return string
*/
function _php_crypt_generate_crypt_salt($hash_type = 'SHA512', $hash_difficulty = null)
{
// generate a salt (with magic matching chosen hash algorithm) for the PHP crypt() function
// most commonly used alphabet
$alphabet = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
switch ($hash_type) {
case 'DES':
$alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$length = 2;
$salt = _php_crypt_random_string($alphabet, $length);
return $salt;
case 'MD5':
$length = 12;
$algorithm = '1';
$salt = _php_crypt_random_string($alphabet, $length);
return sprintf('$%s$%s', $algorithm, $salt);
case 'BLOWFISH':
$length = 22;
if (empty($hash_difficulty)) {
$cost = 10;
} else {
$cost = (int)$hash_difficulty;
if ($cost < 4 || $cost > 31) {
throw new Exception('invalid encrypt difficulty setting "' . $hash_difficulty . '" for ' . $hash_type . ', the valid range is 4-31');
}
}
$algorithm = '2y'; // bcrypt (2a is a legacy variant with a unicode problem).
$salt = _php_crypt_random_string($alphabet, $length);
$hash = sprintf('$%s$%02d$%s', $algorithm, $cost, $salt);
if (!is_string($hash)) {
throw new \InvalidArgumentException('Failed to generate crypt salt for ' . $hash_type);
}
return $hash;
case 'SHA256':
$length = 16;
$algorithm = '5';
if (empty($hash_difficulty)) {
$rounds = '';
} else {
$rounds = (int)$hash_difficulty;
if ($rounds < 1000 || $rounds > 999999999) {
throw new Exception('invalid encrypt difficulty setting "' . $hash_difficulty . '" for ' . $hash_type . ', the valid range is 1000-999999999');
}
}
$salt = _php_crypt_random_string($alphabet, $length);
if (!empty($rounds)) {
$rounds = sprintf('rounds=%d$', $rounds);
}
return sprintf('$%s$%s%s', $algorithm, $rounds, $salt);
case 'SHA512':
$length = 16;
$algorithm = '6';
if (empty($hash_difficulty)) {
$rounds = '';
} else {
$rounds = (int)$hash_difficulty;
if ($rounds < 1000 || $rounds > 999999999) {
throw new Exception('invalid encrypt difficulty setting "' . $hash_difficulty . '" for ' . $hash_type . ', the valid range is 1000-999999999');
}
}
$salt = _php_crypt_random_string($alphabet, $length);
if (!empty($rounds)) {
$rounds = sprintf('rounds=%d$', $rounds);
}
return sprintf('$%s$%s%s', $algorithm, $rounds, $salt);
default:
throw new Exception("unknown hash type: '$hash_type'");
}
}
/**
* Generates a random string of specified $length from $characters.
* @param string $characters
* @param int $length
* @return string of given $length
*/
function _php_crypt_random_string(string $characters, int $length): string
{
$string = '';
for ($p = 0; $p < $length; $p++) {
$string .= $characters[random_int(0, strlen($characters) - 1)];
}
return $string;
}
/**
* Encrypt a password, using the apparopriate hashing mechanism as defined in
* config.inc.php ($CONF['encrypt']).
*
* When wanting to compare one pw to another, it's necessary to provide the salt used - hence
* the second parameter ($pw_db), which is the existing hash from the DB.
*
* @param string $pw
* @param string $pw_db optional encrypted password
* @param string $username optional, but required when $CONF['encrypt'] = 'dovecot:digest-md5'
* @return string encrypted password - if this matches $pw_db then the original password is $pw.
*/
function pacrypt($pw, $pw_db = "", $username = '')
{
global $CONF;
$mechanism = strtoupper($CONF['encrypt'] ?? 'CRYPT');
if (preg_match('/^PHP_CRYPT:(DES|MD5|BLOWFISH|SHA256|SHA512):?/', $mechanism, $matches)) {
return _pacrypt_php_crypt($pw, $pw_db);
}
$crypts = ['PHP_CRYPT', 'MD5CRYPT'];
if (in_array($mechanism, $crypts)) {
$mechanism = 'CRYPT';
}
if ($mechanism == 'AUTHLIB') {
return _pacrypt_authlib($pw, $pw_db);
}
if (!empty($pw_db) && preg_match('/^{([0-9a-z-\.]+)}/i', $pw_db, $matches)) {
$method_in_hash = $matches[1];
if ('DOVECOT:' . strtoupper($method_in_hash) == $mechanism || 'COURIER:' . strtoupper($method_in_hash) == $mechanism) {
// don't try and be clever.
} elseif ($mechanism != $method_in_hash) {
error_log("PostfixAdmin: configured to use $mechanism, but asked to crypt password using {$method_in_hash}; are you migrating algorithm/mechanism or is something wrong?");
$mechanism = $method_in_hash;
}
}
if ($mechanism == 'MD5RAW') {
$mechanism = 'COURIER:MD5RAW';
}
if (!empty($pw_db) && preg_match('/^\$[0-9]\$/i', $pw_db, $matches)) {
$method_in_hash = $matches[0];
switch ($method_in_hash) {
case '$1$':
case '$6$':
$mechanism = 'SYSTEM';
}
}
if ($mechanism == 'SHA512.B64') {
// postfixadmin incorrectly uses this as a SHA512-CRYPT.B64
$mechanism = 'SHA512-CRYPT.B64';
// backwards compatability - see https://github.com/postfixadmin/postfixadmin/issues/58 and https://github.com/postfixadmin/postfixadmin/issues/647
// if we are configured for SHA512.B64, support existing passwords in MD5-CRYPT format.
if ($pw_db && strncmp($pw_db, '{MD5-CRYPT}', 11) == 0) {
$mechanism = 'MD5-CRYPT';
}
}
if (preg_match('/^DOVECOT:(.*)$/i', $mechanism, $matches)) {
return _pacrypt_dovecot($pw, $pw_db, $username);
}
if (empty($pw_db)) {
$pw_db = null;
}
$hasher = new \PostfixAdmin\PasswordHashing\Crypt($mechanism);
return $hasher->crypt($pw, $pw_db);
}
/**
* @return string - should be random, 8 chars long
*/
function create_salt()
{
return bin2hex(random_bytes(4));
}
/*
* remove item $item from array $array
*/
function remove_from_array($array, $item)
{
# array_diff might be faster, but doesn't provide an easy way to know if the value was found or not
# return array_diff($array, array($item));
$ret = array_search($item, $array);
if ($ret === false) {
$found = 0;
} else {
$found = 1;
unset($array[$ret]);
}
return array($found, $array);
}
function enable_socket_crypto($fh)
{
stream_set_blocking($fh, true);
stream_socket_enable_crypto($fh, true, STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT);
stream_set_blocking($fh, true);
}
/**
* smtp_mail
* Action: Send email
* Call: smtp_mail (string to, string from, string subject, string body]) - or -
* Call: smtp_mail (string to, string from, string data) - DEPRECATED
* @param string $to
* @param string $from
* @param string $subject_or_data (if called with 4 parameters) or full mail body (if called with 3 parameters)
* @param ?string $body (optional, but recommended) - mail body (if null, assume $subject_or_data is the entire mail body with headers etc)
* @return bool - true on success, otherwise false
*/
function smtp_mail(string $to, string $from, string $subject_or_data, ?string $body = null): bool
{
global $CONF;
$server = $CONF['smtp_server'];
$port = (int)$CONF['smtp_port'];
$timeout = 30;
$helo = !empty($CONF['smtp_client'])
? $CONF['smtp_client']
: php_uname('n');
$username = $CONF['smtp_username'] ?? '';
$password = $CONF['admin_smtp_password'] ?? '';
$type = $CONF['smtp_type'] ?? 'starttls';
// Building of SMTP payload
if ($body === null) {
// RAW MOD for Broadcast (broadcast-message.php)
$maildata = $subject_or_data;
} else {
// NORMAL MOD (sendmail.php)
$maildata =
"To: $to\r\n" .
"From: $from\r\n" .
"Subject: " . encode_header($subject_or_data) . "\r\n" .
"MIME-Version: 1.0\r\n" .
"Date: " . date('r') . "\r\n" .
"Content-Type: text/plain; charset=utf-8\r\n" .
"Content-Transfer-Encoding: 8bit\r\n\r\n" .
$body;
}
// Connection
if ($type === 'tls' || $type === 'ssl') {
$socket = stream_socket_client(
"ssl://{$server}:{$port}",
$errno,
$errstr,
$timeout,
STREAM_CLIENT_CONNECT
);
} else {
$socket = fsockopen($server, $port, $errno, $errstr, $timeout);
}
if (!$socket) {
error_log("smtp_mail(): socket error $errno - $errstr");
return false;
}
smtp_expect($socket, 220);
fputs($socket, "EHLO $helo\r\n");
smtp_expect($socket, 250);
if ($type === 'starttls') {
fputs($socket, "STARTTLS\r\n");
smtp_expect($socket, 220);
stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
fputs($socket, "EHLO $helo\r\n");
smtp_expect($socket, 250);
}
// AUTH
fputs($socket, "AUTH LOGIN\r\n");
smtp_expect($socket, 334);
fputs($socket, base64_encode($username) . "\r\n");
smtp_expect($socket, 334);
fputs($socket, base64_encode($password) . "\r\n");
smtp_expect($socket, 235);
// SMTP FLOW
fputs($socket, "MAIL FROM:<$from>\r\n");
smtp_expect($socket, 250);
fputs($socket, "RCPT TO:<$to>\r\n");
smtp_expect($socket, 250);
fputs($socket, "DATA\r\n");
smtp_expect($socket, 354);
fputs($socket, $maildata . "\r\n.\r\n");
smtp_expect($socket, 250);
fputs($socket, "QUIT\r\n");
fclose($socket);
return true;
}
//end
// auxiliary function
function smtp_expect($socket, $code)
{
$response = '';
while ($line = fgets($socket, 515)) {
$response .= $line;
if (preg_match('/^\d{3}\s/', $line)) {
break;
}
}
if ((int)substr($response, 0, 3) !== $code) {
error_log("smtp_mail(): especting $code, received: " . trim($response));
return false;
}
return true;
}
//end commit
/**
* smtp_get_admin_email
* Action: Get configured email address or current user if nothing configured
* Call: smtp_get_admin_email
* @return string - username/mail address
*/
function smtp_get_admin_email(bool $fallback_to_loggedin_user = true)
{
$admin_email = Config::read_string('admin_email');
if (!empty($admin_email)) {
return $admin_email;
}
if ($fallback_to_loggedin_user) {
/* may do a redirect to login */
return authentication_get_username();
}
error_log(__FILE__ . " WARNING : Please set a PostfixAdmin admin_email setting in your config.local.php file");
return "PasswordReset FATAL Error:
Invalid \$CONF['database_type']
Only: 'pgsql', 'mysql' or 'sqlite' supported.
Please fix your config.inc.php!
FATAL Error:
Invalid \$CONF['database_type']! Please fix your config.inc.php!