View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.security;
20  
21  import static org.apache.hadoop.hbase.security.HBaseKerberosUtils.getKeytabFileForTesting;
22  import static org.apache.hadoop.hbase.security.HBaseKerberosUtils.getPrincipalForTesting;
23  import static org.apache.hadoop.hbase.security.HBaseKerberosUtils.getSecuredConfiguration;
24  import static org.junit.Assert.assertEquals;
25  import static org.junit.Assert.assertNotSame;
26  import static org.junit.Assert.assertSame;
27  
28  import java.io.File;
29  import java.io.IOException;
30  import java.net.InetSocketAddress;
31  import java.util.ArrayList;
32  import java.util.List;
33  import java.util.Properties;
34  import java.util.concurrent.ThreadLocalRandom;
35  
36  import com.google.protobuf.RpcController;
37  import com.google.protobuf.ServiceException;
38  import org.apache.hadoop.conf.Configuration;
39  import org.apache.hadoop.fs.CommonConfigurationKeys;
40  import org.apache.hadoop.hbase.Cell;
41  import org.apache.hadoop.hbase.CellScanner;
42  import org.apache.hadoop.hbase.CellUtil;
43  import org.apache.hadoop.hbase.HBaseTestingUtility;
44  import org.apache.hadoop.hbase.HConstants;
45  import org.apache.hadoop.hbase.ServerName;
46  import org.apache.hadoop.hbase.ipc.AsyncRpcClient;
47  import org.apache.hadoop.hbase.ipc.FifoRpcScheduler;
48  import org.apache.hadoop.hbase.ipc.PayloadCarryingRpcController;
49  import org.apache.hadoop.hbase.ipc.RpcClient;
50  import org.apache.hadoop.hbase.ipc.RpcClientFactory;
51  import org.apache.hadoop.hbase.ipc.RpcClientImpl;
52  import org.apache.hadoop.hbase.ipc.RpcServer;
53  import org.apache.hadoop.hbase.ipc.RpcServerInterface;
54  import org.apache.hadoop.hbase.ipc.protobuf.generated.TestProtos;
55  import org.apache.hadoop.hbase.ipc.protobuf.generated.TestRpcServiceProtos;
56  import org.apache.hadoop.hbase.testclassification.SmallTests;
57  import org.apache.hadoop.minikdc.MiniKdc;
58  import org.apache.hadoop.security.UserGroupInformation;
59  import org.apache.hadoop.security.UserGroupInformation.AuthenticationMethod;
60  import org.junit.AfterClass;
61  import org.junit.BeforeClass;
62  import org.junit.Test;
63  import org.junit.experimental.categories.Category;
64  import org.mockito.Mockito;
65  
66  import com.google.common.collect.Lists;
67  import com.google.protobuf.BlockingRpcChannel;
68  import com.google.protobuf.BlockingService;
69  
70  @Category(SmallTests.class)
71  public class TestSecureRPC {
72  
73    private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
74  
75    private static final File KEYTAB_FILE = new File(TEST_UTIL.getDataTestDir("keytab").toUri()
76        .getPath());
77  
78    static final BlockingService SERVICE =
79        TestRpcServiceProtos.TestProtobufRpcProto.newReflectiveBlockingService(
80            new TestRpcServiceProtos.TestProtobufRpcProto.BlockingInterface() {
81  
82              @Override
83              public TestProtos.EmptyResponseProto ping(RpcController controller,
84                                                        TestProtos.EmptyRequestProto request)
85                  throws ServiceException {
86                return null;
87              }
88  
89              @Override
90              public TestProtos.EmptyResponseProto error(RpcController controller,
91                                                         TestProtos.EmptyRequestProto request)
92                  throws ServiceException {
93                return null;
94              }
95  
96              @Override
97              public TestProtos.EchoResponseProto echo(RpcController controller,
98                                                       TestProtos.EchoRequestProto request)
99                  throws ServiceException {
100               if (controller instanceof PayloadCarryingRpcController) {
101                 PayloadCarryingRpcController pcrc = (PayloadCarryingRpcController) controller;
102                 // If cells, scan them to check we are able to iterate what we were given and since
103                 // this is
104                 // an echo, just put them back on the controller creating a new block. Tests our
105                 // block
106                 // building.
107                 CellScanner cellScanner = pcrc.cellScanner();
108                 List<Cell> list = null;
109                 if (cellScanner != null) {
110                   list = new ArrayList<Cell>();
111                   try {
112                     while (cellScanner.advance()) {
113                       list.add(cellScanner.current());
114                     }
115                   } catch (IOException e) {
116                     throw new ServiceException(e);
117                   }
118                 }
119                 cellScanner = CellUtil.createCellScanner(list);
120                 ((PayloadCarryingRpcController) controller).setCellScanner(cellScanner);
121               }
122               return TestProtos.EchoResponseProto.newBuilder()
123                   .setMessage(request.getMessage()).build();
124             }
125           });
126 
127   private static MiniKdc KDC;
128 
129   private static String HOST = "localhost";
130 
131   private static String PRINCIPAL;
132 
133   @BeforeClass
134   public static void setUp() throws Exception {
135     KDC = TEST_UTIL.setupMiniKdc(KEYTAB_FILE);
136     PRINCIPAL = "hbase/" + HOST;
137     KDC.createPrincipal(KEYTAB_FILE, PRINCIPAL);
138     HBaseKerberosUtils.setPrincipalForTesting(PRINCIPAL + "@" + KDC.getRealm());
139   }
140 
141   @AfterClass
142   public static void tearDown() throws IOException {
143     if (KDC != null) {
144       KDC.stop();
145     }
146     TEST_UTIL.cleanupTestDir();
147   }
148 
149   @Test
150   public void testRpc() throws Exception {
151     testRpcCallWithEnabledKerberosSaslAuth(RpcClientImpl.class);
152   }
153 
154   @Test
155   public void testRpcWithInsecureFallback() throws Exception {
156     testRpcFallbackToSimpleAuth(RpcClientImpl.class);
157   }
158 
159   @Test
160   public void testAsyncRpc() throws Exception {
161     testRpcCallWithEnabledKerberosSaslAuth(AsyncRpcClient.class);
162   }
163 
164   @Test
165   public void testAsyncRpcWithInsecureFallback() throws Exception {
166     testRpcFallbackToSimpleAuth(AsyncRpcClient.class);
167   }
168 
169   private void testRpcCallWithEnabledKerberosSaslAuth(Class<? extends RpcClient> rpcImplClass)
170       throws Exception {
171     String krbKeytab = getKeytabFileForTesting();
172     String krbPrincipal = getPrincipalForTesting();
173 
174     UserGroupInformation ugi = loginKerberosPrincipal(krbKeytab, krbPrincipal);
175     UserGroupInformation ugi2 = UserGroupInformation.getCurrentUser();
176 
177     // check that the login user is okay:
178     assertSame(ugi, ugi2);
179     assertEquals(AuthenticationMethod.KERBEROS, ugi.getAuthenticationMethod());
180     assertEquals(krbPrincipal, ugi.getUserName());
181 
182     Configuration clientConf = getSecuredConfiguration();
183     callRpcService(rpcImplClass, User.create(ugi2), clientConf, false);
184   }
185 
186   private UserGroupInformation loginKerberosPrincipal(String krbKeytab, String krbPrincipal)
187       throws Exception {
188     Configuration cnf = new Configuration();
189     cnf.set(CommonConfigurationKeys.HADOOP_SECURITY_AUTHENTICATION, "kerberos");
190     UserGroupInformation.setConfiguration(cnf);
191     UserGroupInformation.loginUserFromKeytab(krbPrincipal, krbKeytab);
192     return UserGroupInformation.getLoginUser();
193   }
194 
195   private void callRpcService(Class<? extends RpcClient> rpcImplClass, User clientUser,
196                               Configuration clientConf, boolean allowInsecureFallback)
197       throws Exception {
198     Configuration clientConfCopy = new Configuration(clientConf);
199     clientConfCopy.set(RpcClientFactory.CUSTOM_RPC_CLIENT_IMPL_CONF_KEY, rpcImplClass.getName());
200 
201     Configuration conf = getSecuredConfiguration();
202     conf.setBoolean(RpcServer.FALLBACK_TO_INSECURE_CLIENT_AUTH, allowInsecureFallback);
203 
204     SecurityInfo securityInfoMock = Mockito.mock(SecurityInfo.class);
205     Mockito.when(securityInfoMock.getServerPrincipal())
206         .thenReturn(HBaseKerberosUtils.KRB_PRINCIPAL);
207     SecurityInfo.addInfo("TestProtobufRpcProto", securityInfoMock);
208 
209     InetSocketAddress isa = new InetSocketAddress(HOST, 0);
210 
211     RpcServerInterface rpcServer =
212         new RpcServer(null, "AbstractTestSecureIPC",
213             Lists.newArrayList(new RpcServer.BlockingServiceAndInterface(SERVICE, null)), isa,
214             conf, new FifoRpcScheduler(conf, 1));
215     rpcServer.start();
216     try (RpcClient rpcClient = RpcClientFactory.createClient(clientConf,
217         HConstants.DEFAULT_CLUSTER_ID.toString())) {
218       InetSocketAddress address = rpcServer.getListenerAddress();
219       if (address == null) {
220         throw new IOException("Listener channel is closed");
221       }
222       BlockingRpcChannel channel =
223           rpcClient.createBlockingRpcChannel(
224 
225             ServerName.valueOf(address.getHostName(), address.getPort(),
226             System.currentTimeMillis()), clientUser, 5000);
227       TestRpcServiceProtos.TestProtobufRpcProto.BlockingInterface stub =
228           TestRpcServiceProtos.TestProtobufRpcProto.newBlockingStub(channel);
229       List<String> results = new ArrayList<String>();
230       TestThread th1 = new TestThread(stub, results);
231       th1.start();
232       th1.join();
233 
234     } finally {
235       rpcServer.stop();
236     }
237   }
238 
239   public void testRpcFallbackToSimpleAuth(Class<? extends RpcClient> rpcImplClass) throws Exception {
240     String krbKeytab = getKeytabFileForTesting();
241     String krbPrincipal = getPrincipalForTesting();
242 
243     UserGroupInformation ugi = loginKerberosPrincipal(krbKeytab, krbPrincipal);
244     assertEquals(AuthenticationMethod.KERBEROS, ugi.getAuthenticationMethod());
245     assertEquals(krbPrincipal, ugi.getUserName());
246 
247     String clientUsername = "testuser";
248     UserGroupInformation clientUgi = UserGroupInformation.createUserForTesting(clientUsername,
249         new String[]{clientUsername});
250 
251     // check that the client user is insecure
252     assertNotSame(ugi, clientUgi);
253     assertEquals(AuthenticationMethod.SIMPLE, clientUgi.getAuthenticationMethod());
254     assertEquals(clientUsername, clientUgi.getUserName());
255 
256     Configuration clientConf = new Configuration();
257     clientConf.set(User.HBASE_SECURITY_CONF_KEY, "simple");
258     callRpcService(rpcImplClass, User.create(clientUgi), clientConf, true);
259   }
260 
261   public static class TestThread extends Thread {
262       private final TestRpcServiceProtos.TestProtobufRpcProto.BlockingInterface stub;
263 
264       private final List<String> results;
265 
266           public TestThread(TestRpcServiceProtos.TestProtobufRpcProto.BlockingInterface stub, List<String> results) {
267           this.stub = stub;
268           this.results = results;
269         }
270 
271           @Override
272       public void run() {
273           String result;
274           try {
275               result = stub.echo(null, TestProtos.EchoRequestProto.newBuilder().setMessage(String.valueOf(
276                   ThreadLocalRandom.current().nextInt())).build()).getMessage();
277             } catch (ServiceException e) {
278               throw new RuntimeException(e);
279             }
280           if (results != null) {
281               synchronized (results) {
282                   results.add(result);
283                 }
284             }
285         }
286     }
287 }