Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3799,5 +3799,7 @@ private DataNodeQueryMessages() {}
public static final String EXCEPTION_ALIAS_IS_NULL_862D23B1 = "alias is null";
public static final String EXCEPTION_REFERENCES_IS_NULL_25A7E3AF = "references is null";
public static final String EXCEPTION_VISIBLEALIASES_IS_NULL_630B27F1 = "visibleAliases is null";
public static final String EXCEPTION_HAS_NO_PERMISSION_TO_EXECUTE_ARG_BECAUSE_ONLY_THE_SUPERUSER_CAN_ALTER_HIM_HERSELF_C5902893 =
"Has no permission to execute %s, because only the superuser can alter him/herself.";

}
Original file line number Diff line number Diff line change
Expand Up @@ -4556,5 +4556,7 @@ private DataNodeQueryMessages() {}
public static final String EXCEPTION_ALIAS_IS_NULL_862D23B1 = "alias 不能为空";
public static final String EXCEPTION_REFERENCES_IS_NULL_25A7E3AF = "references 不能为空";
public static final String EXCEPTION_VISIBLEALIASES_IS_NULL_630B27F1 = "visibleAliases 不能为空";
public static final String EXCEPTION_HAS_NO_PERMISSION_TO_EXECUTE_ARG_BECAUSE_ONLY_THE_SUPERUSER_CAN_ALTER_HIM_HERSELF_C5902893 =
"无权执行 %s,因为只有超级用户可以修改其自身。";

}
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,41 @@
package org.apache.iotdb.db.audit;

import org.apache.iotdb.commons.audit.AbstractAuditLogger;
import org.apache.iotdb.commons.audit.AuditEventType;
import org.apache.iotdb.commons.audit.AuditLogFields;
import org.apache.iotdb.commons.audit.AuditLogOperation;
import org.apache.iotdb.commons.audit.IAuditEntity;
import org.apache.iotdb.commons.audit.PrivilegeLevel;
import org.apache.iotdb.commons.auth.entity.PrivilegeType;
import org.apache.iotdb.commons.exception.IllegalPathException;
import org.apache.iotdb.commons.path.PartialPath;
import org.apache.iotdb.commons.utils.CommonDateTimeUtils;
import org.apache.iotdb.db.queryengine.plan.Coordinator;
import org.apache.iotdb.db.queryengine.plan.statement.crud.InsertRowStatement;

import org.apache.tsfile.common.conf.TSFileConfig;
import org.apache.tsfile.enums.TSDataType;
import org.apache.tsfile.utils.Binary;

import jakarta.validation.constraints.NotNull;

