Skip to content

Commit ee4dbc0

Browse files
wsjzdataroaring
authored andcommitted
[fix](kerberos)fix and refactor ugi login for kerberos and simple authentication (#37301)
## Proposed changes optimize kerberos ugi login: 1. support authentication framework for external table 2. cache ugi to avoid conflicts when set configuration for ugi login 3. do ugi login just on creating catalog, which reduces the ugi create times 4. only simple authentication will use getloginUser, which avoids conflicts between simple and kerberos authentication <!--Describe your changes.-->
1 parent 580eb67 commit ee4dbc0

File tree

15 files changed

+427
-94
lines changed

15 files changed

+427
-94
lines changed

docker/thirdparties/docker-compose/kerberos/common/conf/doris-krb5.conf

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
default_realm = LABS.TERADATA.COM
2525
dns_lookup_realm = false
2626
dns_lookup_kdc = false
27-
ticket_lifetime = 24h
27+
ticket_lifetime = 5s
2828
# this setting is causing a Message stream modified (41) error when talking to KDC running on CentOS 7: https://stackoverflow.com/a/60978520
2929
# renew_lifetime = 7d
3030
forwardable = true

fe/fe-common/src/main/java/org/apache/doris/common/security/authentication/AuthenticationConfig.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ public abstract class AuthenticationConfig {
2626
public static String HADOOP_KERBEROS_KEYTAB = "hadoop.kerberos.keytab";
2727
public static String HIVE_KERBEROS_PRINCIPAL = "hive.metastore.kerberos.principal";
2828
public static String HIVE_KERBEROS_KEYTAB = "hive.metastore.kerberos.keytab.file";
29+
public static String DORIS_KRB5_DEBUG = "doris.krb5.debug";
2930

3031
/**
3132
* @return true if the config is valid, otherwise false.
@@ -57,6 +58,7 @@ public static AuthenticationConfig getKerberosConfig(Configuration conf,
5758
krbConfig.setKerberosPrincipal(conf.get(krbPrincipalKey));
5859
krbConfig.setKerberosKeytab(conf.get(krbKeytabKey));
5960
krbConfig.setConf(conf);
61+
krbConfig.setPrintDebugLog(Boolean.parseBoolean(conf.get(DORIS_KRB5_DEBUG, "false")));
6062
return krbConfig;
6163
} else {
6264
// AuthType.SIMPLE
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// Licensed to the Apache Software Foundation (ASF) under one
2+
// or more contributor license agreements. See the NOTICE file
3+
// distributed with this work for additional information
4+
// regarding copyright ownership. The ASF licenses this file
5+
// to you under the Apache License, Version 2.0 (the
6+
// "License"); you may not use this file except in compliance
7+
// with the License. You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing,
12+
// software distributed under the License is distributed on an
13+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
// KIND, either express or implied. See the License for the
15+
// specific language governing permissions and limitations
16+
// under the License.
17+
18+
package org.apache.doris.common.security.authentication;
19+
20+
import org.apache.hadoop.security.UserGroupInformation;
21+
22+
import java.io.IOException;
23+
import java.security.PrivilegedExceptionAction;
24+
25+
public interface HadoopAuthenticator {
26+
27+
UserGroupInformation getUGI() throws IOException;
28+
29+
default <T> T doAs(PrivilegedExceptionAction<T> action) throws IOException {
30+
try {
31+
return getUGI().doAs(action);
32+
} catch (InterruptedException e) {
33+
throw new IOException(e);
34+
}
35+
}
36+
37+
static HadoopAuthenticator getHadoopAuthenticator(AuthenticationConfig config) {
38+
if (config instanceof KerberosAuthenticationConfig) {
39+
return new HadoopKerberosAuthenticator((KerberosAuthenticationConfig) config);
40+
} else {
41+
return new HadoopSimpleAuthenticator((SimpleAuthenticationConfig) config);
42+
}
43+
}
44+
}
Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
// Licensed to the Apache Software Foundation (ASF) under one
2+
// or more contributor license agreements. See the NOTICE file
3+
// distributed with this work for additional information
4+
// regarding copyright ownership. The ASF licenses this file
5+
// to you under the Apache License, Version 2.0 (the
6+
// "License"); you may not use this file except in compliance
7+
// with the License. You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing,
12+
// software distributed under the License is distributed on an
13+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
// KIND, either express or implied. See the License for the
15+
// specific language governing permissions and limitations
16+
// under the License.
17+
18+
package org.apache.doris.common.security.authentication;
19+
20+
import com.google.common.base.Preconditions;
21+
import com.google.common.collect.ImmutableMap;
22+
import com.google.common.collect.ImmutableSet;
23+
import io.trino.plugin.base.authentication.KerberosTicketUtils;
24+
import org.apache.hadoop.conf.Configuration;
25+
import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
26+
import org.apache.hadoop.security.UserGroupInformation;
27+
import org.apache.logging.log4j.LogManager;
28+
import org.apache.logging.log4j.Logger;
29+
30+
import java.io.IOException;
31+
import java.util.Collections;
32+
import java.util.Date;
33+
import java.util.Map;
34+
import java.util.Objects;
35+
import java.util.Set;
36+
import javax.security.auth.Subject;
37+
import javax.security.auth.kerberos.KerberosPrincipal;
38+
import javax.security.auth.kerberos.KerberosTicket;
39+
import javax.security.auth.login.AppConfigurationEntry;
40+
import javax.security.auth.login.LoginContext;
41+
import javax.security.auth.login.LoginException;
42+
43+
public class HadoopKerberosAuthenticator implements HadoopAuthenticator {
44+
private static final Logger LOG = LogManager.getLogger(HadoopKerberosAuthenticator.class);
45+
private final KerberosAuthenticationConfig config;
46+
private Subject subject;
47+
private long nextRefreshTime;
48+
private UserGroupInformation ugi;
49+
50+
public HadoopKerberosAuthenticator(KerberosAuthenticationConfig config) {
51+
this.config = config;
52+
}
53+
54+
public static void initializeAuthConfig(Configuration hadoopConf) {
55+
hadoopConf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, "true");
56+
synchronized (HadoopKerberosAuthenticator.class) {
57+
// avoid other catalog set conf at the same time
58+
UserGroupInformation.setConfiguration(hadoopConf);
59+
}
60+
}
61+
62+
@Override
63+
public synchronized UserGroupInformation getUGI() throws IOException {
64+
if (ugi == null) {
65+
subject = getSubject(config.getKerberosKeytab(), config.getKerberosPrincipal(), config.isPrintDebugLog());
66+
ugi = Objects.requireNonNull(login(subject), "login result is null");
67+
return ugi;
68+
}
69+
if (nextRefreshTime < System.currentTimeMillis()) {
70+
long lastRefreshTime = nextRefreshTime;
71+
Subject existingSubject = subject;
72+
if (LOG.isDebugEnabled()) {
73+
Date lastTicketEndTime = getTicketEndTime(subject);
74+
LOG.debug("Current ticket expired time is {}", lastTicketEndTime);
75+
}
76+
// renew subject
77+
Subject newSubject = getSubject(config.getKerberosKeytab(), config.getKerberosPrincipal(),
78+
config.isPrintDebugLog());
79+
Objects.requireNonNull(login(newSubject), "re-login result is null");
80+
// modify UGI instead of returning new UGI
81+
existingSubject.getPrincipals().addAll(newSubject.getPrincipals());
82+
Set<Object> privateCredentials = existingSubject.getPrivateCredentials();
83+
// clear the old credentials
84+
synchronized (privateCredentials) {
85+
privateCredentials.clear();
86+
privateCredentials.addAll(newSubject.getPrivateCredentials());
87+
}
88+
Set<Object> publicCredentials = existingSubject.getPublicCredentials();
89+
synchronized (publicCredentials) {
90+
publicCredentials.clear();
91+
publicCredentials.addAll(newSubject.getPublicCredentials());
92+
}
93+
nextRefreshTime = calculateNextRefreshTime(newSubject);
94+
if (LOG.isDebugEnabled()) {
95+
Date lastTicketEndTime = getTicketEndTime(newSubject);
96+
LOG.debug("Next ticket expired time is {}", lastTicketEndTime);
97+
LOG.debug("Refresh kerberos ticket succeeded, last time is {}, next time is {}",
98+
lastRefreshTime, nextRefreshTime);
99+
}
100+
}
101+
return ugi;
102+
}
103+
104+
private UserGroupInformation login(Subject subject) throws IOException {
105+
// login and get ugi when catalog is initialized
106+
initializeAuthConfig(config.getConf());
107+
String principal = config.getKerberosPrincipal();
108+
if (LOG.isDebugEnabled()) {
109+
LOG.debug("Login by kerberos authentication with principal: {}", principal);
110+
}
111+
return UserGroupInformation.getUGIFromSubject(subject);
112+
}
113+
114+
private static long calculateNextRefreshTime(Subject subject) {
115+
Preconditions.checkArgument(subject != null, "subject must be present in kerberos based UGI");
116+
KerberosTicket tgtTicket = KerberosTicketUtils.getTicketGrantingTicket(subject);
117+
return KerberosTicketUtils.getRefreshTime(tgtTicket);
118+
}
119+
120+
private static Date getTicketEndTime(Subject subject) {
121+
Preconditions.checkArgument(subject != null, "subject must be present in kerberos based UGI");
122+
KerberosTicket tgtTicket = KerberosTicketUtils.getTicketGrantingTicket(subject);
123+
return tgtTicket.getEndTime();
124+
}
125+
126+
private static Subject getSubject(String keytab, String principal, boolean printDebugLog) {
127+
Subject subject = new Subject(false, ImmutableSet.of(new KerberosPrincipal(principal)),
128+
Collections.emptySet(), Collections.emptySet());
129+
javax.security.auth.login.Configuration conf = getConfiguration(keytab, principal, printDebugLog);
130+
try {
131+
LoginContext loginContext = new LoginContext("", subject, null, conf);
132+
loginContext.login();
133+
return loginContext.getSubject();
134+
} catch (LoginException e) {
135+
throw new RuntimeException(e);
136+
}
137+
}
138+
139+
private static javax.security.auth.login.Configuration getConfiguration(String keytab, String principal,
140+
boolean printDebugLog) {
141+
return new javax.security.auth.login.Configuration() {
142+
@Override
143+
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
144+
ImmutableMap.Builder<String, String> builder = ImmutableMap.<String, String>builder()
145+
.put("doNotPrompt", "true")
146+
.put("isInitiator", "true")
147+
.put("useKeyTab", "true")
148+
.put("storeKey", "true")
149+
.put("keyTab", keytab)
150+
.put("principal", principal);
151+
if (printDebugLog) {
152+
builder.put("debug", "true");
153+
}
154+
Map<String, String> options = builder.build();
155+
return new AppConfigurationEntry[]{
156+
new AppConfigurationEntry(
157+
"com.sun.security.auth.module.Krb5LoginModule",
158+
AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
159+
options)};
160+
}
161+
};
162+
}
163+
}
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Licensed to the Apache Software Foundation (ASF) under one
2+
// or more contributor license agreements. See the NOTICE file
3+
// distributed with this work for additional information
4+
// regarding copyright ownership. The ASF licenses this file
5+
// to you under the Apache License, Version 2.0 (the
6+
// "License"); you may not use this file except in compliance
7+
// with the License. You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing,
12+
// software distributed under the License is distributed on an
13+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
// KIND, either express or implied. See the License for the
15+
// specific language governing permissions and limitations
16+
// under the License.
17+
18+
package org.apache.doris.common.security.authentication;
19+
20+
import org.apache.hadoop.security.UserGroupInformation;
21+
import org.apache.logging.log4j.LogManager;
22+
import org.apache.logging.log4j.Logger;
23+
24+
public class HadoopSimpleAuthenticator implements HadoopAuthenticator {
25+
private static final Logger LOG = LogManager.getLogger(HadoopSimpleAuthenticator.class);
26+
private final UserGroupInformation ugi;
27+
28+
public HadoopSimpleAuthenticator(SimpleAuthenticationConfig config) {
29+
String hadoopUserName = config.getUsername();
30+
if (hadoopUserName == null) {
31+
hadoopUserName = "hadoop";
32+
config.setUsername(hadoopUserName);
33+
if (LOG.isDebugEnabled()) {
34+
LOG.debug("{} is unset, use default user: hadoop", AuthenticationConfig.HADOOP_USER_NAME);
35+
}
36+
}
37+
ugi = UserGroupInformation.createRemoteUser(hadoopUserName);
38+
if (LOG.isDebugEnabled()) {
39+
LOG.debug("Login by proxy user, hadoop.username: {}", hadoopUserName);
40+
}
41+
}
42+
43+
@Override
44+
public UserGroupInformation getUGI() {
45+
return ugi;
46+
}
47+
}

fe/fe-common/src/main/java/org/apache/doris/common/security/authentication/HadoopUGI.java

Lines changed: 18 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,14 @@
1818
package org.apache.doris.common.security.authentication;
1919

2020
import org.apache.commons.lang3.StringUtils;
21-
import org.apache.hadoop.conf.Configuration;
22-
import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
2321
import org.apache.hadoop.security.UserGroupInformation;
2422
import org.apache.logging.log4j.LogManager;
2523
import org.apache.logging.log4j.Logger;
2624

2725
import java.io.IOException;
2826
import java.security.PrivilegedExceptionAction;
2927

28+
@Deprecated
3029
public class HadoopUGI {
3130
private static final Logger LOG = LogManager.getLogger(HadoopUGI.class);
3231

@@ -39,82 +38,30 @@ private static UserGroupInformation loginWithUGI(AuthenticationConfig config) {
3938
if (config == null || !config.isValid()) {
4039
return null;
4140
}
42-
UserGroupInformation ugi;
4341
if (config instanceof KerberosAuthenticationConfig) {
44-
KerberosAuthenticationConfig krbConfig = (KerberosAuthenticationConfig) config;
45-
Configuration hadoopConf = krbConfig.getConf();
46-
hadoopConf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, "true");
47-
hadoopConf.set(CommonConfigurationKeysPublic.HADOOP_KERBEROS_KEYTAB_LOGIN_AUTORENEWAL_ENABLED, "true");
48-
UserGroupInformation.setConfiguration(hadoopConf);
49-
String principal = krbConfig.getKerberosPrincipal();
5042
try {
51-
// login hadoop with keytab and try checking TGT
52-
ugi = UserGroupInformation.getLoginUser();
53-
LOG.debug("Current login user: {}", ugi.getUserName());
54-
if (ugi.hasKerberosCredentials() && StringUtils.equals(ugi.getUserName(), principal)) {
55-
// if the current user is logged by kerberos and is the same user
56-
// just use checkTGTAndReloginFromKeytab because this method will only relogin
57-
// when the TGT is expired or is close to expiry
58-
ugi.checkTGTAndReloginFromKeytab();
59-
return ugi;
43+
// TODO: remove after iceberg and hudi kerberos test case pass
44+
try {
45+
// login hadoop with keytab and try checking TGT
46+
UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
47+
LOG.debug("Current login user: {}", ugi.getUserName());
48+
String principal = ((KerberosAuthenticationConfig) config).getKerberosPrincipal();
49+
if (ugi.hasKerberosCredentials() && StringUtils.equals(ugi.getUserName(), principal)) {
50+
// if the current user is logged by kerberos and is the same user
51+
// just use checkTGTAndReloginFromKeytab because this method will only relogin
52+
// when the TGT is expired or is close to expiry
53+
ugi.checkTGTAndReloginFromKeytab();
54+
return ugi;
55+
}
56+
} catch (IOException e) {
57+
LOG.warn("A SecurityException occurs with kerberos, do login immediately.", e);
6058
}
61-
} catch (IOException e) {
62-
LOG.warn("A SecurityException occurs with kerberos, do login immediately.", e);
63-
}
64-
try {
65-
ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(principal, krbConfig.getKerberosKeytab());
66-
UserGroupInformation.setLoginUser(ugi);
67-
LOG.debug("Login by kerberos authentication with principal: {}", principal);
68-
return ugi;
59+
return new HadoopKerberosAuthenticator((KerberosAuthenticationConfig) config).getUGI();
6960
} catch (IOException e) {
7061
throw new RuntimeException(e);
7162
}
7263
} else {
73-
String hadoopUserName = ((SimpleAuthenticationConfig) config).getUsername();
74-
if (hadoopUserName == null) {
75-
hadoopUserName = "hadoop";
76-
((SimpleAuthenticationConfig) config).setUsername(hadoopUserName);
77-
LOG.debug(AuthenticationConfig.HADOOP_USER_NAME + " is unset, use default user: hadoop");
78-
}
79-
80-
try {
81-
ugi = UserGroupInformation.getLoginUser();
82-
if (ugi.getUserName().equals(hadoopUserName)) {
83-
return ugi;
84-
}
85-
} catch (IOException e) {
86-
LOG.warn("A SecurityException occurs with simple, do login immediately.", e);
87-
}
88-
89-
ugi = UserGroupInformation.createRemoteUser(hadoopUserName);
90-
UserGroupInformation.setLoginUser(ugi);
91-
LOG.debug("Login by proxy user, hadoop.username: {}", hadoopUserName);
92-
return ugi;
93-
}
94-
}
95-
96-
/**
97-
* use for HMSExternalCatalog to login
98-
* @param config auth config
99-
*/
100-
public static void tryKrbLogin(String catalogName, AuthenticationConfig config) {
101-
if (config instanceof KerberosAuthenticationConfig) {
102-
KerberosAuthenticationConfig krbConfig = (KerberosAuthenticationConfig) config;
103-
try {
104-
Configuration hadoopConf = krbConfig.getConf();
105-
hadoopConf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, "true");
106-
hadoopConf.set(CommonConfigurationKeysPublic.HADOOP_KERBEROS_KEYTAB_LOGIN_AUTORENEWAL_ENABLED, "true");
107-
UserGroupInformation.setConfiguration(hadoopConf);
108-
/**
109-
* Because metastore client is created by using
110-
* {@link org.apache.hadoop.hive.metastore.RetryingMetaStoreClient#getProxy}
111-
* it will relogin when TGT is expired, so we don't need to relogin manually.
112-
*/
113-
UserGroupInformation.loginUserFromKeytab(krbConfig.getKerberosPrincipal(),
114-
krbConfig.getKerberosKeytab());
115-
} catch (IOException e) {
116-
throw new RuntimeException("login with kerberos auth failed for catalog: " + catalogName, e);
117-
}
64+
return new HadoopSimpleAuthenticator((SimpleAuthenticationConfig) config).getUGI();
11865
}
11966
}
12067

0 commit comments

Comments
 (0)