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.http; 019 020import static org.junit.Assert.assertEquals; 021import static org.junit.Assert.assertFalse; 022import static org.junit.Assert.assertNotNull; 023 024import java.io.File; 025import java.io.IOException; 026import java.net.HttpURLConnection; 027import java.net.URL; 028import java.security.Principal; 029import java.security.PrivilegedExceptionAction; 030import java.util.Set; 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.HBaseCommonTestingUtility; 036import org.apache.hadoop.hbase.http.TestHttpServer.EchoServlet; 037import org.apache.hadoop.hbase.http.resource.JerseyResource; 038import org.apache.hadoop.hbase.testclassification.MiscTests; 039import org.apache.hadoop.hbase.testclassification.SmallTests; 040import org.apache.hadoop.hbase.util.SimpleKdcServerUtil; 041import org.apache.hadoop.security.authentication.util.KerberosName; 042import org.apache.http.HttpHost; 043import org.apache.http.HttpResponse; 044import org.apache.http.auth.AuthSchemeProvider; 045import org.apache.http.auth.AuthScope; 046import org.apache.http.auth.KerberosCredentials; 047import org.apache.http.client.HttpClient; 048import org.apache.http.client.config.AuthSchemes; 049import org.apache.http.client.methods.HttpGet; 050import org.apache.http.client.protocol.HttpClientContext; 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.HttpClients; 056import org.apache.http.util.EntityUtils; 057import org.apache.kerby.kerberos.kerb.KrbException; 058import org.apache.kerby.kerberos.kerb.client.JaasKrbUtil; 059import org.apache.kerby.kerberos.kerb.server.SimpleKdcServer; 060import org.ietf.jgss.GSSCredential; 061import org.ietf.jgss.GSSManager; 062import org.ietf.jgss.GSSName; 063import org.ietf.jgss.Oid; 064import org.junit.AfterClass; 065import org.junit.BeforeClass; 066import org.junit.ClassRule; 067import org.junit.Test; 068import org.junit.experimental.categories.Category; 069import org.slf4j.Logger; 070import org.slf4j.LoggerFactory; 071 072/** 073 * Test class for SPNEGO authentication on the HttpServer. Uses Kerby's MiniKDC and Apache 074 * HttpComponents to verify that a simple Servlet is reachable via SPNEGO and unreachable w/o. 075 */ 076@Category({ MiscTests.class, SmallTests.class }) 077public class TestSpnegoHttpServer extends HttpServerFunctionalTest { 078 @ClassRule 079 public static final HBaseClassTestRule CLASS_RULE = 080 HBaseClassTestRule.forClass(TestSpnegoHttpServer.class); 081 082 private static final Logger LOG = LoggerFactory.getLogger(TestSpnegoHttpServer.class); 083 private static final String KDC_SERVER_HOST = "localhost"; 084 private static final String CLIENT_PRINCIPAL = "client"; 085 086 private static HttpServer server; 087 private static URL baseUrl; 088 private static SimpleKdcServer kdc; 089 private static File infoServerKeytab; 090 private static File clientKeytab; 091 092 @BeforeClass 093 public static void setupServer() throws Exception { 094 Configuration conf = new Configuration(); 095 HBaseCommonTestingUtility htu = new HBaseCommonTestingUtility(conf); 096 097 final String serverPrincipal = "HTTP/" + KDC_SERVER_HOST; 098 099 kdc = SimpleKdcServerUtil.getRunningSimpleKdcServer(new File(htu.getDataTestDir().toString()), 100 HBaseCommonTestingUtility::randomFreePort); 101 File keytabDir = new File(htu.getDataTestDir("keytabs").toString()); 102 if (keytabDir.exists()) { 103 deleteRecursively(keytabDir); 104 } 105 keytabDir.mkdirs(); 106 107 infoServerKeytab = new File(keytabDir, serverPrincipal.replace('/', '_') + ".keytab"); 108 clientKeytab = new File(keytabDir, CLIENT_PRINCIPAL + ".keytab"); 109 110 setupUser(kdc, clientKeytab, CLIENT_PRINCIPAL); 111 setupUser(kdc, infoServerKeytab, serverPrincipal); 112 113 buildSpnegoConfiguration(conf, serverPrincipal, infoServerKeytab); 114 115 server = createTestServerWithSecurity(conf); 116 server.addUnprivilegedServlet("echo", "/echo", EchoServlet.class); 117 server.addJerseyResourcePackage(JerseyResource.class.getPackage().getName(), "/jersey/*"); 118 server.start(); 119 baseUrl = getServerURL(server); 120 121 LOG.info("HTTP server started: " + baseUrl); 122 } 123 124 @AfterClass 125 public static void stopServer() throws Exception { 126 try { 127 if (null != server) { 128 server.stop(); 129 } 130 } catch (Exception e) { 131 LOG.info("Failed to stop info server", e); 132 } 133 try { 134 if (null != kdc) { 135 kdc.stop(); 136 } 137 } catch (Exception e) { 138 LOG.info("Failed to stop mini KDC", e); 139 } 140 } 141 142 private static void setupUser(SimpleKdcServer kdc, File keytab, String principal) 143 throws KrbException { 144 kdc.createPrincipal(principal); 145 kdc.exportPrincipal(principal, keytab); 146 } 147 148 private static Configuration buildSpnegoConfiguration(Configuration conf, String serverPrincipal, 149 File serverKeytab) { 150 KerberosName.setRules("DEFAULT"); 151 152 conf.setInt(HttpServer.HTTP_MAX_THREADS, TestHttpServer.MAX_THREADS); 153 154 // Enable Kerberos (pre-req) 155 conf.set("hbase.security.authentication", "kerberos"); 156 conf.set(HttpServer.HTTP_UI_AUTHENTICATION, "kerberos"); 157 conf.set(HttpServer.HTTP_SPNEGO_AUTHENTICATION_PRINCIPAL_KEY, serverPrincipal); 158 conf.set(HttpServer.HTTP_SPNEGO_AUTHENTICATION_KEYTAB_KEY, serverKeytab.getAbsolutePath()); 159 160 return conf; 161 } 162 163 @Test 164 public void testUnauthorizedClientsDisallowed() throws IOException { 165 URL url = new URL(getServerURL(server), "/echo?a=b"); 166 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 167 assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, conn.getResponseCode()); 168 } 169 170 @Test 171 public void testAllowedClient() throws Exception { 172 // Create the subject for the client 173 final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(CLIENT_PRINCIPAL, clientKeytab); 174 final Set<Principal> clientPrincipals = clientSubject.getPrincipals(); 175 // Make sure the subject has a principal 176 assertFalse(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(privateCredentials.isEmpty()); 183 KerberosTicket tgt = privateCredentials.iterator().next(); 184 assertNotNull(tgt); 185 186 // The name of the principal 187 final String principalName = clientPrincipals.iterator().next().getName(); 188 189 // Run this code, logged in as the subject (the client) 190 HttpResponse resp = Subject.doAs(clientSubject, new PrivilegedExceptionAction<HttpResponse>() { 191 @Override 192 public HttpResponse run() throws Exception { 193 // Logs in with Kerberos via GSS 194 GSSManager gssManager = GSSManager.getInstance(); 195 // jGSS Kerberos login constant 196 Oid oid = new Oid("1.2.840.113554.1.2.2"); 197 GSSName gssClient = gssManager.createName(principalName, GSSName.NT_USER_NAME); 198 GSSCredential credential = gssManager.createCredential(gssClient, 199 GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY); 200 201 HttpClientContext context = HttpClientContext.create(); 202 Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider> create() 203 .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true)).build(); 204 205 HttpClient client = HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry).build(); 206 BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); 207 credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential)); 208 209 URL url = new URL(getServerURL(server), "/echo?a=b"); 210 context.setTargetHost(new HttpHost(url.getHost(), url.getPort())); 211 context.setCredentialsProvider(credentialsProvider); 212 context.setAuthSchemeRegistry(authRegistry); 213 214 HttpGet get = new HttpGet(url.toURI()); 215 return client.execute(get, context); 216 } 217 }); 218 219 assertNotNull(resp); 220 assertEquals(HttpURLConnection.HTTP_OK, resp.getStatusLine().getStatusCode()); 221 assertEquals("a:b", EntityUtils.toString(resp.getEntity()).trim()); 222 } 223 224 @Test(expected = IllegalArgumentException.class) 225 public void testMissingConfigurationThrowsException() throws Exception { 226 Configuration conf = new Configuration(); 227 conf.setInt(HttpServer.HTTP_MAX_THREADS, TestHttpServer.MAX_THREADS); 228 // Enable Kerberos (pre-req) 229 conf.set("hbase.security.authentication", "kerberos"); 230 // Intentionally skip keytab and principal 231 232 HttpServer customServer = createTestServerWithSecurity(conf); 233 customServer.addUnprivilegedServlet("echo", "/echo", EchoServlet.class); 234 customServer.addJerseyResourcePackage(JerseyResource.class.getPackage().getName(), "/jersey/*"); 235 customServer.start(); 236 } 237}