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