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.net.InetAddress; 026import java.nio.ByteBuffer; 027import java.nio.file.Paths; 028import java.security.Principal; 029import java.security.PrivilegedExceptionAction; 030import java.util.List; 031import java.util.Set; 032import java.util.function.Supplier; 033import java.util.stream.Collectors; 034import javax.security.auth.Subject; 035import javax.security.auth.kerberos.KerberosTicket; 036import org.apache.hadoop.conf.Configuration; 037import org.apache.hadoop.hbase.HBaseClassTestRule; 038import org.apache.hadoop.hbase.HBaseTestingUtility; 039import org.apache.hadoop.hbase.security.HBaseKerberosUtils; 040import org.apache.hadoop.hbase.testclassification.ClientTests; 041import org.apache.hadoop.hbase.testclassification.LargeTests; 042import org.apache.hadoop.hbase.thrift.generated.Hbase; 043import org.apache.hadoop.hbase.util.Bytes; 044import org.apache.hadoop.hbase.util.SimpleKdcServerUtil; 045import org.apache.hadoop.security.authentication.util.KerberosName; 046import org.apache.http.HttpHeaders; 047import org.apache.http.auth.AuthSchemeProvider; 048import org.apache.http.auth.AuthScope; 049import org.apache.http.auth.KerberosCredentials; 050import org.apache.http.client.config.AuthSchemes; 051import org.apache.http.config.Lookup; 052import org.apache.http.config.RegistryBuilder; 053import org.apache.http.impl.auth.SPNegoSchemeFactory; 054import org.apache.http.impl.client.BasicCredentialsProvider; 055import org.apache.http.impl.client.CloseableHttpClient; 056import org.apache.http.impl.client.HttpClients; 057import org.apache.kerby.kerberos.kerb.client.JaasKrbUtil; 058import org.apache.kerby.kerberos.kerb.server.SimpleKdcServer; 059import org.apache.thrift.protocol.TBinaryProtocol; 060import org.apache.thrift.protocol.TProtocol; 061import org.apache.thrift.transport.THttpClient; 062import org.ietf.jgss.GSSCredential; 063import org.ietf.jgss.GSSManager; 064import org.ietf.jgss.GSSName; 065import org.ietf.jgss.Oid; 066import org.junit.AfterClass; 067import org.junit.Assert; 068import org.junit.BeforeClass; 069import org.junit.ClassRule; 070import org.junit.Test; 071import org.junit.experimental.categories.Category; 072import org.slf4j.Logger; 073import org.slf4j.LoggerFactory; 074 075/** 076 * Start the HBase Thrift HTTP server on a random port through the command-line interface and talk 077 * to it from client side with SPNEGO security enabled. 078 */ 079@Category({ ClientTests.class, LargeTests.class }) 080public class TestThriftSpnegoHttpServer extends TestThriftHttpServer { 081 @ClassRule 082 public static final HBaseClassTestRule CLASS_RULE = 083 HBaseClassTestRule.forClass(TestThriftSpnegoHttpServer.class); 084 085 private static final Logger LOG = 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.getRunningSimpleKdcServer( 117 new File(TEST_UTIL.getDataTestDir().toString()), HBaseTestingUtility::randomFreePort); 118 File keytabDir = Paths.get(TEST_UTIL.getRandomDir().toString()).toAbsolutePath().toFile(); 119 Assert.assertTrue(keytabDir.mkdirs()); 120 121 clientPrincipal = "client@" + kdc.getKdcConfig().getKdcRealm(); 122 clientKeytab = new File(keytabDir, clientPrincipal + ".keytab"); 123 kdc.createAndExportPrincipals(clientKeytab, clientPrincipal); 124 125 String hostname = InetAddress.getLoopbackAddress().getHostName(); 126 serverPrincipal = "hbase/" + hostname + "@" + kdc.getKdcConfig().getKdcRealm(); 127 serverKeytab = new File(keytabDir, serverPrincipal.replace('/', '_') + ".keytab"); 128 129 // Setup separate SPNEGO keytab 130 spnegoServerPrincipal = "HTTP/" + hostname + "@" + kdc.getKdcConfig().getKdcRealm(); 131 spnegoServerKeytab = new File(keytabDir, spnegoServerPrincipal.replace('/', '_') + ".keytab"); 132 kdc.createAndExportPrincipals(spnegoServerKeytab, spnegoServerPrincipal); 133 kdc.createAndExportPrincipals(serverKeytab, serverPrincipal); 134 135 TEST_UTIL.getConfiguration().setBoolean(Constants.USE_HTTP_CONF_KEY, true); 136 addSecurityConfigurations(TEST_UTIL.getConfiguration()); 137 138 TestThriftHttpServer.setUpBeforeClass(); 139 } 140 141 @Override 142 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 and then 162 * succeeds only the first attempt adds a table which the second attempt doesn't want to be in 163 * place to succeed. Let the super impl of this test be responsible for verifying we fail if bad 164 * header size. 165 */ 166 @org.junit.Ignore 167 @Test 168 @Override 169 public void testRunThriftServerWithHeaderBufferLength() throws Exception { 170 super.testRunThriftServerWithHeaderBufferLength(); 171 } 172 173 @Override 174 protected void talkToThriftServer(String url, int customHeaderSize) throws Exception { 175 // Close httpClient and THttpClient automatically on any failures 176 try (CloseableHttpClient httpClient = createHttpClient(); 177 THttpClient tHttpClient = new THttpClient(url, httpClient)) { 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 List<ByteBuffer> bbs = client.getTableNames(); 190 LOG.info("PRE-EXISTING {}", 191 bbs.stream().map(b -> Bytes.toString(b.array())).collect(Collectors.joining(","))); 192 if (!bbs.isEmpty()) { 193 for (ByteBuffer bb : bbs) { 194 client.disableTable(bb); 195 client.deleteTable(bb); 196 } 197 } 198 TestThriftServer.createTestTables(client); 199 TestThriftServer.checkTableList(client); 200 TestThriftServer.dropTestTables(client); 201 } 202 } 203 204 private CloseableHttpClient createHttpClient() throws Exception { 205 final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(clientPrincipal, clientKeytab); 206 final Set<Principal> clientPrincipals = clientSubject.getPrincipals(); 207 // Make sure the subject has a principal 208 assertFalse("Found no client principals in the clientSubject.", clientPrincipals.isEmpty()); 209 210 // Get a TGT for the subject (might have many, different encryption types). The first should 211 // be the default encryption type. 212 Set<KerberosTicket> privateCredentials = 213 clientSubject.getPrivateCredentials(KerberosTicket.class); 214 assertFalse("Found no private credentials in the clientSubject.", privateCredentials.isEmpty()); 215 KerberosTicket tgt = privateCredentials.iterator().next(); 216 assertNotNull("No kerberos ticket found.", tgt); 217 218 // The name of the principal 219 final String clientPrincipalName = clientPrincipals.iterator().next().getName(); 220 221 return Subject.doAs(clientSubject, (PrivilegedExceptionAction<CloseableHttpClient>) () -> { 222 // Logs in with Kerberos via GSS 223 GSSManager gssManager = GSSManager.getInstance(); 224 // jGSS Kerberos login constant 225 Oid oid = new Oid("1.2.840.113554.1.2.2"); 226 GSSName gssClient = gssManager.createName(clientPrincipalName, GSSName.NT_USER_NAME); 227 GSSCredential credential = gssManager.createCredential(gssClient, 228 GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY); 229 230 Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider> create() 231 .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true)).build(); 232 233 BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); 234 credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential)); 235 236 return HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry) 237 .setDefaultCredentialsProvider(credentialsProvider).build(); 238 }); 239 } 240}