001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.thrift;
019
020import static org.junit.Assert.assertFalse;
021import static org.junit.Assert.assertNotNull;
022
023import java.io.File;
024import java.nio.file.Paths;
025import java.security.Principal;
026import java.security.PrivilegedExceptionAction;
027import java.util.Set;
028
029import javax.security.auth.Subject;
030import javax.security.auth.kerberos.KerberosTicket;
031
032import org.apache.hadoop.conf.Configuration;
033import org.apache.hadoop.hbase.HBaseClassTestRule;
034import org.apache.hadoop.hbase.HBaseTestingUtility;
035import org.apache.hadoop.hbase.HConstants;
036import org.apache.hadoop.hbase.security.HBaseKerberosUtils;
037import org.apache.hadoop.hbase.testclassification.ClientTests;
038import org.apache.hadoop.hbase.testclassification.LargeTests;
039import org.apache.hadoop.hbase.thrift.generated.Hbase;
040import org.apache.hadoop.hdfs.DFSConfigKeys;
041import org.apache.hadoop.security.authentication.util.KerberosName;
042import org.apache.http.HttpHeaders;
043import org.apache.http.auth.AuthSchemeProvider;
044import org.apache.http.auth.AuthScope;
045import org.apache.http.auth.KerberosCredentials;
046import org.apache.http.client.config.AuthSchemes;
047import org.apache.http.config.Lookup;
048import org.apache.http.config.RegistryBuilder;
049import org.apache.http.impl.auth.SPNegoSchemeFactory;
050import org.apache.http.impl.client.BasicCredentialsProvider;
051import org.apache.http.impl.client.CloseableHttpClient;
052import org.apache.http.impl.client.HttpClients;
053import org.apache.kerby.kerberos.kerb.client.JaasKrbUtil;
054import org.apache.kerby.kerberos.kerb.server.SimpleKdcServer;
055import org.apache.thrift.protocol.TBinaryProtocol;
056import org.apache.thrift.protocol.TProtocol;
057import org.apache.thrift.transport.THttpClient;
058import org.ietf.jgss.GSSCredential;
059import org.ietf.jgss.GSSManager;
060import org.ietf.jgss.GSSName;
061import org.ietf.jgss.Oid;
062import org.junit.AfterClass;
063import org.junit.BeforeClass;
064import org.junit.ClassRule;
065import org.junit.experimental.categories.Category;
066import org.slf4j.Logger;
067import org.slf4j.LoggerFactory;
068
069/**
070 * Start the HBase Thrift HTTP server on a random port through the command-line
071 * interface and talk to it from client side with SPNEGO security enabled.
072 *
073 * Supplemental test to TestThriftSpnegoHttpServer which falls back to the original
074 * Kerberos principal and keytab configuration properties, not the separate
075 * SPNEGO-specific properties.
076 */
077@Category({ClientTests.class, LargeTests.class})
078public class TestThriftSpnegoHttpFallbackServer extends TestThriftHttpServer {
079  @ClassRule
080  public static final HBaseClassTestRule CLASS_RULE =
081    HBaseClassTestRule.forClass(TestThriftSpnegoHttpFallbackServer.class);
082
083  private static final Logger LOG =
084    LoggerFactory.getLogger(TestThriftSpnegoHttpFallbackServer.class);
085
086  private static SimpleKdcServer kdc;
087  private static File serverKeytab;
088  private static File clientKeytab;
089
090  private static String clientPrincipal;
091  private static String serverPrincipal;
092  private static String spnegoServerPrincipal;
093
094  private static SimpleKdcServer buildMiniKdc() throws Exception {
095    SimpleKdcServer kdc = new SimpleKdcServer();
096
097    File kdcDir = Paths.get(TEST_UTIL.getRandomDir().toString()).toAbsolutePath().toFile();
098    kdcDir.mkdirs();
099    kdc.setWorkDir(kdcDir);
100
101    kdc.setKdcHost(HConstants.LOCALHOST);
102    int kdcPort = HBaseTestingUtility.randomFreePort();
103    kdc.setAllowTcp(true);
104    kdc.setAllowUdp(false);
105    kdc.setKdcTcpPort(kdcPort);
106
107    LOG.info("Starting KDC server at " + HConstants.LOCALHOST + ":" + kdcPort);
108
109    kdc.init();
110
111    return kdc;
112  }
113
114  private static void addSecurityConfigurations(Configuration conf) {
115    KerberosName.setRules("DEFAULT");
116
117    HBaseKerberosUtils.setKeytabFileForTesting(serverKeytab.getAbsolutePath());
118    HBaseKerberosUtils.setPrincipalForTesting(spnegoServerPrincipal);
119    HBaseKerberosUtils.setSecuredConfiguration(conf);
120
121    // if we drop support for hadoop-2.4.0 and hadoop-2.4.1,
122    // the following key should be changed.
123    // 1) DFS_NAMENODE_USER_NAME_KEY -> DFS_NAMENODE_KERBEROS_PRINCIPAL_KEY
124    // 2) DFS_DATANODE_USER_NAME_KEY -> DFS_DATANODE_KERBEROS_PRINCIPAL_KEY
125    conf.set(DFSConfigKeys.DFS_NAMENODE_USER_NAME_KEY, spnegoServerPrincipal);
126    conf.set(DFSConfigKeys.DFS_NAMENODE_KEYTAB_FILE_KEY, serverKeytab.getAbsolutePath());
127    conf.set(DFSConfigKeys.DFS_DATANODE_USER_NAME_KEY, spnegoServerPrincipal);
128    conf.set(DFSConfigKeys.DFS_DATANODE_KEYTAB_FILE_KEY, serverKeytab.getAbsolutePath());
129
130    conf.setBoolean(DFSConfigKeys.DFS_BLOCK_ACCESS_TOKEN_ENABLE_KEY, true);
131
132    conf.set(DFSConfigKeys.DFS_WEB_AUTHENTICATION_KERBEROS_PRINCIPAL_KEY, spnegoServerPrincipal);
133    conf.set(DFSConfigKeys.DFS_WEB_AUTHENTICATION_KERBEROS_KEYTAB_KEY,
134        serverKeytab.getAbsolutePath());
135
136    conf.setBoolean("ignore.secure.ports.for.testing", true);
137
138    conf.setBoolean(ThriftServerRunner.THRIFT_SUPPORT_PROXYUSER_KEY, true);
139    conf.setBoolean(ThriftServerRunner.USE_HTTP_CONF_KEY, true);
140    conf.set("hadoop.proxyuser.HTTP.hosts", "*");
141    conf.set("hadoop.proxyuser.HTTP.groups", "*");
142
143    conf.set(ThriftServerRunner.THRIFT_KERBEROS_PRINCIPAL_KEY, spnegoServerPrincipal);
144    conf.set(ThriftServerRunner.THRIFT_KEYTAB_FILE_KEY, serverKeytab.getAbsolutePath());
145  }
146
147  @BeforeClass
148  public static void setUpBeforeClass() throws Exception {
149    kdc = buildMiniKdc();
150    kdc.start();
151
152    File keytabDir = Paths.get(TEST_UTIL.getRandomDir().toString()).toAbsolutePath().toFile();
153    keytabDir.mkdirs();
154
155    clientPrincipal = "client@" + kdc.getKdcConfig().getKdcRealm();
156    clientKeytab = new File(keytabDir, clientPrincipal + ".keytab");
157    kdc.createAndExportPrincipals(clientKeytab, clientPrincipal);
158
159    serverPrincipal = "hbase/" + HConstants.LOCALHOST + "@" + kdc.getKdcConfig().getKdcRealm();
160    serverKeytab = new File(keytabDir, serverPrincipal.replace('/', '_') + ".keytab");
161
162    spnegoServerPrincipal = "HTTP/" + HConstants.LOCALHOST + "@" + kdc.getKdcConfig().getKdcRealm();
163    // Add SPNEGO principal to server keytab
164    kdc.createAndExportPrincipals(serverKeytab, serverPrincipal, spnegoServerPrincipal);
165
166    TEST_UTIL.getConfiguration().setBoolean(ThriftServerRunner.USE_HTTP_CONF_KEY, true);
167    addSecurityConfigurations(TEST_UTIL.getConfiguration());
168
169    TestThriftHttpServer.setUpBeforeClass();
170  }
171
172  @AfterClass
173  public static void tearDownAfterClass() throws Exception {
174    TestThriftHttpServer.tearDownAfterClass();
175
176    try {
177      if (null != kdc) {
178        kdc.stop();
179        kdc = null;
180      }
181    } catch (Exception e) {
182      LOG.info("Failed to stop mini KDC", e);
183    }
184  }
185
186  @Override
187  protected void talkToThriftServer(String url, int customHeaderSize) throws Exception {
188    // Close httpClient and THttpClient automatically on any failures
189    try (
190        CloseableHttpClient httpClient = createHttpClient();
191        THttpClient tHttpClient = new THttpClient(url, httpClient)
192    ) {
193      tHttpClient.open();
194      if (customHeaderSize > 0) {
195        StringBuilder sb = new StringBuilder();
196        for (int i = 0; i < customHeaderSize; i++) {
197          sb.append("a");
198        }
199        tHttpClient.setCustomHeader(HttpHeaders.USER_AGENT, sb.toString());
200      }
201
202      TProtocol prot = new TBinaryProtocol(tHttpClient);
203      Hbase.Client client = new Hbase.Client(prot);
204      TestThriftServer.createTestTables(client);
205      TestThriftServer.checkTableList(client);
206      TestThriftServer.dropTestTables(client);
207    }
208  }
209
210  private CloseableHttpClient createHttpClient() throws Exception {
211    final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(clientPrincipal, clientKeytab);
212    final Set<Principal> clientPrincipals = clientSubject.getPrincipals();
213    // Make sure the subject has a principal
214    assertFalse("Found no client principals in the clientSubject.",
215      clientPrincipals.isEmpty());
216
217    // Get a TGT for the subject (might have many, different encryption types). The first should
218    // be the default encryption type.
219    Set<KerberosTicket> privateCredentials =
220        clientSubject.getPrivateCredentials(KerberosTicket.class);
221    assertFalse("Found no private credentials in the clientSubject.",
222      privateCredentials.isEmpty());
223    KerberosTicket tgt = privateCredentials.iterator().next();
224    assertNotNull("No kerberos ticket found.", tgt);
225
226    // The name of the principal
227    final String clientPrincipalName = clientPrincipals.iterator().next().getName();
228
229    return Subject.doAs(clientSubject, new PrivilegedExceptionAction<CloseableHttpClient>() {
230      @Override
231      public CloseableHttpClient run() throws Exception {
232        // Logs in with Kerberos via GSS
233        GSSManager gssManager = GSSManager.getInstance();
234        // jGSS Kerberos login constant
235        Oid oid = new Oid("1.2.840.113554.1.2.2");
236        GSSName gssClient = gssManager.createName(clientPrincipalName, GSSName.NT_USER_NAME);
237        GSSCredential credential = gssManager.createCredential(gssClient,
238            GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY);
239
240        Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create()
241            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true))
242            .build();
243
244        BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
245        credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential));
246
247        return HttpClients.custom()
248            .setDefaultAuthSchemeRegistry(authRegistry)
249            .setDefaultCredentialsProvider(credentialsProvider)
250            .build();
251      }
252    });
253  }
254}