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.util;
019
020import static org.junit.Assert.assertEquals;
021import static org.junit.Assert.assertNotNull;
022import static org.junit.Assert.assertTrue;
023
024import java.security.Key;
025import java.security.SecureRandom;
026import java.util.ArrayList;
027import java.util.List;
028import javax.crypto.spec.SecretKeySpec;
029import org.apache.hadoop.conf.Configuration;
030import org.apache.hadoop.fs.Path;
031import org.apache.hadoop.hbase.HBaseClassTestRule;
032import org.apache.hadoop.hbase.HBaseTestingUtil;
033import org.apache.hadoop.hbase.HConstants;
034import org.apache.hadoop.hbase.TableName;
035import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor;
036import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
037import org.apache.hadoop.hbase.client.Put;
038import org.apache.hadoop.hbase.client.Table;
039import org.apache.hadoop.hbase.client.TableDescriptor;
040import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
041import org.apache.hadoop.hbase.io.crypto.Encryption;
042import org.apache.hadoop.hbase.io.crypto.KeyProviderForTesting;
043import org.apache.hadoop.hbase.io.crypto.aes.AES;
044import org.apache.hadoop.hbase.io.hfile.CacheConfig;
045import org.apache.hadoop.hbase.io.hfile.HFile;
046import org.apache.hadoop.hbase.regionserver.HRegion;
047import org.apache.hadoop.hbase.regionserver.HStore;
048import org.apache.hadoop.hbase.regionserver.HStoreFile;
049import org.apache.hadoop.hbase.regionserver.Region;
050import org.apache.hadoop.hbase.security.EncryptionUtil;
051import org.apache.hadoop.hbase.security.User;
052import org.apache.hadoop.hbase.testclassification.MediumTests;
053import org.apache.hadoop.hbase.testclassification.MiscTests;
054import org.apache.hadoop.hbase.util.hbck.HFileCorruptionChecker;
055import org.apache.hadoop.hbase.util.hbck.HbckTestingUtil;
056import org.junit.After;
057import org.junit.Before;
058import org.junit.ClassRule;
059import org.junit.Test;
060import org.junit.experimental.categories.Category;
061
062@Category({MiscTests.class, MediumTests.class})
063public class TestHBaseFsckEncryption {
064
065  @ClassRule
066  public static final HBaseClassTestRule CLASS_RULE =
067      HBaseClassTestRule.forClass(TestHBaseFsckEncryption.class);
068
069  private static final HBaseTestingUtil TEST_UTIL = new HBaseTestingUtil();
070
071  private Configuration conf;
072  private TableDescriptor tableDescriptor;
073  private Key cfKey;
074
075  @Before
076  public void setUp() throws Exception {
077    conf = TEST_UTIL.getConfiguration();
078    conf.setInt("hfile.format.version", 3);
079    conf.set(HConstants.CRYPTO_KEYPROVIDER_CONF_KEY, KeyProviderForTesting.class.getName());
080    conf.set(HConstants.CRYPTO_MASTERKEY_NAME_CONF_KEY, "hbase");
081
082    // Create the test encryption key
083    SecureRandom rng = new SecureRandom();
084    byte[] keyBytes = new byte[AES.KEY_LENGTH];
085    rng.nextBytes(keyBytes);
086    String algorithm =
087        conf.get(HConstants.CRYPTO_KEY_ALGORITHM_CONF_KEY, HConstants.CIPHER_AES);
088    cfKey = new SecretKeySpec(keyBytes,algorithm);
089
090    // Start the minicluster
091    TEST_UTIL.startMiniCluster(3);
092
093    // Create the table
094    TableDescriptorBuilder tableDescriptorBuilder =
095      TableDescriptorBuilder.newBuilder(TableName.valueOf("default", "TestHBaseFsckEncryption"));
096    ColumnFamilyDescriptor columnFamilyDescriptor =
097      ColumnFamilyDescriptorBuilder
098        .newBuilder(Bytes.toBytes("cf"))
099        .setEncryptionType(algorithm)
100        .setEncryptionKey(EncryptionUtil.wrapKey(conf,
101          conf.get(HConstants.CRYPTO_MASTERKEY_NAME_CONF_KEY, User.getCurrent().getShortName()),
102          cfKey)).build();
103    tableDescriptorBuilder.setColumnFamily(columnFamilyDescriptor);
104    tableDescriptor = tableDescriptorBuilder.build();
105    TEST_UTIL.getAdmin().createTable(tableDescriptor);
106    TEST_UTIL.waitTableAvailable(tableDescriptor.getTableName(), 5000);
107  }
108
109  @After
110  public void tearDown() throws Exception {
111    TEST_UTIL.shutdownMiniCluster();
112  }
113
114  @Test
115  public void testFsckWithEncryption() throws Exception {
116    // Populate the table with some data
117    Table table = TEST_UTIL.getConnection().getTable(tableDescriptor.getTableName());
118    try {
119      byte[] values = { 'A', 'B', 'C', 'D' };
120      for (int i = 0; i < values.length; i++) {
121        for (int j = 0; j < values.length; j++) {
122          Put put = new Put(new byte[] { values[i], values[j] });
123          put.addColumn(Bytes.toBytes("cf"), new byte[]{}, new byte[]{values[i],
124                  values[j]});
125          table.put(put);
126        }
127      }
128    } finally {
129      table.close();
130    }
131    // Flush it
132    TEST_UTIL.getAdmin().flush(tableDescriptor.getTableName());
133
134    // Verify we have encrypted store files on disk
135    final List<Path> paths = findStorefilePaths(tableDescriptor.getTableName());
136    assertTrue(paths.size() > 0);
137    for (Path path: paths) {
138      assertTrue("Store file " + path + " has incorrect key",
139        Bytes.equals(cfKey.getEncoded(), extractHFileKey(path)));
140    }
141
142    // Insure HBck doesn't consider them corrupt
143    HBaseFsck res = HbckTestingUtil.doHFileQuarantine(conf, tableDescriptor.getTableName());
144    assertEquals(0, res.getRetCode());
145    HFileCorruptionChecker hfcc = res.getHFilecorruptionChecker();
146    assertEquals(0, hfcc.getCorrupted().size());
147    assertEquals(0, hfcc.getFailures().size());
148    assertEquals(0, hfcc.getQuarantined().size());
149    assertEquals(0, hfcc.getMissing().size());
150  }
151
152  private List<Path> findStorefilePaths(TableName tableName) throws Exception {
153    List<Path> paths = new ArrayList<>();
154    for (Region region : TEST_UTIL.getRSForFirstRegionInTable(tableName)
155        .getRegions(tableDescriptor.getTableName())) {
156      for (HStore store : ((HRegion) region).getStores()) {
157        for (HStoreFile storefile : store.getStorefiles()) {
158          paths.add(storefile.getPath());
159        }
160      }
161    }
162    return paths;
163  }
164
165  private byte[] extractHFileKey(Path path) throws Exception {
166    HFile.Reader reader = HFile.createReader(TEST_UTIL.getTestFileSystem(), path,
167      new CacheConfig(conf), true, conf);
168    try {
169      Encryption.Context cryptoContext = reader.getFileContext().getEncryptionContext();
170      assertNotNull("Reader has a null crypto context", cryptoContext);
171      Key key = cryptoContext.getKey();
172      assertNotNull("Crypto context has no key", key);
173      return key.getEncoded();
174    } finally {
175      reader.close();
176    }
177  }
178
179}