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