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.apache.hadoop.hbase.thrift.Constants.THRIFT_SUPPORT_PROXYUSER_KEY;
021import static org.junit.Assert.assertFalse;
022import static org.junit.Assert.assertNotNull;
023import java.io.File;
024import java.net.InetAddress;
025import java.nio.ByteBuffer;
026import java.nio.file.Paths;
027import java.security.Principal;
028import java.security.PrivilegedExceptionAction;
029import java.util.List;
030import java.util.Set;
031import java.util.function.Supplier;
032import java.util.stream.Collectors;
033import javax.security.auth.Subject;
034import javax.security.auth.kerberos.KerberosTicket;
035import org.apache.hadoop.conf.Configuration;
036import org.apache.hadoop.hbase.HBaseClassTestRule;
037import org.apache.hadoop.hbase.HBaseTestingUtility;
038import org.apache.hadoop.hbase.security.HBaseKerberosUtils;
039import org.apache.hadoop.hbase.testclassification.ClientTests;
040import org.apache.hadoop.hbase.testclassification.LargeTests;
041import org.apache.hadoop.hbase.thrift.generated.Hbase;
042import org.apache.hadoop.hbase.util.Bytes;
043import org.apache.hadoop.hbase.util.SimpleKdcServerUtil;
044import org.apache.hadoop.security.authentication.util.KerberosName;
045import org.apache.http.HttpHeaders;
046import org.apache.http.auth.AuthSchemeProvider;
047import org.apache.http.auth.AuthScope;
048import org.apache.http.auth.KerberosCredentials;
049import org.apache.http.client.config.AuthSchemes;
050import org.apache.http.config.Lookup;
051import org.apache.http.config.RegistryBuilder;
052import org.apache.http.impl.auth.SPNegoSchemeFactory;
053import org.apache.http.impl.client.BasicCredentialsProvider;
054import org.apache.http.impl.client.CloseableHttpClient;
055import org.apache.http.impl.client.HttpClients;
056import org.apache.kerby.kerberos.kerb.client.JaasKrbUtil;
057import org.apache.kerby.kerberos.kerb.server.SimpleKdcServer;
058import org.apache.thrift.protocol.TBinaryProtocol;
059import org.apache.thrift.protocol.TProtocol;
060import org.apache.thrift.transport.THttpClient;
061import org.ietf.jgss.GSSCredential;
062import org.ietf.jgss.GSSManager;
063import org.ietf.jgss.GSSName;
064import org.ietf.jgss.Oid;
065import org.junit.AfterClass;
066import org.junit.Assert;
067import org.junit.BeforeClass;
068import org.junit.ClassRule;
069import org.junit.Test;
070import org.junit.experimental.categories.Category;
071import org.slf4j.Logger;
072import org.slf4j.LoggerFactory;
073
074/**
075 * Start the HBase Thrift HTTP server on a random port through the command-line
076 * interface and talk to it from client side with SPNEGO security enabled.
077 */
078@Category({ClientTests.class, LargeTests.class})
079public class TestThriftSpnegoHttpServer extends TestThriftHttpServer {
080  @ClassRule
081  public static final HBaseClassTestRule CLASS_RULE =
082    HBaseClassTestRule.forClass(TestThriftSpnegoHttpServer.class);
083
084  private static final Logger LOG =
085    LoggerFactory.getLogger(TestThriftSpnegoHttpServer.class);
086
087  private static SimpleKdcServer kdc;
088  private static File serverKeytab;
089  private static File spnegoServerKeytab;
090  private static File clientKeytab;
091
092  private static String clientPrincipal;
093  private static String serverPrincipal;
094  private static String spnegoServerPrincipal;
095
096  private static void addSecurityConfigurations(Configuration conf) {
097    KerberosName.setRules("DEFAULT");
098
099    HBaseKerberosUtils.setKeytabFileForTesting(serverKeytab.getAbsolutePath());
100
101    conf.setBoolean(THRIFT_SUPPORT_PROXYUSER_KEY, true);
102    conf.setBoolean(Constants.USE_HTTP_CONF_KEY, true);
103
104    conf.set(Constants.THRIFT_KERBEROS_PRINCIPAL_KEY, serverPrincipal);
105    conf.set(Constants.THRIFT_KEYTAB_FILE_KEY, serverKeytab.getAbsolutePath());
106
107    HBaseKerberosUtils.setSecuredConfiguration(conf, serverPrincipal, spnegoServerPrincipal);
108    conf.set("hadoop.proxyuser.hbase.hosts", "*");
109    conf.set("hadoop.proxyuser.hbase.groups", "*");
110    conf.set(Constants.THRIFT_SPNEGO_PRINCIPAL_KEY, spnegoServerPrincipal);
111    conf.set(Constants.THRIFT_SPNEGO_KEYTAB_FILE_KEY, spnegoServerKeytab.getAbsolutePath());
112  }
113
114  @BeforeClass
115  public static void setUpBeforeClass() throws Exception {
116    kdc = SimpleKdcServerUtil.
117      getRunningSimpleKdcServer(new File(TEST_UTIL.getDataTestDir().toString()),
118        HBaseTestingUtility::randomFreePort);
119    File keytabDir = Paths.get(TEST_UTIL.getRandomDir().toString()).toAbsolutePath().toFile();
120    Assert.assertTrue(keytabDir.mkdirs());
121
122    clientPrincipal = "client@" + kdc.getKdcConfig().getKdcRealm();
123    clientKeytab = new File(keytabDir, clientPrincipal + ".keytab");
124    kdc.createAndExportPrincipals(clientKeytab, clientPrincipal);
125
126    String hostname = InetAddress.getLoopbackAddress().getHostName();
127    serverPrincipal = "hbase/" + hostname + "@" + kdc.getKdcConfig().getKdcRealm();
128    serverKeytab = new File(keytabDir, serverPrincipal.replace('/', '_') + ".keytab");
129
130    // Setup separate SPNEGO keytab
131    spnegoServerPrincipal = "HTTP/" + hostname + "@" + kdc.getKdcConfig().getKdcRealm();
132    spnegoServerKeytab = new File(keytabDir, spnegoServerPrincipal.replace('/', '_') + ".keytab");
133    kdc.createAndExportPrincipals(spnegoServerKeytab, spnegoServerPrincipal);
134    kdc.createAndExportPrincipals(serverKeytab, serverPrincipal);
135
136    TEST_UTIL.getConfiguration().setBoolean(Constants.USE_HTTP_CONF_KEY, true);
137    addSecurityConfigurations(TEST_UTIL.getConfiguration());
138
139    TestThriftHttpServer.setUpBeforeClass();
140  }
141
142  @Override protected Supplier<ThriftServer> getThriftServerSupplier() {
143    return () -> new ThriftServer(TEST_UTIL.getConfiguration());
144  }
145
146  @AfterClass
147  public static void tearDownAfterClass() throws Exception {
148    TestThriftHttpServer.tearDownAfterClass();
149
150    try {
151      if (null != kdc) {
152        kdc.stop();
153        kdc = null;
154      }
155    } catch (Exception e) {
156      LOG.info("Failed to stop mini KDC", e);
157    }
158  }
159
160  /**
161   * Block call through to this method. It is a messy test that fails because of bad config
162   * and then succeeds only the first attempt adds a table which the second attempt doesn't
163   * want to be in place to succeed. Let the super impl of this test be responsible for
164   * verifying we fail if bad header size.
165   */
166  @org.junit.Ignore
167  @Test
168  @Override public void testRunThriftServerWithHeaderBufferLength() throws Exception {
169    super.testRunThriftServerWithHeaderBufferLength();
170  }
171
172  @Override
173  protected void talkToThriftServer(String url, int customHeaderSize) throws Exception {
174    // Close httpClient and THttpClient automatically on any failures
175    try (
176        CloseableHttpClient httpClient = createHttpClient();
177        THttpClient tHttpClient = new THttpClient(url, httpClient)
178    ) {
179      tHttpClient.open();
180      if (customHeaderSize > 0) {
181        StringBuilder sb = new StringBuilder();
182        for (int i = 0; i < customHeaderSize; i++) {
183          sb.append("a");
184        }
185        tHttpClient.setCustomHeader(HttpHeaders.USER_AGENT, sb.toString());
186      }
187
188      TProtocol prot = new TBinaryProtocol(tHttpClient);
189      Hbase.Client client = new Hbase.Client(prot);
190      List<ByteBuffer> bbs = client.getTableNames();
191      LOG.info("PRE-EXISTING {}", bbs.stream().
192        map(b -> Bytes.toString(b.array())).collect(Collectors.joining(",")));
193      if (!bbs.isEmpty()) {
194        for (ByteBuffer bb: bbs) {
195          client.disableTable(bb);
196          client.deleteTable(bb);
197        }
198      }
199      TestThriftServer.createTestTables(client);
200      TestThriftServer.checkTableList(client);
201      TestThriftServer.dropTestTables(client);
202    }
203  }
204
205  private CloseableHttpClient createHttpClient() throws Exception {
206    final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(clientPrincipal, clientKeytab);
207    final Set<Principal> clientPrincipals = clientSubject.getPrincipals();
208    // Make sure the subject has a principal
209    assertFalse("Found no client principals in the clientSubject.",
210      clientPrincipals.isEmpty());
211
212    // Get a TGT for the subject (might have many, different encryption types). The first should
213    // be the default encryption type.
214    Set<KerberosTicket> privateCredentials =
215        clientSubject.getPrivateCredentials(KerberosTicket.class);
216    assertFalse("Found no private credentials in the clientSubject.",
217      privateCredentials.isEmpty());
218    KerberosTicket tgt = privateCredentials.iterator().next();
219    assertNotNull("No kerberos ticket found.", tgt);
220
221    // The name of the principal
222    final String clientPrincipalName = clientPrincipals.iterator().next().getName();
223
224    return Subject.doAs(clientSubject, (PrivilegedExceptionAction<CloseableHttpClient>) () -> {
225      // Logs in with Kerberos via GSS
226      GSSManager gssManager = GSSManager.getInstance();
227      // jGSS Kerberos login constant
228      Oid oid = new Oid("1.2.840.113554.1.2.2");
229      GSSName gssClient = gssManager.createName(clientPrincipalName, GSSName.NT_USER_NAME);
230      GSSCredential credential = gssManager.createCredential(gssClient,
231          GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY);
232
233      Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create()
234          .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true))
235          .build();
236
237      BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
238      credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential));
239
240      return HttpClients.custom()
241          .setDefaultAuthSchemeRegistry(authRegistry)
242          .setDefaultCredentialsProvider(credentialsProvider)
243          .build();
244    });
245  }
246}