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.coprocessor; 019 020import static org.junit.Assert.assertEquals; 021 022import com.google.protobuf.ServiceException; 023import java.io.File; 024import java.io.IOException; 025import java.security.PrivilegedExceptionAction; 026import java.util.Arrays; 027import java.util.LinkedList; 028import java.util.List; 029import java.util.Map; 030import java.util.Properties; 031import org.apache.hadoop.conf.Configuration; 032import org.apache.hadoop.fs.FileSystem; 033import org.apache.hadoop.fs.Path; 034import org.apache.hadoop.fs.permission.FsAction; 035import org.apache.hadoop.fs.permission.FsPermission; 036import org.apache.hadoop.hbase.HBaseClassTestRule; 037import org.apache.hadoop.hbase.HBaseTestingUtility; 038import org.apache.hadoop.hbase.TableName; 039import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder; 040import org.apache.hadoop.hbase.client.Connection; 041import org.apache.hadoop.hbase.client.ConnectionFactory; 042import org.apache.hadoop.hbase.client.Put; 043import org.apache.hadoop.hbase.client.Result; 044import org.apache.hadoop.hbase.client.ResultScanner; 045import org.apache.hadoop.hbase.client.Scan; 046import org.apache.hadoop.hbase.client.Table; 047import org.apache.hadoop.hbase.client.TableDescriptor; 048import org.apache.hadoop.hbase.client.TableDescriptorBuilder; 049import org.apache.hadoop.hbase.http.ssl.KeyStoreTestUtil; 050import org.apache.hadoop.hbase.mapreduce.ExportUtils; 051import org.apache.hadoop.hbase.mapreduce.Import; 052import org.apache.hadoop.hbase.protobuf.generated.VisibilityLabelsProtos; 053import org.apache.hadoop.hbase.security.HBaseKerberosUtils; 054import org.apache.hadoop.hbase.security.HadoopSecurityEnabledUserProviderForTesting; 055import org.apache.hadoop.hbase.security.User; 056import org.apache.hadoop.hbase.security.UserProvider; 057import org.apache.hadoop.hbase.security.access.AccessControlConstants; 058import org.apache.hadoop.hbase.security.access.AccessControlLists; 059import org.apache.hadoop.hbase.security.access.Permission; 060import org.apache.hadoop.hbase.security.access.SecureTestUtil; 061import org.apache.hadoop.hbase.security.access.SecureTestUtil.AccessTestAction; 062import org.apache.hadoop.hbase.security.visibility.Authorizations; 063import org.apache.hadoop.hbase.security.visibility.CellVisibility; 064import org.apache.hadoop.hbase.security.visibility.VisibilityClient; 065import org.apache.hadoop.hbase.security.visibility.VisibilityConstants; 066import org.apache.hadoop.hbase.security.visibility.VisibilityTestUtil; 067import org.apache.hadoop.hbase.testclassification.MediumTests; 068import org.apache.hadoop.hbase.util.Bytes; 069import org.apache.hadoop.hbase.util.Pair; 070import org.apache.hadoop.hdfs.DFSConfigKeys; 071import org.apache.hadoop.http.HttpConfig; 072import org.apache.hadoop.minikdc.MiniKdc; 073import org.apache.hadoop.security.UserGroupInformation; 074import org.apache.hadoop.util.ToolRunner; 075import org.apache.hadoop.yarn.conf.YarnConfiguration; 076import org.junit.After; 077import org.junit.AfterClass; 078import org.junit.Before; 079import org.junit.BeforeClass; 080import org.junit.ClassRule; 081import org.junit.Rule; 082import org.junit.Test; 083import org.junit.experimental.categories.Category; 084import org.junit.rules.TestName; 085import org.slf4j.Logger; 086import org.slf4j.LoggerFactory; 087 088@Category({MediumTests.class}) 089public class TestSecureExport { 090 091 @ClassRule 092 public static final HBaseClassTestRule CLASS_RULE = 093 HBaseClassTestRule.forClass(TestSecureExport.class); 094 095 private static final Logger LOG = LoggerFactory.getLogger(TestSecureExport.class); 096 private static final HBaseTestingUtility UTIL = new HBaseTestingUtility(); 097 private static MiniKdc KDC; 098 private static final File KEYTAB_FILE = new File(UTIL.getDataTestDir("keytab").toUri().getPath()); 099 private static String USERNAME; 100 private static String SERVER_PRINCIPAL; 101 private static String HTTP_PRINCIPAL; 102 private static final String FAMILYA_STRING = "fma"; 103 private static final String FAMILYB_STRING = "fma"; 104 private static final byte[] FAMILYA = Bytes.toBytes(FAMILYA_STRING); 105 private static final byte[] FAMILYB = Bytes.toBytes(FAMILYB_STRING); 106 private static final byte[] ROW1 = Bytes.toBytes("row1"); 107 private static final byte[] ROW2 = Bytes.toBytes("row2"); 108 private static final byte[] ROW3 = Bytes.toBytes("row3"); 109 private static final byte[] QUAL = Bytes.toBytes("qual"); 110 private static final String LOCALHOST = "localhost"; 111 private static final long NOW = System.currentTimeMillis(); 112 // user granted with all global permission 113 private static final String USER_ADMIN = "admin"; 114 // user is table owner. will have all permissions on table 115 private static final String USER_OWNER = "owner"; 116 // user with rx permissions. 117 private static final String USER_RX = "rxuser"; 118 // user with exe-only permissions. 119 private static final String USER_XO = "xouser"; 120 // user with read-only permissions. 121 private static final String USER_RO = "rouser"; 122 // user with no permissions 123 private static final String USER_NONE = "noneuser"; 124 private static final String PRIVATE = "private"; 125 private static final String CONFIDENTIAL = "confidential"; 126 private static final String SECRET = "secret"; 127 private static final String TOPSECRET = "topsecret"; 128 @Rule 129 public final TestName name = new TestName(); 130 private static void setUpKdcServer() throws Exception { 131 Properties conf = MiniKdc.createConf(); 132 conf.put(MiniKdc.DEBUG, true); 133 File kdcFile = new File(UTIL.getDataTestDir("kdc").toUri().getPath()); 134 KDC = new MiniKdc(conf, kdcFile); 135 KDC.start(); 136 USERNAME = UserGroupInformation.getLoginUser().getShortUserName(); 137 SERVER_PRINCIPAL = USERNAME + "/" + LOCALHOST; 138 HTTP_PRINCIPAL = "HTTP/" + LOCALHOST; 139 KDC.createPrincipal(KEYTAB_FILE, 140 SERVER_PRINCIPAL, 141 HTTP_PRINCIPAL, 142 USER_ADMIN + "/" + LOCALHOST, 143 USER_OWNER + "/" + LOCALHOST, 144 USER_RX + "/" + LOCALHOST, 145 USER_RO + "/" + LOCALHOST, 146 USER_XO + "/" + LOCALHOST, 147 USER_NONE + "/" + LOCALHOST); 148 } 149 private static User getUserByLogin(final String user) throws IOException { 150 return User.create(UserGroupInformation.loginUserFromKeytabAndReturnUGI(getPrinciple(user), KEYTAB_FILE.getAbsolutePath())); 151 } 152 private static String getPrinciple(final String user) { 153 return user + "/" + LOCALHOST + "@" + KDC.getRealm(); 154 } 155 private static void setUpClusterKdc() throws Exception { 156 HBaseKerberosUtils.setKeytabFileForTesting(KEYTAB_FILE.getAbsolutePath()); 157 HBaseKerberosUtils.setPrincipalForTesting(SERVER_PRINCIPAL + "@" + KDC.getRealm()); 158 HBaseKerberosUtils.setSecuredConfiguration(UTIL.getConfiguration()); 159 // if we drop support for hadoop-2.4.0 and hadoop-2.4.1, 160 // the following key should be changed. 161 // 1) DFS_NAMENODE_USER_NAME_KEY -> DFS_NAMENODE_KERBEROS_PRINCIPAL_KEY 162 // 2) DFS_DATANODE_USER_NAME_KEY -> DFS_DATANODE_KERBEROS_PRINCIPAL_KEY 163 UTIL.getConfiguration().set(DFSConfigKeys.DFS_NAMENODE_USER_NAME_KEY, SERVER_PRINCIPAL + "@" + KDC.getRealm()); 164 UTIL.getConfiguration().set(DFSConfigKeys.DFS_DATANODE_USER_NAME_KEY, SERVER_PRINCIPAL + "@" + KDC.getRealm()); 165 UTIL.getConfiguration().set(DFSConfigKeys.DFS_NAMENODE_KEYTAB_FILE_KEY, KEYTAB_FILE.getAbsolutePath()); 166 UTIL.getConfiguration().set(DFSConfigKeys.DFS_DATANODE_KEYTAB_FILE_KEY, KEYTAB_FILE.getAbsolutePath()); 167 // set yarn principal 168 UTIL.getConfiguration().set(YarnConfiguration.RM_PRINCIPAL, SERVER_PRINCIPAL + "@" + KDC.getRealm()); 169 UTIL.getConfiguration().set(YarnConfiguration.NM_PRINCIPAL, SERVER_PRINCIPAL + "@" + KDC.getRealm()); 170 UTIL.getConfiguration().set(DFSConfigKeys.DFS_WEB_AUTHENTICATION_KERBEROS_PRINCIPAL_KEY, HTTP_PRINCIPAL + "@" + KDC.getRealm()); 171 UTIL.getConfiguration().setBoolean(DFSConfigKeys.DFS_BLOCK_ACCESS_TOKEN_ENABLE_KEY, true); 172 UTIL.getConfiguration().set(DFSConfigKeys.DFS_HTTP_POLICY_KEY, HttpConfig.Policy.HTTPS_ONLY.name()); 173 UTIL.getConfiguration().set(DFSConfigKeys.DFS_NAMENODE_HTTPS_ADDRESS_KEY, LOCALHOST + ":0"); 174 UTIL.getConfiguration().set(DFSConfigKeys.DFS_DATANODE_HTTPS_ADDRESS_KEY, LOCALHOST + ":0"); 175 176 File keystoresDir = new File(UTIL.getDataTestDir("keystore").toUri().getPath()); 177 keystoresDir.mkdirs(); 178 String sslConfDir = KeyStoreTestUtil.getClasspathDir(TestSecureExport.class); 179 KeyStoreTestUtil.setupSSLConfig(keystoresDir.getAbsolutePath(), sslConfDir, UTIL.getConfiguration(), false); 180 181 UTIL.getConfiguration().setBoolean("ignore.secure.ports.for.testing", true); 182 UserGroupInformation.setConfiguration(UTIL.getConfiguration()); 183 UTIL.getConfiguration().set(CoprocessorHost.REGION_COPROCESSOR_CONF_KEY, UTIL.getConfiguration().get( 184 CoprocessorHost.REGION_COPROCESSOR_CONF_KEY) + "," + Export.class.getName()); 185 } 186 private static void addLabels(final Configuration conf, final List<String> users, final List<String> labels) throws Exception { 187 PrivilegedExceptionAction<VisibilityLabelsProtos.VisibilityLabelsResponse> action 188 = () -> { 189 try (Connection conn = ConnectionFactory.createConnection(conf)) { 190 VisibilityClient.addLabels(conn, labels.toArray(new String[labels.size()])); 191 for (String user : users) { 192 VisibilityClient.setAuths(conn, labels.toArray(new String[labels.size()]), user); 193 } 194 } catch (Throwable t) { 195 throw new IOException(t); 196 } 197 return null; 198 }; 199 getUserByLogin(USER_ADMIN).runAs(action); 200 } 201 202 @Before 203 public void announce() { 204 LOG.info("Running " + name.getMethodName()); 205 } 206 207 @After 208 public void cleanup() throws IOException { 209 } 210 private static void clearOutput(Path path) throws IOException { 211 FileSystem fs = path.getFileSystem(UTIL.getConfiguration()); 212 if (fs.exists(path)) { 213 assertEquals(true, fs.delete(path, true)); 214 } 215 } 216 /** 217 * Sets the security firstly for getting the correct default realm. 218 * @throws Exception 219 */ 220 @BeforeClass 221 public static void beforeClass() throws Exception { 222 UserProvider.setUserProviderForTesting(UTIL.getConfiguration(), HadoopSecurityEnabledUserProviderForTesting.class); 223 setUpKdcServer(); 224 SecureTestUtil.enableSecurity(UTIL.getConfiguration()); 225 UTIL.getConfiguration().setBoolean(AccessControlConstants.EXEC_PERMISSION_CHECKS_KEY, true); 226 VisibilityTestUtil.enableVisiblityLabels(UTIL.getConfiguration()); 227 SecureTestUtil.verifyConfiguration(UTIL.getConfiguration()); 228 setUpClusterKdc(); 229 UTIL.startMiniCluster(); 230 UTIL.waitUntilAllRegionsAssigned(AccessControlLists.ACL_TABLE_NAME); 231 UTIL.waitUntilAllRegionsAssigned(VisibilityConstants.LABELS_TABLE_NAME); 232 UTIL.waitTableEnabled(AccessControlLists.ACL_TABLE_NAME, 50000); 233 UTIL.waitTableEnabled(VisibilityConstants.LABELS_TABLE_NAME, 50000); 234 SecureTestUtil.grantGlobal(UTIL, USER_ADMIN, 235 Permission.Action.ADMIN, 236 Permission.Action.CREATE, 237 Permission.Action.EXEC, 238 Permission.Action.READ, 239 Permission.Action.WRITE); 240 addLabels(UTIL.getConfiguration(), Arrays.asList(USER_OWNER), 241 Arrays.asList(PRIVATE, CONFIDENTIAL, SECRET, TOPSECRET)); 242 } 243 244 @AfterClass 245 public static void afterClass() throws Exception { 246 if (KDC != null) { 247 KDC.stop(); 248 } 249 UTIL.shutdownMiniCluster(); 250 } 251 252 /** 253 * Test the ExportEndpoint's access levels. The {@link Export} test is ignored 254 * since the access exceptions cannot be collected from the mappers. 255 * 256 * @throws java.io.IOException 257 */ 258 @Test 259 public void testAccessCase() throws IOException, Throwable { 260 final String exportTable = name.getMethodName(); 261 TableDescriptor exportHtd = TableDescriptorBuilder 262 .newBuilder(TableName.valueOf(name.getMethodName())) 263 .setColumnFamily(ColumnFamilyDescriptorBuilder.of(FAMILYA)) 264 .setOwnerString(USER_OWNER) 265 .build(); 266 SecureTestUtil.createTable(UTIL, exportHtd, new byte[][]{Bytes.toBytes("s")}); 267 SecureTestUtil.grantOnTable(UTIL, USER_RO, 268 TableName.valueOf(exportTable), null, null, 269 Permission.Action.READ); 270 SecureTestUtil.grantOnTable(UTIL, USER_RX, 271 TableName.valueOf(exportTable), null, null, 272 Permission.Action.READ, 273 Permission.Action.EXEC); 274 SecureTestUtil.grantOnTable(UTIL, USER_XO, 275 TableName.valueOf(exportTable), null, null, 276 Permission.Action.EXEC); 277 assertEquals(4, AccessControlLists.getTablePermissions(UTIL.getConfiguration(), 278 TableName.valueOf(exportTable)).size()); 279 AccessTestAction putAction = () -> { 280 Put p = new Put(ROW1); 281 p.addColumn(FAMILYA, Bytes.toBytes("qual_0"), NOW, QUAL); 282 p.addColumn(FAMILYA, Bytes.toBytes("qual_1"), NOW, QUAL); 283 try (Connection conn = ConnectionFactory.createConnection(UTIL.getConfiguration()); 284 Table t = conn.getTable(TableName.valueOf(exportTable))) { 285 t.put(p); 286 } 287 return null; 288 }; 289 // no hdfs access. 290 SecureTestUtil.verifyAllowed(putAction, 291 getUserByLogin(USER_ADMIN), 292 getUserByLogin(USER_OWNER)); 293 SecureTestUtil.verifyDenied(putAction, 294 getUserByLogin(USER_RO), 295 getUserByLogin(USER_XO), 296 getUserByLogin(USER_RX), 297 getUserByLogin(USER_NONE)); 298 299 final FileSystem fs = UTIL.getDFSCluster().getFileSystem(); 300 final Path openDir = fs.makeQualified(new Path("testAccessCase")); 301 fs.mkdirs(openDir); 302 fs.setPermission(openDir, new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.ALL)); 303 final Path output = fs.makeQualified(new Path(openDir, "output")); 304 AccessTestAction exportAction = () -> { 305 try { 306 String[] args = new String[]{exportTable, output.toString()}; 307 Map<byte[], Export.Response> result 308 = Export.run(new Configuration(UTIL.getConfiguration()), args); 309 long rowCount = 0; 310 long cellCount = 0; 311 for (Export.Response r : result.values()) { 312 rowCount += r.getRowCount(); 313 cellCount += r.getCellCount(); 314 } 315 assertEquals(1, rowCount); 316 assertEquals(2, cellCount); 317 return null; 318 } catch (ServiceException | IOException ex) { 319 throw ex; 320 } catch (Throwable ex) { 321 LOG.error(ex.toString(), ex); 322 throw new Exception(ex); 323 } finally { 324 clearOutput(output); 325 } 326 }; 327 SecureTestUtil.verifyDenied(exportAction, 328 getUserByLogin(USER_RO), 329 getUserByLogin(USER_XO), 330 getUserByLogin(USER_NONE)); 331 SecureTestUtil.verifyAllowed(exportAction, 332 getUserByLogin(USER_ADMIN), 333 getUserByLogin(USER_OWNER), 334 getUserByLogin(USER_RX)); 335 AccessTestAction deleteAction = () -> { 336 UTIL.deleteTable(TableName.valueOf(exportTable)); 337 return null; 338 }; 339 SecureTestUtil.verifyAllowed(deleteAction, getUserByLogin(USER_OWNER)); 340 fs.delete(openDir, true); 341 } 342 @Test 343 public void testVisibilityLabels() throws IOException, Throwable { 344 final String exportTable = name.getMethodName() + "_export"; 345 final String importTable = name.getMethodName() + "_import"; 346 final TableDescriptor exportHtd = TableDescriptorBuilder.newBuilder(TableName.valueOf(exportTable)) 347 .setColumnFamily(ColumnFamilyDescriptorBuilder.of(FAMILYA)) 348 .setOwnerString(USER_OWNER) 349 .build(); 350 SecureTestUtil.createTable(UTIL, exportHtd, new byte[][]{Bytes.toBytes("s")}); 351 AccessTestAction putAction = () -> { 352 Put p1 = new Put(ROW1); 353 p1.addColumn(FAMILYA, QUAL, NOW, QUAL); 354 p1.setCellVisibility(new CellVisibility(SECRET)); 355 Put p2 = new Put(ROW2); 356 p2.addColumn(FAMILYA, QUAL, NOW, QUAL); 357 p2.setCellVisibility(new CellVisibility(PRIVATE + " & " + CONFIDENTIAL)); 358 Put p3 = new Put(ROW3); 359 p3.addColumn(FAMILYA, QUAL, NOW, QUAL); 360 p3.setCellVisibility(new CellVisibility("!" + CONFIDENTIAL + " & " + TOPSECRET)); 361 try (Connection conn = ConnectionFactory.createConnection(UTIL.getConfiguration()); 362 Table t = conn.getTable(TableName.valueOf(exportTable))) { 363 t.put(p1); 364 t.put(p2); 365 t.put(p3); 366 } 367 return null; 368 }; 369 SecureTestUtil.verifyAllowed(putAction, getUserByLogin(USER_OWNER)); 370 List<Pair<List<String>, Integer>> labelsAndRowCounts = new LinkedList<>(); 371 labelsAndRowCounts.add(new Pair<>(Arrays.asList(SECRET), 1)); 372 labelsAndRowCounts.add(new Pair<>(Arrays.asList(PRIVATE, CONFIDENTIAL), 1)); 373 labelsAndRowCounts.add(new Pair<>(Arrays.asList(TOPSECRET), 1)); 374 labelsAndRowCounts.add(new Pair<>(Arrays.asList(TOPSECRET, CONFIDENTIAL), 0)); 375 labelsAndRowCounts.add(new Pair<>(Arrays.asList(TOPSECRET, CONFIDENTIAL, PRIVATE, SECRET), 2)); 376 for (final Pair<List<String>, Integer> labelsAndRowCount : labelsAndRowCounts) { 377 final List<String> labels = labelsAndRowCount.getFirst(); 378 final int rowCount = labelsAndRowCount.getSecond(); 379 //create a open permission directory. 380 final Path openDir = new Path("testAccessCase"); 381 final FileSystem fs = openDir.getFileSystem(UTIL.getConfiguration()); 382 fs.mkdirs(openDir); 383 fs.setPermission(openDir, new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.ALL)); 384 final Path output = fs.makeQualified(new Path(openDir, "output")); 385 AccessTestAction exportAction = () -> { 386 StringBuilder buf = new StringBuilder(); 387 labels.forEach(v -> buf.append(v).append(",")); 388 buf.deleteCharAt(buf.length() - 1); 389 try { 390 String[] args = new String[]{ 391 "-D " + ExportUtils.EXPORT_VISIBILITY_LABELS + "=" + buf.toString(), 392 exportTable, 393 output.toString(),}; 394 Export.run(new Configuration(UTIL.getConfiguration()), args); 395 return null; 396 } catch (ServiceException | IOException ex) { 397 throw ex; 398 } catch (Throwable ex) { 399 throw new Exception(ex); 400 } 401 }; 402 SecureTestUtil.verifyAllowed(exportAction, getUserByLogin(USER_OWNER)); 403 final TableDescriptor importHtd = TableDescriptorBuilder.newBuilder(TableName.valueOf(importTable)) 404 .setColumnFamily(ColumnFamilyDescriptorBuilder.of(FAMILYB)) 405 .setOwnerString(USER_OWNER) 406 .build(); 407 SecureTestUtil.createTable(UTIL, importHtd, new byte[][]{Bytes.toBytes("s")}); 408 AccessTestAction importAction = () -> { 409 String[] args = new String[]{ 410 "-D" + Import.CF_RENAME_PROP + "=" + FAMILYA_STRING + ":" + FAMILYB_STRING, 411 importTable, 412 output.toString() 413 }; 414 assertEquals(0, ToolRunner.run(new Configuration(UTIL.getConfiguration()), new Import(), args)); 415 return null; 416 }; 417 SecureTestUtil.verifyAllowed(importAction, getUserByLogin(USER_OWNER)); 418 AccessTestAction scanAction = () -> { 419 Scan scan = new Scan(); 420 scan.setAuthorizations(new Authorizations(labels)); 421 try (Connection conn = ConnectionFactory.createConnection(UTIL.getConfiguration()); 422 Table table = conn.getTable(importHtd.getTableName()); 423 ResultScanner scanner = table.getScanner(scan)) { 424 int count = 0; 425 for (Result r : scanner) { 426 ++count; 427 } 428 assertEquals(rowCount, count); 429 } 430 return null; 431 }; 432 SecureTestUtil.verifyAllowed(scanAction, getUserByLogin(USER_OWNER)); 433 AccessTestAction deleteAction = () -> { 434 UTIL.deleteTable(importHtd.getTableName()); 435 return null; 436 }; 437 SecureTestUtil.verifyAllowed(deleteAction, getUserByLogin(USER_OWNER)); 438 clearOutput(output); 439 } 440 AccessTestAction deleteAction = () -> { 441 UTIL.deleteTable(exportHtd.getTableName()); 442 return null; 443 }; 444 SecureTestUtil.verifyAllowed(deleteAction, getUserByLogin(USER_OWNER)); 445 } 446}