import java.util.Arrays;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DNAuditLogger extends AbstractAuditLogger {

// This text matcher is only a fallback. Password-update semantic nodes must clear sql_string
// before any audit entry is generated.
private static final Pattern ALTER_USER_PASSWORD_PATTERN =
Pattern.compile(
"^(\\s*ALTER\\s+USER\\s+.+?\\s+SET\\s+PASSWORD\\s+)"
+ "(?:(?:U&)?'(?:''|[^'])*'|\"(?:\"\"|[^\"])*\")"
+ "(\\s*;?\\s*)$",
Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
private static final Pattern VALUES_PATTERN = Pattern.compile("(?i)(values)\\([^)]*\\)");

private Coordinator coordinator;

private DNAuditLogger() {
Expand All @@ -50,7 +72,115 @@ public void setCoordinator(Coordinator coordinator) {
@NotNull
private static InsertRowStatement generateInsertStatement(
IAuditEntity auditLogFields, String log, PartialPath logDevice) {
return null;
return generateInsertStatement(
auditLogFields, log, logDevice, CommonDateTimeUtils.currentTime());
}

@NotNull
static InsertRowStatement generateInsertStatement(
IAuditEntity auditLogFields, String log, PartialPath logDevice, long logTimestamp) {
String username = auditLogFields.getUsername();
String address = auditLogFields.getCliHostname();
AuditEventType type = auditLogFields.getAuditEventType();
AuditLogOperation operation = auditLogFields.getAuditLogOperation();
PrivilegeLevel privilegeLevel = PrivilegeLevel.GLOBAL;
if (auditLogFields.getPrivilegeTypes() != null) {
for (PrivilegeType privilegeType : auditLogFields.getPrivilegeTypes()) {
privilegeLevel = judgePrivilegeLevel(privilegeType);
if (privilegeLevel == PrivilegeLevel.GLOBAL) {
break;
}
}
}

InsertRowStatement insertStatement = new InsertRowStatement();
insertStatement.setDevicePath(logDevice);
insertStatement.setTime(logTimestamp);
insertStatement.setMeasurements(
new String[] {
AUDIT_LOG_USERNAME,
AUDIT_LOG_CLI_HOSTNAME,
AUDIT_LOG_AUDIT_EVENT_TYPE,
AUDIT_LOG_OPERATION_TYPE,
AUDIT_LOG_PRIVILEGE_TYPE,
AUDIT_LOG_PRIVILEGE_LEVEL,
AUDIT_LOG_RESULT,
AUDIT_LOG_DATABASE,
AUDIT_LOG_SQL_STRING,
AUDIT_LOG_LOG
});
insertStatement.setAligned(true);
String sqlString = sanitizeAuditSql(auditLogFields.getSqlString());
insertStatement.setValues(
new Object[] {
new Binary(username == null ? "null" : username, TSFileConfig.STRING_CHARSET),
new Binary(address == null ? "null" : address, TSFileConfig.STRING_CHARSET),
new Binary(type == null ? "null" : type.toString(), TSFileConfig.STRING_CHARSET),
new Binary(
operation == null ? "null" : operation.toString(), TSFileConfig.STRING_CHARSET),
new Binary(
auditLogFields.getPrivilegeTypes() == null
? "null"
: auditLogFields.getPrivilegeTypeString(),
TSFileConfig.STRING_CHARSET),
new Binary(privilegeLevel.toString(), TSFileConfig.STRING_CHARSET),
auditLogFields.getResult(),
new Binary(
auditLogFields.getDatabase() == null ? "null" : auditLogFields.getDatabase(),
TSFileConfig.STRING_CHARSET),
new Binary(sqlString == null ? "null" : sqlString, TSFileConfig.STRING_CHARSET),
new Binary(log == null ? "null" : log, TSFileConfig.STRING_CHARSET)
});
insertStatement.setDataTypes(
new TSDataType[] {
TSDataType.STRING,
TSDataType.STRING,
TSDataType.STRING,
TSDataType.STRING,
TSDataType.STRING,
TSDataType.STRING,
TSDataType.BOOLEAN,
TSDataType.STRING,
TSDataType.STRING,
TSDataType.STRING,
});
return insertStatement;
}

static String sanitizeAuditSql(String sqlString) {
if (sqlString == null) {
return null;
}
if (sqlString.regionMatches(true, 0, "CREATE USER", 0, "CREATE USER".length())) {
sqlString = String.join(" ", Arrays.asList(sqlString.split(" ")).subList(0, 3)) + " ...";
}
Matcher alterUserMatcher = ALTER_USER_PASSWORD_PATTERN.matcher(sqlString);
if (alterUserMatcher.matches()) {
sqlString = alterUserMatcher.replaceFirst("$1...$2");
}
return VALUES_PATTERN.matcher(sqlString).replaceAll("$1(...)");
}

private static PrivilegeLevel judgePrivilegeLevel(PrivilegeType type) {
if (type == null) {
return PrivilegeLevel.GLOBAL;
}
switch (type) {
case READ_DATA:
case DROP:
case ALTER:
case CREATE:
case DELETE:
case INSERT:
case SELECT:
case MANAGE_DATABASE:
case WRITE_DATA:
case READ_SCHEMA:
case WRITE_SCHEMA:
return PrivilegeLevel.OBJECT;
default:
return PrivilegeLevel.GLOBAL;
}
}

public void createViewIfNecessary() {}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package org.apache.iotdb.db.audit;

import org.apache.iotdb.common.rpc.thrift.TSStatus;
import org.apache.iotdb.commons.audit.AuditEventType;
import org.apache.iotdb.commons.audit.AuditLogFields;
import org.apache.iotdb.commons.audit.AuditLogOperation;
import org.apache.iotdb.commons.audit.IAuditEntity;
import org.apache.iotdb.commons.auth.entity.PrivilegeType;
import org.apache.iotdb.commons.queryengine.common.SessionInfo;
import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.RelationalAuthorStatement;
import org.apache.iotdb.db.queryengine.plan.relational.type.AuthorRType;
import org.apache.iotdb.db.queryengine.plan.statement.AuthorType;
import org.apache.iotdb.db.queryengine.plan.statement.Statement;
import org.apache.iotdb.db.queryengine.plan.statement.sys.AuthorStatement;
import org.apache.iotdb.rpc.TSStatusCode;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Supplier;

/** Holds the security-safe audit fields for one password-change statement. */
public final class PasswordChangeAuditContext {

private static final PasswordChangeAuditContext EMPTY =
new PasswordChangeAuditContext(null, -1, null, null, null, null);

private final AuditLogWriter auditLogWriter;
private final long userId;
private final String username;
private final String clientHostname;
private final String database;
private final String targetUsername;
private final AtomicBoolean logged = new AtomicBoolean(false);

private PasswordChangeAuditContext(
AuditLogWriter auditLogWriter,
long userId,
String username,
String clientHostname,
String database,
String targetUsername) {
this.auditLogWriter = auditLogWriter;
this.userId = userId;
this.username = username;
this.clientHostname = clientHostname;
this.database = database;
this.targetUsername = targetUsername;
}

public static PasswordChangeAuditContext forTreeStatement(
Statement statement, SessionInfo sessionInfo) {
String targetUsername = getTreeTargetUsername(statement);
return targetUsername == null
? EMPTY
: fromSessionInfo(sessionInfo, targetUsername, DNAuditLogger.getInstance()::log);
}

static PasswordChangeAuditContext forTreeStatement(
Statement statement, SessionInfo sessionInfo, AuditLogWriter auditLogWriter) {
String targetUsername = getTreeTargetUsername(statement);
return targetUsername == null
? EMPTY
: fromSessionInfo(sessionInfo, targetUsername, auditLogWriter);
}

public static PasswordChangeAuditContext forTableStatement(
org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Statement statement,
SessionInfo sessionInfo) {
String targetUsername = getTableTargetUsername(statement);
return targetUsername == null
? EMPTY
: fromSessionInfo(sessionInfo, targetUsername, DNAuditLogger.getInstance()::log);
}

static PasswordChangeAuditContext forTableStatement(
org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Statement statement,
SessionInfo sessionInfo,
AuditLogWriter auditLogWriter) {
String targetUsername = getTableTargetUsername(statement);
return targetUsername == null
? EMPTY
: fromSessionInfo(sessionInfo, targetUsername, auditLogWriter);
}

public static PasswordChangeAuditContext forTreeAuthorization(
Statement statement, IAuditEntity auditEntity) {
String targetUsername = getTreeTargetUsername(statement);
return targetUsername == null
? EMPTY
: fromAuditEntity(auditEntity, targetUsername, DNAuditLogger.getInstance()::log);
}

static PasswordChangeAuditContext forTreeAuthorization(
Statement statement, IAuditEntity auditEntity, AuditLogWriter auditLogWriter) {
String targetUsername = getTreeTargetUsername(statement);
return targetUsername == null
? EMPTY
: fromAuditEntity(auditEntity, targetUsername, auditLogWriter);
}

private static String getTreeTargetUsername(Statement statement) {
return statement instanceof AuthorStatement
&& ((AuthorStatement) statement).getAuthorType() == AuthorType.UPDATE_USER
? ((AuthorStatement) statement).getUserName()
: null;
}

private static String getTableTargetUsername(
org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Statement statement) {
return statement instanceof RelationalAuthorStatement
&& ((RelationalAuthorStatement) statement).getAuthorType() == AuthorRType.UPDATE_USER
? ((RelationalAuthorStatement) statement).getUserName()
: null;
}

private static PasswordChangeAuditContext fromAuditEntity(
IAuditEntity auditEntity, String targetUsername, AuditLogWriter auditLogWriter) {
return new PasswordChangeAuditContext(
auditLogWriter,
auditEntity.getUserId(),
auditEntity.getUsername(),
auditEntity.getCliHostname(),
auditEntity.getDatabase(),
targetUsername);
}

private static PasswordChangeAuditContext fromSessionInfo(
SessionInfo sessionInfo, String targetUsername, AuditLogWriter auditLogWriter) {
return new PasswordChangeAuditContext(
auditLogWriter,
sessionInfo.getUserId(),
sessionInfo.getUserName(),
sessionInfo.getCliHostname(),
sessionInfo.getDatabaseName().orElse(null),
targetUsername);
}

public void log(TSStatus status) {
if (targetUsername == null || !logged.compareAndSet(false, true)) {
return;
}
boolean result =
status != null
&& (status.getCode() == TSStatusCode.SUCCESS_STATUS.getStatusCode()
|| status.getCode() == TSStatusCode.REDIRECTION_RECOMMEND.getStatusCode());
auditLogWriter.log(
new AuditLogFields(
userId,
username,
clientHostname,
AuditEventType.MODIFY_PASSWD,
AuditLogOperation.CONTROL,
PrivilegeType.SECURITY,
result,
database,
null),
() -> targetUsername);
}

boolean isEnabled() {
return targetUsername != null;
}

@FunctionalInterface
interface AuditLogWriter {

void log(IAuditEntity auditEntity, Supplier<String> logMessage);
}
}
Loading