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;
023
024import java.io.File;
025import java.nio.file.Paths;
026import java.security.Principal;
027import java.security.PrivilegedExceptionAction;
028import java.util.Set;
029
030import javax.security.auth.Subject;
031import javax.security.auth.kerberos.KerberosTicket;
032
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.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
119    conf.setBoolean(THRIFT_SUPPORT_PROXYUSER_KEY, true);
120    conf.setBoolean(Constants.USE_HTTP_CONF_KEY, true);
121
122    conf.set(Constants.THRIFT_KERBEROS_PRINCIPAL_KEY, serverPrincipal);
123    conf.set(Constants.THRIFT_KEYTAB_FILE_KEY, serverKeytab.getAbsolutePath());
124
125    HBaseKerberosUtils.setSecuredConfiguration(conf, spnegoServerPrincipal,
126      spnegoServerPrincipal);
127    conf.set("hadoop.proxyuser.HTTP.hosts", "*");
128    conf.set("hadoop.proxyuser.HTTP.groups", "*");
129    conf.set(Constants.THRIFT_KERBEROS_PRINCIPAL_KEY, spnegoServerPrincipal);
130  }
131
132  @BeforeClass
133  public static void setUpBeforeClass() throws Exception {
134    kdc = buildMiniKdc();
135    kdc.start();
136
137    File keytabDir = Paths.get(TEST_UTIL.getRandomDir().toString()).toAbsolutePath().toFile();
138    keytabDir.mkdirs();
139
140    clientPrincipal = "client@" + kdc.getKdcConfig().getKdcRealm();
141    clientKeytab = new File(keytabDir, clientPrincipal + ".keytab");
142    kdc.createAndExportPrincipals(clientKeytab, clientPrincipal);
143
144    serverPrincipal = "hbase/" + HConstants.LOCALHOST + "@" + kdc.getKdcConfig().getKdcRealm();
145    serverKeytab = new File(keytabDir, serverPrincipal.replace('/', '_') + ".keytab");
146
147    spnegoServerPrincipal = "HTTP/" + HConstants.LOCALHOST + "@" + kdc.getKdcConfig().getKdcRealm();
148    // Add SPNEGO principal to server keytab
149    kdc.createAndExportPrincipals(serverKeytab, serverPrincipal, spnegoServerPrincipal);
150
151    TEST_UTIL.getConfiguration().setBoolean(Constants.USE_HTTP_CONF_KEY, true);
152    addSecurityConfigurations(TEST_UTIL.getConfiguration());
153
154    TestThriftHttpServer.setUpBeforeClass();
155  }
156
157  @AfterClass
158  public static void tearDownAfterClass() throws Exception {
159    TestThriftHttpServer.tearDownAfterClass();
160
161    try {
162      if (null != kdc) {
163        kdc.stop();
164        kdc = null;
165      }
166    } catch (Exception e) {
167      LOG.info("Failed to stop mini KDC", e);
168    }
169  }
170
171  @Override
172  protected void talkToThriftServer(String url, int customHeaderSize) throws Exception {
173    // Close httpClient and THttpClient automatically on any failures
174    try (
175      CloseableHttpClient httpClient = createHttpClient();
176      THttpClient tHttpClient = new THttpClient(url, httpClient)
177    ) {
178      tHttpClient.open();
179      if (customHeaderSize > 0) {
180        StringBuilder sb = new StringBuilder();
181        for (int i = 0; i < customHeaderSize; i++) {
182          sb.append("a");
183        }
184        tHttpClient.setCustomHeader(HttpHeaders.USER_AGENT, sb.toString());
185      }
186
187      TProtocol prot = new TBinaryProtocol(tHttpClient);
188      Hbase.Client client = new Hbase.Client(prot);
189      TestThriftServer.createTestTables(client);
190      TestThriftServer.checkTableList(client);
191      TestThriftServer.dropTestTables(client);
192    }
193  }
194
195  private CloseableHttpClient createHttpClient() throws Exception {
196    final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(clientPrincipal, clientKeytab);
197    final Set<Principal> clientPrincipals = clientSubject.getPrincipals();
198    // Make sure the subject has a principal
199    assertFalse("Found no client principals in the clientSubject.",
200      clientPrincipals.isEmpty());
201
202    // Get a TGT for the subject (might have many, different encryption types). The first should
203    // be the default encryption type.
204    Set<KerberosTicket> privateCredentials =
205      clientSubject.getPrivateCredentials(KerberosTicket.class);
206    assertFalse("Found no private credentials in the clientSubject.",
207      privateCredentials.isEmpty());
208    KerberosTicket tgt = privateCredentials.iterator().next();
209    assertNotNull("No kerberos ticket found.", tgt);
210
211    // The name of the principal
212    final String clientPrincipalName = clientPrincipals.iterator().next().getName();
213
214    return Subject.doAs(clientSubject, (PrivilegedExceptionAction<CloseableHttpClient>) () -> {
215      // Logs in with Kerberos via GSS
216      GSSManager gssManager = GSSManager.getInstance();
217      // jGSS Kerberos login constant
218      Oid oid = new Oid("1.2.840.113554.1.2.2");
219      GSSName gssClient = gssManager.createName(clientPrincipalName, GSSName.NT_USER_NAME);
220      GSSCredential credential = gssManager.createCredential(gssClient,
221        GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY);
222
223      Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create()
224        .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true))
225        .build();
226
227      BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
228      credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential));
229
230      return HttpClients.custom()
231        .setDefaultAuthSchemeRegistry(authRegistry)
232        .setDefaultCredentialsProvider(credentialsProvider)
233        .build();
234    });
235  }
236}