[Web] Do not allow to add domain admin for non existing domain

[Web] oAuth2 implementation (wip)
This commit is contained in:
andryyy 2019-10-02 19:00:36 +02:00
parent 9f66b83a34
commit 1c35002505
No known key found for this signature in database
GPG Key ID: 8EC34FF2794E25EF
20 changed files with 478 additions and 119 deletions

View File

@ -177,6 +177,30 @@ if (!isset($_SESSION['gal']) && $license_cache = $redis->Get('LICENSE_STATUS_CAC
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">OAuth2 Apps</div>
<div class="panel-body">
<p><?=$lang['admin']['oauth2_info'];?></p>
<div class="table-responsive">
<table class="table table-striped" id="oauth2clientstable"></table>
</div>
<div class="mass-actions-admin">
<div class="btn-group">
<a class="btn btn-sm btn-default" id="toggle_multi_select_all" data-id="oauth2_clients" href="#"><span class="glyphicon glyphicon-check" aria-hidden="true"></span> <?=$lang['mailbox']['toggle_all'];?></a>
<a class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" href="#"><?=$lang['mailbox']['quick_actions'];?> <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a data-action="delete_selected" data-id="oauth2_clients" data-api-url='delete/oauth2-client' href="#"><?=$lang['mailbox']['remove'];?></a></li>
<li role="separator" class="divider"></li>
<li><a data-action="edit_selected" data-id="oauth2_clients" data-api-url='edit/oauth2-client' data-api-attr='{"revoke_tokens":"1"}' href="#"><?=$lang['admin']['oauth2_revoke_tokens'];?></a></li>
<li role="separator" class="divider"></li>
<li><a data-action="edit_selected" data-id="oauth2_clients" data-api-url='edit/oauth2-client' data-api-attr='{"renew_secret":"1"}' href="#"><?=$lang['admin']['oauth2_renew_secret'];?></a></li>
</ul>
<a class="btn btn-sm btn-success" data-id="add_oauth2_client" data-toggle="modal" data-target="#addOAuth2ClientModal" href="#"><span class="glyphicon glyphicon-plus"></span> Add OAuth2 client</a>
</div>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Rspamd UI</h3>
@ -950,10 +974,8 @@ if (!isset($_SESSION['gal']) && $license_cache = $redis->Get('LICENSE_STATUS_CAC
<button class="btn btn-sm btn-default" type="button" id="add_app_link_row"><?=$lang['admin']['add_row'];?></button>
</div></p>
</form>
<legend data-target="#ui_texts" style="cursor:pointer" class="arrow-toggle" unselectable="on" data-toggle="collapse">
<span style="font-size:12px" class="arrow rotate glyphicon glyphicon-menu-down"></span> <?=$lang['admin']['ui_texts'];?>
</legend>
<div id="ui_texts" class="collapse" >
<legend data-target="#ui_texts" style="padding-top:20px" unselectable="on"><?=$lang['admin']['ui_texts'];?></legend>
<div id="ui_texts">
<?php
$ui_texts = customize('get', 'ui_texts');
?>
@ -975,8 +997,8 @@ if (!isset($_SESSION['gal']) && $license_cache = $redis->Get('LICENSE_STATUS_CAC
<textarea class="form-control" id="help_text" name="help_text" rows="7"><?=$ui_texts['help_text'];?></textarea>
</div>
<div class="form-group">
<label for="ui_impress"><?=$lang['admin']['ui_impress'];?>:</label>
<textarea class="form-control" id="ui_impress" name="ui_impress" rows="7"><?=$ui_texts['ui_impress'];?></textarea>
<label for="ui_footer"><?=$lang['admin']['ui_footer'];?>:</label>
<textarea class="form-control" id="ui_footer" name="ui_footer" rows="7"><?=$ui_texts['ui_footer'];?></textarea>
</div>
<button class="btn btn-default" data-action="edit_selected" data-item="ui" data-id="uitexts" data-api-url='edit/ui_texts' data-api-attr='{}' href="#"><span class="glyphicon glyphicon-check"></span> <?=$lang['admin']['save'];?></button>
</form>

View File

@ -432,6 +432,53 @@ if (isset($_SESSION['mailcow_cc_role'])) {
<?php
}
}
elseif (isset($_GET['oauth2client']) &&
is_numeric($_GET["oauth2client"]) &&
!empty($_GET["oauth2client"])) {
$oauth2client = $_GET["oauth2client"];
$result = oauth2('details', 'client', $oauth2client);
if (!empty($result)) {
?>
<h4>OAuth2</h4>
<form data-id="oauth2client" class="form-horizontal" role="form" method="post">
<div class="form-group">
<label class="control-label col-sm-2" for="client_id"><?=$lang['edit']['client_id'];?></label>
<div class="col-sm-10">
<input type="text" class="form-control" name="client_id" id="client_id" value="<?=htmlspecialchars($result['client_id']);?>" disabled>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="client_secret"><?=$lang['edit']['client_secret'];?></label>
<div class="col-sm-10">
<input type="text" class="form-control" name="client_secret" id="client_secret" value="<?=htmlspecialchars($result['client_secret']);?>" disabled>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="scope"><?=$lang['edit']['scope'];?></label>
<div class="col-sm-10">
<input type="text" class="form-control" name="scope" id="scope" value="<?=htmlspecialchars($result['scope']);?>" disabled>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="redirect_uri"><?=$lang['edit']['redirect_uri'];?></label>
<div class="col-sm-10">
<input type="text" class="form-control" name="redirect_uri" id="redirect_uri" value="<?=htmlspecialchars($result['redirect_uri']);?>">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button class="btn btn-default" data-action="edit_selected" data-id="oauth2client" data-item="<?=$oauth2client;?>" data-api-url='edit/oauth2-client' data-api-attr='{}' href="#"><?=$lang['admin']['save'];?></button>
</div>
</div>
</form>
<?php
}
else {
?>
<div class="alert alert-info" role="alert"><?=$lang['info']['no_action'];?></div>
<?php
}
}
elseif (isset($_GET['aliasdomain']) &&
is_valid_domain_name(html_entity_decode(rawurldecode($_GET["aliasdomain"]))) &&
!empty($_GET["aliasdomain"])) {

View File

@ -175,11 +175,11 @@ $(document).ready(function() {
});
</script>
<?php
if (!empty($UI_TEXTS['ui_impress'])):
if (!empty($UI_TEXTS['ui_footer'])):
?>
<div class="container" style="margin-bottom:20px;color:#959595;">
<hr>
<?=$UI_TEXTS['ui_impress'];?>
<?=$UI_TEXTS['ui_footer'];?>
</div>
<?php
endif;

View File

@ -112,13 +112,13 @@ function customize($_action, $_item, $_data = null) {
$main_name = $_data['main_name'];
$apps_name = $_data['apps_name'];
$help_text = $_data['help_text'];
$ui_impress = $_data['ui_impress'];
$ui_footer = $_data['ui_footer'];
try {
$redis->set('TITLE_NAME', htmlspecialchars($title_name));
$redis->set('MAIN_NAME', htmlspecialchars($main_name));
$redis->set('APPS_NAME', htmlspecialchars($apps_name));
$redis->set('HELP_TEXT', $help_text);
$redis->set('UI_IMPRESS', $ui_impress);
$redis->set('UI_FOOTER', $ui_footer);
}
catch (RedisException $e) {
$_SESSION['return'][] = array(
@ -203,7 +203,11 @@ function customize($_action, $_item, $_data = null) {
$data['main_name'] = ($main_name = $redis->get('MAIN_NAME')) ? $main_name : 'mailcow UI';
$data['apps_name'] = ($apps_name = $redis->get('APPS_NAME')) ? $apps_name : 'mailcow Apps';
$data['help_text'] = ($help_text = $redis->get('HELP_TEXT')) ? $help_text : false;
$data['ui_impress'] = ($ui_impress = $redis->get('UI_IMPRESS')) ? $ui_impress : false;
if (!empty($redis->get('UI_IMPRESS'))) {
$redis->set('UI_FOOTER', $redis->get('UI_IMPRESS'));
$redis->del('UI_IMPRESS');
}
$data['ui_footer'] = ($ui_footer = $redis->get('UI_FOOTER')) ? $ui_footer : false;
return $data;
}
catch (RedisException $e) {

View File

@ -83,15 +83,17 @@ function domain_admin($_action, $_data = null) {
return false;
}
$password_hashed = hash_password($password);
$valid_domains = 0;
foreach ($domains as $domain) {
if (!is_valid_domain_name($domain)) {
if (!is_valid_domain_name($domain) || mailbox('get', 'domain_details', $domain) === false) {
$_SESSION['return'][] = array(
'type' => 'danger',
'log' => array(__FUNCTION__, $_action, $_data_log),
'msg' => 'domain_invalid'
'msg' => array('domain_invalid', htmlspecialchars($domain))
);
return false;
continue;
}
$valid_domains++;
$stmt = $pdo->prepare("INSERT INTO `domain_admins` (`username`, `domain`, `created`, `active`)
VALUES (:username, :domain, :created, :active)");
$stmt->execute(array(
@ -101,13 +103,15 @@ function domain_admin($_action, $_data = null) {
':active' => $active
));
}
$stmt = $pdo->prepare("INSERT INTO `admin` (`username`, `password`, `superadmin`, `active`)
VALUES (:username, :password_hashed, '0', :active)");
$stmt->execute(array(
':username' => $username,
':password_hashed' => $password_hashed,
':active' => $active
));
if ($valid_domains != 0) {
$stmt = $pdo->prepare("INSERT INTO `admin` (`username`, `password`, `superadmin`, `active`)
VALUES (:username, :password_hashed, '0', :active)");
$stmt->execute(array(
':username' => $username,
':password_hashed' => $password_hashed,
':active' => $active
));
}
}
else {
$_SESSION['return'][] = array(
@ -117,15 +121,17 @@ function domain_admin($_action, $_data = null) {
);
return false;
}
$stmt = $pdo->prepare("INSERT INTO `da_acl` (`username`) VALUES (:username)");
$stmt->execute(array(
':username' => $username
));
$_SESSION['return'][] = array(
'type' => 'success',
'log' => array(__FUNCTION__, $_action, $_data_log),
'msg' => array('domain_admin_added', htmlspecialchars($username))
);
if ($valid_domains != 0) {
$stmt = $pdo->prepare("INSERT INTO `da_acl` (`username`) VALUES (:username)");
$stmt->execute(array(
':username' => $username
));
$_SESSION['return'][] = array(
'type' => 'success',
'log' => array(__FUNCTION__, $_action, $_data_log),
'msg' => array('domain_admin_added', htmlspecialchars($username))
);
}
break;
case 'edit':
if ($_SESSION['mailcow_cc_role'] != "admin" && $_SESSION['mailcow_cc_role'] != "domainadmin") {
@ -165,7 +171,7 @@ function domain_admin($_action, $_data = null) {
$password2 = $_data['password2'];
if (!empty($domains)) {
foreach ($domains as $domain) {
if (!is_valid_domain_name($domain)) {
if (!is_valid_domain_name($domain) || mailbox('get', 'domain_details', $domain) === false) {
$_SESSION['return'][] = array(
'type' => 'danger',
'log' => array(__FUNCTION__, $_action, $_data_log),

View File

@ -3806,6 +3806,18 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) {
$stmt->execute(array(
':username' => $username
));
$stmt = $pdo->prepare("DELETE FROM `oauth_access_tokens` WHERE `user_id` = :username");
$stmt->execute(array(
':username' => $username
));
$stmt = $pdo->prepare("DELETE FROM `oauth_refresh_tokens` WHERE `user_id` = :username");
$stmt->execute(array(
':username' => $username
));
$stmt = $pdo->prepare("DELETE FROM `oauth_authorization_codes` WHERE `user_id` = :username");
$stmt->execute(array(
':username' => $username
));
$stmt = $pdo->prepare("SELECT `address`, `goto` FROM `alias`
WHERE `goto` REGEXP :username");
$stmt->execute(array(':username' => '(^|,)'.$username.'($|,)'));

View File

@ -4,9 +4,10 @@ function oauth2($_action, $_type, $_data = null) {
global $redis;
global $lang;
if ($_SESSION['mailcow_cc_role'] != "admin") {
$_SESSION['return'] = array(
$_SESSION['return'][] = array(
'type' => 'danger',
'msg' => sprintf($lang['danger']['access_denied'])
'log' => array(__FUNCTION__, $_action, $_type, $_data),
'msg' => 'access_denied'
);
return false;
}
@ -14,30 +15,26 @@ function oauth2($_action, $_type, $_data = null) {
case 'add':
switch ($_type) {
case 'client':
$client_id = $_data['client_id'];
$client_secret = $_data['client_secret'];
$client_id = bin2hex(random_bytes(6));
$client_secret = bin2hex(random_bytes(12));
$redirect_uri = $_data['redirect_uri'];
$scope = 'profile';
// For future use
// $grant_type = isset($_data['grant_type']) ? $_data['grant_type'] : 'authorization_code';
// $scope = isset($_data['scope']) ? $_data['scope'] : 'profile';
if ($grant_type != "authorization_code" && $grant_type != "password") {
$_SESSION['return'] = array(
'type' => 'danger',
'msg' => sprintf($lang['danger']['access_denied'])
);
return false;
}
// For future use
// if ($grant_type != "authorization_code" && $grant_type != "password") {
// $_SESSION['return'][] = array(
// 'type' => 'danger',
// 'log' => array(__FUNCTION__, $_action, $_type, $_data),
// 'msg' => 'access_denied'
// );
// return false;
// }
if ($scope != "profile") {
$_SESSION['return'] = array(
$_SESSION['return'][] = array(
'type' => 'danger',
'msg' => sprintf($lang['danger']['access_denied'])
);
return false;
}
if (!ctype_alnum($client_id) || !ctype_alnum($client_secret)) {
$_SESSION['return'] = array(
'type' => 'danger',
'msg' => sprintf($lang['danger']['access_denied'])
'log' => array(__FUNCTION__, $_action, $_type, $_data),
'msg' => 'Invalid scope'
);
return false;
}
@ -46,21 +43,24 @@ function oauth2($_action, $_type, $_data = null) {
$stmt->execute(array(':client_id' => $client_id));
$num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
if ($num_results != 0) {
$_SESSION['return'] = array(
$_SESSION['return'][] = array(
'type' => 'danger',
'log' => array(__FUNCTION__, $_action, $_type, $_data),
'msg' => 'Client ID exists'
);
return false;
}
$stmt = $pdo->prepare("INSERT INTO `oauth_clients` (`client_id`, `client_secret` ,`redirect_uri`)
VALUES (:client_id, :client_secret, :redirect_uri)");
$stmt = $pdo->prepare("INSERT INTO `oauth_clients` (`client_id`, `client_secret`, `redirect_uri`, `scope`)
VALUES (:client_id, :client_secret, :redirect_uri, :scope)");
$stmt->execute(array(
':client_id' => $client_id,
':client_secret' => $client_secret,
':redirect_uri' => $redirect_uri
':redirect_uri' => $redirect_uri,
':scope' => $scope
));
$_SESSION['return'] = array(
$_SESSION['return'][] = array(
'type' => 'success',
'log' => array(__FUNCTION__, $_action, $_type, $_data),
'msg' => 'Added client access'
);
break;
@ -73,47 +73,73 @@ function oauth2($_action, $_type, $_data = null) {
foreach ($ids as $id) {
$is_now = oauth2('details', 'client', $id);
if (!empty($is_now)) {
$client_id = (!empty($_data['client_id'])) ? $_data['client_id'] : $is_now['client_id'];
$client_secret = (!empty($_data['client_secret'])) ? $_data['client_secret'] : $is_now['client_secret'];
$redirect_uri = (!empty($_data['redirect_uri'])) ? $_data['redirect_uri'] : $is_now['redirect_uri'];
$redirect_uri = (!empty($_data['redirect_uri'])) ? $_data['redirect_uri'] : $is_now['redirect_uri'];
}
else {
$_SESSION['return'] = array(
$_SESSION['return'][] = array(
'type' => 'danger',
'msg' => sprintf($lang['danger']['access_denied'])
'log' => array(__FUNCTION__, $_action, $_type, $_data),
'msg' => 'access_denied'
);
return false;
}
if (!ctype_alnum($client_id) || !ctype_alnum($client_secret)) {
$_SESSION['return'] = array(
'type' => 'danger',
'msg' => 'Client ID and secret must be alphanumeric'
if (isset($_data['revoke_tokens'])) {
$stmt = $pdo->prepare("DELETE FROM `oauth_access_tokens`
WHERE `client_id` IN (
SELECT `client_id` FROM `oauth_clients` WHERE `id` = :id
)");
$stmt->execute(array(
':id' => $id
));
$stmt = $pdo->prepare("DELETE FROM `oauth_refresh_tokens`
WHERE `client_id` IN (
SELECT `client_id` FROM `oauth_clients` WHERE `id` = :id
)");
$stmt->execute(array(
':id' => $id
));
$_SESSION['return'][] = array(
'type' => 'success',
'log' => array(__FUNCTION__, $_action, $_type, $_data),
'msg' => array('object_modified', htmlspecialchars($id))
);
return false;
continue;
}
if (isset($_data['renew_secret'])) {
$client_secret = bin2hex(random_bytes(12));
$stmt = $pdo->prepare("UPDATE `oauth_clients` SET `client_secret` = :client_secret WHERE `id` = :id");
$stmt->execute(array(
':client_secret' => $client_secret,
':id' => $id
));
$_SESSION['return'][] = array(
'type' => 'success',
'log' => array(__FUNCTION__, $_action, $_type, $_data),
'msg' => array('object_modified', htmlspecialchars($id))
);
continue;
}
if (empty($redirect_uri)) {
$_SESSION['return'] = array(
$_SESSION['return'][] = array(
'type' => 'danger',
'log' => array(__FUNCTION__, $_action, $_type, $_data),
'msg' => 'Redirect/Callback URL cannot be empty'
);
return false;
continue;
}
$stmt = $pdo->prepare("UPDATE `oauth_clients` SET
`client_id` = :client_id,
`client_secret` = :client_secret,
`redirect_uri` = :redirect_uri
WHERE `id` = :id");
$stmt->execute(array(
':id' => $id,
':client_id' => $client_id,
':client_secret' => $client_secret,
':redirect_uri' => $redirect_uri
));
$_SESSION['return'][] = array(
'type' => 'success',
'log' => array(__FUNCTION__, $_action, $_type, $_data),
'msg' => array('object_modified', htmlspecialchars($id))
);
}
$_SESSION['return'] = array(
'type' => 'success',
'msg' => sprintf($lang['success']['object_modified'], htmlspecialchars(implode(', ', $ids)))
);
break;
}
break;
@ -123,39 +149,45 @@ function oauth2($_action, $_type, $_data = null) {
(array)$ids = $_data['id'];
foreach ($ids as $id) {
if (!is_numeric($id)) {
$_SESSION['return'] = array(
$_SESSION['return'][] = array(
'type' => 'danger',
'msg' => sprintf($lang['danger']['access_denied'])
'log' => array(__FUNCTION__, $_action, $_type, $_data),
'msg' => 'access_denied'
);
return false;
continue;
}
$stmt = $pdo->prepare("DELETE FROM `oauth_clients` WHERE `id` = :id");
$stmt = $pdo->prepare("DELETE FROM `oauth_clients`
WHERE `id` = :id");
$stmt->execute(array(
':id' => $id
));
}
$_SESSION['return'] = array(
$_SESSION['return'][] = array(
'type' => 'success',
'msg' => sprintf($lang['success']['items_deleted'], implode(', ', $ids))
'log' => array(__FUNCTION__, $_action, $_type, $_data),
'msg' => array('items_deleted', htmlspecialchars($id))
);
break;
case 'access_token':
(array)$access_tokens = $_data['access_token'];
foreach ($access_tokens as $access_token) {
if (!ctype_alnum($access_token)) {
$_SESSION['return'] = array(
$_SESSION['return'][] = array(
'type' => 'danger',
'msg' => sprintf($lang['danger']['access_denied'])
'log' => array(__FUNCTION__, $_action, $_type, $_data),
'msg' => 'access_denied'
);
return false;
}
$stmt = $pdo->prepare("DELETE FROM `oauth_access_tokens` WHERE `access_token` = :access_token");
$stmt = $pdo->prepare("DELETE FROM `oauth_access_tokens`
WHERE `access_token` = :access_token");
$stmt->execute(array(
':access_token' => $access_token
));
}
$_SESSION['return'] = array(
$_SESSION['return'][] = array(
'type' => 'success',
'log' => array(__FUNCTION__, $_action, $_type, $_data),
'msg' => sprintf($lang['success']['items_deleted'], implode(', ', $access_tokens))
);
break;
@ -163,9 +195,10 @@ function oauth2($_action, $_type, $_data = null) {
(array)$refresh_tokens = $_data['refresh_token'];
foreach ($refresh_tokens as $refresh_token) {
if (!ctype_alnum($refresh_token)) {
$_SESSION['return'] = array(
$_SESSION['return'][] = array(
'type' => 'danger',
'msg' => sprintf($lang['danger']['access_denied'])
'log' => array(__FUNCTION__, $_action, $_type, $_data),
'msg' => 'access_denied'
);
return false;
}
@ -174,8 +207,9 @@ function oauth2($_action, $_type, $_data = null) {
':refresh_token' => $refresh_token
));
}
$_SESSION['return'] = array(
$_SESSION['return'][] = array(
'type' => 'success',
'log' => array(__FUNCTION__, $_action, $_type, $_data),
'msg' => sprintf($lang['success']['items_deleted'], implode(', ', $refresh_tokens))
);
break;

View File

@ -3,7 +3,7 @@ function init_db_schema() {
try {
global $pdo;
$db_version = "27092019_1040";
$db_version = "29092019_1040";
$stmt = $pdo->query("SHOW TABLES LIKE 'versions'");
$num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
@ -1055,6 +1055,17 @@ BEGIN
DELETE FROM spamalias WHERE validity < UNIX_TIMESTAMP();
END;
//
DELIMITER ;';
$events[] = 'DROP EVENT IF EXISTS clean_oauth2;
DELIMITER //
CREATE EVENT clean_oauth2
ON SCHEDULE EVERY 1 DAY DO
BEGIN
DELETE FROM oauth_refresh_tokens WHERE expires < NOW();
DELETE FROM oauth_access_tokens WHERE expires < NOW();
DELETE FROM oauth_authorization_codes WHERE expires < NOW();
END;
//
DELIMITER ;';
foreach ($events as $event) {
$pdo->exec($event);

View File

@ -105,13 +105,15 @@ class mailcowPdo extends OAuth2\Storage\Pdo {
$oauth2_scope_storage = new OAuth2\Storage\Memory(array('default_scope' => 'profile', 'supported_scopes' => array('profile')));
$oauth2_storage = new mailcowPdo(array('dsn' => $dsn, 'username' => $database_user, 'password' => $database_pass));
$oauth2_server = new OAuth2\Server($oauth2_storage, array(
'always_issue_new_refresh_token' => true,
'refresh_token_lifetime' => 2678400,
'refresh_token_lifetime' => $REFRESH_TOKEN_LIFETIME,
'access_lifetime' => $ACCESS_TOKEN_LIFETIME,
));
$oauth2_server->setScopeUtil(new OAuth2\Scope($oauth2_scope_storage));
$oauth2_server->addGrantType(new OAuth2\GrantType\AuthorizationCode($oauth2_storage));
$oauth2_server->addGrantType(new OAuth2\GrantType\UserCredentials($oauth2_storage));
$oauth2_server->addGrantType(new OAuth2\GrantType\RefreshToken($oauth2_storage));
$oauth2_server->addGrantType(new OAuth2\GrantType\RefreshToken($oauth2_storage, array(
'always_issue_new_refresh_token' => true
)));
function exception_handler($e) {
if ($e instanceof PDOException) {

View File

@ -129,6 +129,10 @@ $DOCKER_TIMEOUT = 60;
// Anonymize IPs logged via UI
$ANONYMIZE_IPS = true;
// OAuth2 settings
$REFRESH_TOKEN_LIFETIME = 2678400;
$ACCESS_TOKEN_LIFETIME = 86400;
// MAILBOX_DEFAULT_ATTRIBUTES define default attributes for new mailboxes
// These settings will not change existing mailboxes

View File

@ -1,7 +1,13 @@
<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/inc/prerequisites.inc.php';
if (isset($_SESSION['mailcow_cc_role']) && $_SESSION['mailcow_cc_role'] == 'admin') {
if (isset($_SESSION['mailcow_cc_role']) && isset($_SESSION['oauth2_request'])) {
$oauth2_request = $_SESSION['oauth2_request'];
unset($_SESSION['oauth2_request']);
header('Location: ' . $oauth2_request);
exit();
}
elseif (isset($_SESSION['mailcow_cc_role']) && $_SESSION['mailcow_cc_role'] == 'admin') {
header('Location: /admin');
exit();
}

View File

@ -78,6 +78,33 @@ jQuery(function($){
"toggleSelector": "table tbody span.footable-toggle"
});
}
function draw_oauth2_clients() {
ft_oauth2clientstable = FooTable.init('#oauth2clientstable', {
"columns": [
{"name":"chkbox","title":"","style":{"maxWidth":"40px","width":"40px"},"filterable": false,"sortable": false,"type":"html"},
{"name":"id","type":"text","title":"ID","style":{"width":"50px"}},
{"name":"client_id","type":"text","title":lang.oauth2_client_id,"style":{"width":"200px"}},
{"name":"client_secret","title":lang.oauth2_client_secret,"breakpoints":"xs sm md","style":{"width":"200px"}},
{"name":"redirect_uri","title":lang.oauth2_redirect_uri, "type": "text"},
{"name":"action","filterable": false,"sortable": false,"style":{"text-align":"right","maxWidth":"180px","width":"180px"},"type":"html","title":lang.action,"breakpoints":"xs sm"}
],
"rows": $.ajax({
dataType: 'json',
url: '/api/v1/get/oauth2-client/all',
jsonp: false,
error: function () {
console.log('Cannot draw oauth2 clients table');
},
success: function (data) {
return process_table_data(data, 'oauth2clientstable');
}
}),
"empty": lang.empty,
"paging": {"enabled": true,"limit": 5,"size": log_pagination_size},
"sorting": {"enabled": true},
"toggleSelector": "table tbody span.footable-toggle"
});
}
function draw_admins() {
ft_admins = FooTable.init('#adminstable', {
"columns": [
@ -267,6 +294,16 @@ jQuery(function($){
}
item.chkbox = '<input type="checkbox" data-id="fwdhosts" name="multi_select" value="' + item.host + '" />';
});
} else if (table == 'oauth2clientstable') {
$.each(data, function (i, item) {
item.action = '<div class="btn-group">' +
'<a href="/edit.php?oauth2client=' + encodeURI(item.id) + '" class="btn btn-xs btn-default"><span class="glyphicon glyphicon-pencil"></span> ' + lang.edit + '</a>' +
'<a href="#" id="delete_selected" data-id="single-oauth2-client" data-api-url="delete/oauth2-client" data-item="' + encodeURI(item.id) + '" class="btn btn-xs btn-danger"><span class="glyphicon glyphicon-trash"></span> ' + lang.remove + '</a>' +
'</div>';
item.scope = "profile";
item.grant_types = 'refresh_token password authorization_code';
item.chkbox = '<input type="checkbox" data-id="oauth2_clients" name="multi_select" value="' + item.id + '" />';
});
} else if (table == 'domainadminstable') {
$.each(data, function (i, item) {
item.selected_domains = escapeHtml(item.selected_domains);
@ -299,6 +336,7 @@ jQuery(function($){
draw_admins();
draw_fwd_hosts();
draw_relayhosts();
draw_oauth2_clients();
draw_transport_maps();
draw_queue();
// Relayhost

View File

@ -142,6 +142,9 @@ if (isset($_SESSION['mailcow_cc_role']) || isset($_SESSION['pending_mailcow_cc_u
case "mailbox":
process_add_return(mailbox('add', 'mailbox', $attr));
break;
case "oauth2-client":
process_add_return(oauth2('add', 'client', $attr));
break;
case "domain":
process_add_return(mailbox('add', 'domain', $attr));
break;
@ -1056,6 +1059,9 @@ if (isset($_SESSION['mailcow_cc_role']) || isset($_SESSION['pending_mailcow_cc_u
case "alias":
process_delete_return(mailbox('delete', 'alias', array('id' => $items)));
break;
case "oauth2-client":
process_delete_return(oauth2('delete', 'client', array('id' => $items)));
break;
case "relayhost":
process_delete_return(relayhost('delete', array('id' => $items)));
break;

View File

@ -711,7 +711,39 @@ $lang['admin']['help_text'] = "Hilfstext unter Login-Maske (HTML zulässig)";
$lang['admin']['title_name'] = '"mailcow UI" Webseiten Titel';
$lang['admin']['main_name'] = '"mailcow UI" Name';
$lang['admin']['apps_name'] = '"mailcow Apps" Name';
$lang['admin']['ui_impress'] = 'Impressum, Footer (HTML zulässig)';
$lang['admin']['ui_footer'] = 'Footer (HTML zulässig)';
$lang['admin']['oauth2_info'] = 'Die OAuth2 Implementierung untersützt den Grant Type "Authorization Code" mit Refresh Tokens.<br>
Der Server wird automatisch einen neuen Refresh Token ausstellen, sobald ein vorheriger Token gegen einen Access Token eingetauscht wurde.<br><br>
Der Standard Scope lautet <i>profile</i>. Nur Mailbox-Benutzer können sich gegen OAuth2 authentifizieren. Wird kein Scope angegeben, verwendet das System per Standard <i>profile</i>.<br>
Der <i>state</i> Parameter wird im Zuge des Autorisierungsprozesses benötigt.<br><br>
Die Pfade für die OAuth2 API lauten wie folgt: <br>
<ul>
<li>Authorization Endpoint: <code>/oauth/authorize</code></li>
<li>Token Endpoint: <code>/oauth/token</code></li>
<li>Resource Page: <code>/oauth/profile</code></li>
</ul>
Die Regenerierung des Client Secrets wird vorhandene Authorization Codes nicht invalidieren, dennoch wird der Renew des Access Tokens durch einen Refresh Token nicht mehr gelingen.<br><br>
Das Entfernen aller Client Tokens verursacht die umgehende Terminierung aller aktiven OAuth2 Sessions. Clients müssen sich erneut gegen die OAuth2 Anwendung authentifizieren.';
$lang['admin']['oauth2_client_id'] = "Client ID";
$lang['admin']['oauth2_client_secret'] = "Client Secret";
$lang['admin']['oauth2_redirect_uri'] = "Redirect URI";
$lang['admin']['oauth2_revoke_tokens'] = 'Alle Client Tokens entfernen';
$lang['admin']['oauth2_renew_secret'] = 'Neues Client Secret generieren';
$lang['edit']['client_id'] = 'Client ID';
$lang['edit']['client_secret'] = 'Client Secret';
$lang['edit']['scope'] = 'Scope';
$lang['edit']['grant_types'] = 'Grant types';
$lang['edit']['redirect_uri'] = 'Redirect/Callback URL';
$lang['oauth2']['scope_ask_permission'] = 'Eine Anwendung hat um die folgenden Berechtigungen gebeten';
$lang['oauth2']['profile'] = 'Profil';
$lang['oauth2']['profile_desc'] = 'Persönliche Informationen anzeigen: Benutzername, Name, Erstellzeitpunkt, Änderungszeitpunkt, Status';
$lang['oauth2']['permit'] = 'Anwendung authorisieren';
$lang['oauth2']['authorize_app'] = 'Anwendung authorisieren';
$lang['oauth2']['deny'] = 'Ablehnen';
$lang['oauth2']['access_denied'] = 'Bitte als Mailbox-Nutzer einloggen, um den Zugriff via OAuth2 zu erlauben.';
$lang['admin']['customize'] = "UI Anpassung";
$lang['admin']['change_logo'] = "Logo ändern";
@ -836,14 +868,6 @@ $lang['mailbox']['add_tls_policy_map'] = "TLS-Richtlinieneintrag hinzufügen";
$lang['danger']['tls_policy_map_parameter_invalid'] = "Parameter ist ungültig";
$lang['danger']['temp_error'] = "Temporärer Fehler";
$lang['oauth2']['scope_ask_permission'] = 'Eine Anwendung hat um die folgenden Berechtigungen gebeten';
$lang['oauth2']['profile'] = 'Profil';
$lang['oauth2']['profile_desc'] = 'Persönliche Informationen anzeigen: Benutzername, Name, Erstellzeitpunkt, Änderungszeitpunkt, Status';
$lang['oauth2']['permit'] = 'Anwendung authorisieren';
$lang['oauth2']['authorize_app'] = 'Anwendung authorisieren';
$lang['oauth2']['deny'] = 'Ablehnen';
$lang['oauth2']['access_denied'] = 'Bitte als Mailbox-Nutzer einloggen, um den Zugriff via OAuth2 zu erlauben.';
$lang['admin']['sys_mails'] = 'System-E-Mails';
$lang['admin']['subject'] = 'Betreff';
$lang['admin']['from'] = 'Absender';

View File

@ -346,11 +346,6 @@ $lang['mailbox']['sogo_visible'] = 'Alias is visible in SOGo';
$lang['mailbox']['sogo_visible_y'] = 'Show alias in SOGo';
$lang['mailbox']['sogo_visible_n'] = 'Hide alias in SOGo';
$lang['edit']['syncjob'] = 'Edit sync job';
$lang['edit']['client_id'] = 'Client ID';
$lang['edit']['client_secret'] = 'Client secret';
$lang['edit']['scope'] = 'Scope';
$lang['edit']['grant_types'] = 'Grant types';
$lang['edit']['redirect_uri'] = 'Redirect/Callback URL';
$lang['edit']['hostname'] = 'Hostname';
$lang['edit']['encryption'] = 'Encryption';
$lang['edit']['maxage'] = 'Maximum age of messages in days that will be polled from remote<br><small>(0 = ignore age)</small>';
@ -679,6 +674,38 @@ $lang['admin']['credentials_transport_warning'] = '<b>Warning</b>: Adding a new
$lang['admin']['destination'] = 'Destination';
$lang['admin']['nexthop'] = 'Next hop';
$lang['admin']['oauth2_info'] = 'The OAuth2 implementation supports the grant type "Authorization Code" and issues refresh tokens.<br>
The server also automatically issues new refresh tokens, after a refresh token has been used.<br><br>
The default scope is <i>profile</i>. Only mailbox users can be authenticated against OAuth2. If the scope parameter is omitted, it falls back to <i>profile</i>.<br>
The <i>state</i> parameter is required to be sent by the client as part of the authorize request.<br><br>
Pathes for requests to the OAuth2 API: <br>
<ul>
<li>Authorization endpoint: <code>/oauth/authorize</code></li>
<li>Token endpoint: <code>/oauth/token</code></li>
<li>Resource page: <code>/oauth/profile</code></li>
</ul>
Regenerating the client secret will not expire existing authorization codes, but they will fail to renew their token.<br><br>
Revoking client tokens will cause immediate termination of all active sessions. All clients need to re-authenticate.';
$lang['admin']['oauth2_client_id'] = "Client ID";
$lang['admin']['oauth2_client_secret'] = "Client secret";
$lang['admin']['oauth2_redirect_uri'] = "Redirect URI";
$lang['admin']['oauth2_revoke_tokens'] = 'Revoke all client tokens';
$lang['admin']['oauth2_renew_secret'] = 'Generate new client secret';
$lang['edit']['client_id'] = 'Client ID';
$lang['edit']['client_secret'] = 'Client secret';
$lang['edit']['scope'] = 'Scope';
$lang['edit']['grant_types'] = 'Grant types';
$lang['edit']['redirect_uri'] = 'Redirect/Callback URL';
$lang['oauth2']['scope_ask_permission'] = 'An application asked for the following permissions';
$lang['oauth2']['profile'] = 'Profile';
$lang['oauth2']['profile_desc'] = 'View personal information: username, full name, created, modified, active';
$lang['oauth2']['permit'] = 'Authorize application';
$lang['oauth2']['authorize_app'] = 'Authorize application';
$lang['oauth2']['deny'] = 'Deny';
$lang['oauth2']['access_denied'] = 'Please login as mailbox owner to grant access via OAuth2.';
$lang['success']['forwarding_host_removed'] = "Forwarding host %s has been removed";
$lang['success']['forwarding_host_added'] = "Forwarding host %s has been added";
$lang['success']['relayhost_removed'] = "Map entry %s has been removed";
@ -727,7 +754,7 @@ $lang['admin']['help_text'] = "Override help text below login mask (HTML allowed
$lang['admin']['title_name'] = '"mailcow UI" website title';
$lang['admin']['main_name'] = '"mailcow UI" name';
$lang['admin']['apps_name'] = '"mailcow Apps" name';
$lang['admin']['ui_impress'] = 'Impress, Footer note (HTML allowed)';
$lang['admin']['ui_footer'] = 'Footer (HTML allowed)';
$lang['admin']['customize'] = "Customize";
$lang['admin']['change_logo'] = "Change logo";
@ -864,14 +891,6 @@ $lang['mailbox']['add_recipient_map_entry'] = 'Add recipient map';
$lang['danger']['tls_policy_map_parameter_invalid'] = "Policy parameter is invalid";
$lang['danger']['temp_error'] = "Temporary error";
$lang['oauth2']['scope_ask_permission'] = 'An application asked for the following permissions';
$lang['oauth2']['profile'] = 'Profile';
$lang['oauth2']['profile_desc'] = 'View personal information: username, full name, created, modified, active';
$lang['oauth2']['permit'] = 'Authorize application';
$lang['oauth2']['authorize_app'] = 'Authorize application';
$lang['oauth2']['deny'] = 'Deny';
$lang['oauth2']['access_denied'] = 'Please login as mailbox owner to grant access via OAuth2.';
$lang['admin']['sys_mails'] = 'System mails';
$lang['admin']['subject'] = 'Subject';
$lang['admin']['from'] = 'From';

View File

@ -710,7 +710,7 @@ $lang['admin']['help_text'] = "Hulpteksten onder inlogvenster (HTML toegestaan)"
$lang['admin']['title_name'] = '"Mailcow" (website-titel)';
$lang['admin']['main_name'] = '"Mailcow"';
$lang['admin']['apps_name'] = '"Mailcow-apps"';
$lang['admin']['ui_impress'] = 'Footer-vermelding (HTML toegestaan)';
$lang['admin']['ui_footer'] = 'Footer-vermelding (HTML toegestaan)';
$lang['admin']['customize'] = "Uiterlijk";
$lang['admin']['change_logo'] = "Logo";

View File

@ -105,6 +105,32 @@ if (!isset($_SESSION['mailcow_cc_role'])) {
</div>
</div>
</div><!-- add domain admin modal -->
<!-- add oauth2 client modal -->
<div class="modal fade" id="addOAuth2ClientModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">OAuth2</h3>
</div>
<div class="modal-body">
<form class="form-horizontal" data-cached-form="true" data-id="add_oauth2_client" role="form" method="post">
<div class="form-group">
<label class="control-label col-sm-2" for="redirect_uri"><?=$lang['admin']['oauth2_redirect_uri'];?>:</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="redirect_uri" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button class="btn btn-default" data-action="add_item" data-id="add_oauth2_client" data-api-url='add/oauth2-client' data-api-attr='{}' href="#"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span> <?=$lang['admin']['add'];?></button>
</div>
</div>
</form>
</div>
</div>
</div>
</div><!-- add domain admin modal -->
<!-- add admin modal -->
<div class="modal fade" id="addAdminModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg">

View File

@ -0,0 +1,66 @@
<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/inc/prerequisites.inc.php';
if (!isset($_SESSION['mailcow_cc_role'])) {
$_SESSION['oauth2_request'] = $_SERVER['REQUEST_URI'];
header('Location: /?oauth');
}
$request = OAuth2\Request::createFromGlobals();
$response = new OAuth2\Response();
if (!$oauth2_server->validateAuthorizeRequest($request, $response)) {
$response->send();
exit();
}
if (!isset($_POST['authorized'])):
require_once $_SERVER['DOCUMENT_ROOT'] . '/inc/header.inc.php';
?>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading"><?=$lang['oauth2']['authorize_app'];?></div>
<div class="panel-body">
<?php
if ($_SESSION['mailcow_cc_role'] != 'user'):
$request = '';
?>
<p><?=$lang['oauth2']['access_denied'];?></p>
<?php
else:
?>
<p><?=$lang['oauth2']['scope_ask_permission'];?>:</p>
<dl class="dl-horizontal">
<dt><?=$lang['oauth2']['profile'];?></dt>
<dd><?=$lang['oauth2']['profile_desc'];?></dd>
</dl>
<form class="form-horizontal" autocapitalize="none" autocorrect="off" role="form" method="post">
<div class="form-group">
<div class="col-sm-10 text-center">
<button class="btn btn-success" name="authorized" type="submit" value="1"><?=$lang['oauth2']['permit'];?></button>
<a href="#" class="btn btn-default" onclick="window.history.back()" role="button"><?=$lang['oauth2']['deny'];?></a>
<input type="hidden" name="csrf_token" value="<?=$_SESSION['CSRF']['TOKEN'];?>">
</div>
</div>
</form>
<?php
endif;
?>
</div>
</div>
</div> <!-- /container -->
<script src="../js/authorize.js"></script>
<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/inc/footer.inc.php';
exit();
endif;
// print the authorization code if the user has authorized your client
$is_authorized = ($_POST['authorized'] == '1');
$oauth2_server->handleAuthorizeRequest($request, $response, $is_authorized, $_SESSION['mailcow_cc_username']);
if ($is_authorized) {
unset($_SESSION['oauth2_request']);
header('Location: ' . $response->getHttpHeader('Location'));
exit;
}

View File

@ -0,0 +1,28 @@
<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/inc/prerequisites.inc.php';
if (!$oauth2_server->verifyResourceRequest(OAuth2\Request::createFromGlobals())) {
$oauth2_server->getResponse()->send();
die;
}
$token = $oauth2_server->getAccessTokenData(OAuth2\Request::createFromGlobals());
$stmt = $pdo->prepare("SELECT * FROM `mailbox` WHERE `username` = :username AND `active` = '1'");
$stmt->execute(array(':username' => $token['user_id']));
$mailbox = $stmt->fetch(PDO::FETCH_ASSOC);
if (!empty($mailbox)) {
if ($token['scope'] == 'profile') {
echo json_encode(array(
'success' => true,
'username' => $token['user_id'],
'email' => (!empty($mailbox['username']) ? $mailbox['username'] : ''),
'full_name' => (!empty($mailbox['name']) ? $mailbox['name'] : 'mailcow administrative user'),
'created' => (!empty($mailbox['created']) ? $mailbox['created'] : ''),
'modified' => (!empty($mailbox['modified']) ? $mailbox['modified'] : ''),
'active' => (!empty($mailbox['active']) ? $mailbox['active'] : ''),
));
exit;
}
}
echo json_encode(array(
'success' => false
));

4
data/web/oauth/token.php Normal file
View File

@ -0,0 +1,4 @@
<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/inc/prerequisites.inc.php';
$request = OAuth2\Request::createFromGlobals();
$oauth2_server->handleTokenRequest($request)->send();