View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.io.hfile;
19  
20  import static org.junit.Assert.assertEquals;
21  import static org.junit.Assert.assertFalse;
22  import static org.junit.Assert.assertNotNull;
23  import static org.junit.Assert.assertTrue;
24  import static org.junit.Assert.fail;
25  
26  import java.io.DataInputStream;
27  import java.io.DataOutputStream;
28  import java.io.IOException;
29  import java.security.SecureRandom;
30  import java.util.List;
31  import java.util.UUID;
32  
33  import org.apache.commons.logging.Log;
34  import org.apache.commons.logging.LogFactory;
35  import org.apache.hadoop.conf.Configuration;
36  import org.apache.hadoop.fs.FSDataInputStream;
37  import org.apache.hadoop.fs.FSDataOutputStream;
38  import org.apache.hadoop.fs.FileSystem;
39  import org.apache.hadoop.fs.Path;
40  import org.apache.hadoop.hbase.Cell;
41  import org.apache.hadoop.hbase.HBaseTestingUtility;
42  import org.apache.hadoop.hbase.HConstants;
43  import org.apache.hadoop.hbase.KeyValue;
44  import org.apache.hadoop.hbase.KeyValueUtil;
45  import org.apache.hadoop.hbase.testclassification.SmallTests;
46  import org.apache.hadoop.hbase.io.compress.Compression;
47  import org.apache.hadoop.hbase.io.crypto.Cipher;
48  import org.apache.hadoop.hbase.io.crypto.Encryption;
49  import org.apache.hadoop.hbase.io.crypto.KeyProviderForTesting;
50  import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding;
51  import org.apache.hadoop.hbase.util.Bytes;
52  import org.apache.hadoop.hbase.util.RedundantKVGenerator;
53  import org.junit.BeforeClass;
54  import org.junit.Test;
55  import org.junit.experimental.categories.Category;
56  
57  @Category(SmallTests.class)
58  public class TestHFileEncryption {
59    private static final Log LOG = LogFactory.getLog(TestHFileEncryption.class);
60    private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
61    private static final SecureRandom RNG = new SecureRandom();
62  
63    private static FileSystem fs;
64    private static Encryption.Context cryptoContext;
65  
66    @BeforeClass
67    public static void setUp() throws Exception {
68      Configuration conf = TEST_UTIL.getConfiguration();
69      // Disable block cache in this test.
70      conf.setFloat(HConstants.HFILE_BLOCK_CACHE_SIZE_KEY, 0.0f);
71      conf.set(HConstants.CRYPTO_KEYPROVIDER_CONF_KEY, KeyProviderForTesting.class.getName());
72      conf.set(HConstants.CRYPTO_MASTERKEY_NAME_CONF_KEY, "hbase");
73      conf.setInt("hfile.format.version", 3);
74  
75      fs = FileSystem.get(conf);
76  
77      cryptoContext = Encryption.newContext(conf);
78      String algorithm =
79          conf.get(HConstants.CRYPTO_KEY_ALGORITHM_CONF_KEY, HConstants.CIPHER_AES);
80      Cipher aes = Encryption.getCipher(conf, algorithm);
81      assertNotNull(aes);
82      cryptoContext.setCipher(aes);
83      byte[] key = new byte[aes.getKeyLength()];
84      RNG.nextBytes(key);
85      cryptoContext.setKey(key);
86    }
87  
88    private int writeBlock(FSDataOutputStream os, HFileContext fileContext, int size)
89        throws IOException {
90      HFileBlock.Writer hbw = new HFileBlock.Writer(null, fileContext);
91      DataOutputStream dos = hbw.startWriting(BlockType.DATA);
92      for (int j = 0; j < size; j++) {
93        dos.writeInt(j);
94      }
95      hbw.writeHeaderAndData(os);
96      LOG.info("Wrote a block at " + os.getPos() + " with" +
97          " onDiskSizeWithHeader=" + hbw.getOnDiskSizeWithHeader() +
98          " uncompressedSizeWithoutHeader=" + hbw.getOnDiskSizeWithoutHeader() +
99          " uncompressedSizeWithoutHeader=" + hbw.getUncompressedSizeWithoutHeader());
100     return hbw.getOnDiskSizeWithHeader();
101   }
102 
103   private long readAndVerifyBlock(long pos, HFileContext ctx, HFileBlock.FSReaderImpl hbr, int size)
104       throws IOException {
105     HFileBlock b = hbr.readBlockData(pos, -1, false, false);
106     assertEquals(0, HFile.getAndResetChecksumFailuresCount());
107     b.sanityCheck();
108     assertFalse(b.isUnpacked());
109     b = b.unpack(ctx, hbr);
110     LOG.info("Read a block at " + pos + " with" +
111         " onDiskSizeWithHeader=" + b.getOnDiskSizeWithHeader() +
112         " uncompressedSizeWithoutHeader=" + b.getOnDiskSizeWithoutHeader() +
113         " uncompressedSizeWithoutHeader=" + b.getUncompressedSizeWithoutHeader());
114     DataInputStream dis = b.getByteStream();
115     for (int i = 0; i < size; i++) {
116       int read = dis.readInt();
117       if (read != i) {
118         fail("Block data corrupt at element " + i);
119       }
120     }
121     return b.getOnDiskSizeWithHeader();
122   }
123 
124   @Test(timeout=20000)
125   public void testDataBlockEncryption() throws IOException {
126     final int blocks = 10;
127     final int[] blockSizes = new int[blocks];
128     for (int i = 0; i < blocks; i++) {
129       blockSizes[i] = (1024 + RNG.nextInt(1024 * 63)) / Bytes.SIZEOF_INT;
130     }
131     for (Compression.Algorithm compression : TestHFileBlock.COMPRESSION_ALGORITHMS) {
132       Path path = new Path(TEST_UTIL.getDataTestDir(), "block_v3_" + compression + "_AES");
133       LOG.info("testDataBlockEncryption: encryption=AES compression=" + compression);
134       long totalSize = 0;
135       HFileContext fileContext = new HFileContextBuilder()
136         .withCompression(compression)
137         .withEncryptionContext(cryptoContext)
138         .build();
139       FSDataOutputStream os = fs.create(path);
140       try {
141         for (int i = 0; i < blocks; i++) {
142           totalSize += writeBlock(os, fileContext, blockSizes[i]);
143         }
144       } finally {
145         os.close();
146       }
147       FSDataInputStream is = fs.open(path);
148       try {
149         HFileBlock.FSReaderImpl hbr = new HFileBlock.FSReaderImpl(is, totalSize, fileContext);
150         long pos = 0;
151         for (int i = 0; i < blocks; i++) {
152           pos += readAndVerifyBlock(pos, fileContext, hbr, blockSizes[i]);
153         }
154       } finally {
155         is.close();
156       }
157     }
158   }
159 
160   @Test(timeout=20000)
161   public void testHFileEncryptionMetadata() throws Exception {
162     Configuration conf = TEST_UTIL.getConfiguration();
163     CacheConfig cacheConf = new CacheConfig(conf);
164     HFileContext fileContext = new HFileContextBuilder()
165         .withEncryptionContext(cryptoContext)
166         .build();
167 
168     // write a simple encrypted hfile
169     Path path = new Path(TEST_UTIL.getDataTestDir(), "cryptometa.hfile");
170     FSDataOutputStream out = fs.create(path);
171     HFile.Writer writer = HFile.getWriterFactory(conf, cacheConf)
172         .withOutputStream(out)
173         .withFileContext(fileContext)
174         .create();
175     try {
176       KeyValue kv = new KeyValue("foo".getBytes(), "f1".getBytes(), null, "value".getBytes());
177       writer.append(kv);
178     } finally {
179       writer.close();
180       out.close();
181     }
182 
183     // read it back in and validate correct crypto metadata
184     HFile.Reader reader = HFile.createReader(fs, path, cacheConf, conf);
185     try {
186       reader.loadFileInfo();
187       FixedFileTrailer trailer = reader.getTrailer();
188       assertNotNull(trailer.getEncryptionKey());
189       Encryption.Context readerContext = reader.getFileContext().getEncryptionContext();
190       assertEquals(readerContext.getCipher().getName(), cryptoContext.getCipher().getName());
191       assertTrue(Bytes.equals(readerContext.getKeyBytes(),
192           cryptoContext.getKeyBytes()));
193     } finally {
194       reader.close();
195     }
196   }
197 
198   @Test(timeout=6000000)
199   public void testHFileEncryption() throws Exception {
200     // Create 1000 random test KVs
201     RedundantKVGenerator generator = new RedundantKVGenerator();
202     List<KeyValue> testKvs = generator.generateTestKeyValues(1000);
203 
204     // Iterate through data block encoding and compression combinations
205     Configuration conf = TEST_UTIL.getConfiguration();
206     CacheConfig cacheConf = new CacheConfig(conf);
207     for (DataBlockEncoding encoding: DataBlockEncoding.values()) {
208       for (Compression.Algorithm compression: TestHFileBlock.COMPRESSION_ALGORITHMS) {
209         HFileContext fileContext = new HFileContextBuilder()
210           .withBlockSize(4096) // small blocks
211           .withEncryptionContext(cryptoContext)
212           .withCompression(compression)
213           .withDataBlockEncoding(encoding)
214           .build();
215         // write a new test HFile
216         LOG.info("Writing with " + fileContext);
217         Path path = new Path(TEST_UTIL.getDataTestDir(), UUID.randomUUID().toString() + ".hfile");
218         FSDataOutputStream out = fs.create(path);
219         HFile.Writer writer = HFile.getWriterFactory(conf, cacheConf)
220           .withOutputStream(out)
221           .withFileContext(fileContext)
222           .create();
223         for (KeyValue kv: testKvs) {
224           writer.append(kv);
225         }
226         writer.close();
227         out.close();
228 
229         // read it back in
230         LOG.info("Reading with " + fileContext);
231         HFile.Reader reader = HFile.createReader(fs, path, cacheConf, conf);
232         reader.loadFileInfo();
233         FixedFileTrailer trailer = reader.getTrailer();
234         assertNotNull(trailer.getEncryptionKey());
235         HFileScanner scanner = reader.getScanner(false, false);
236         assertTrue("Initial seekTo failed", scanner.seekTo());
237         int i = 0;
238         do {
239           Cell kv = scanner.getKeyValue();
240           assertTrue("Read back an unexpected or invalid KV",
241               testKvs.contains(KeyValueUtil.ensureKeyValue(kv)));
242           i++;
243         } while (scanner.next());
244         reader.close();
245 
246         assertEquals("Did not read back as many KVs as written", i, testKvs.size());
247 
248         // Test random seeks with pread
249         LOG.info("Random seeking with " + fileContext);
250         reader = HFile.createReader(fs, path, cacheConf, conf);
251         scanner = reader.getScanner(false, true);
252         assertTrue("Initial seekTo failed", scanner.seekTo());
253         for (i = 0; i < 100; i++) {
254           KeyValue kv = testKvs.get(RNG.nextInt(testKvs.size()));
255           assertEquals("Unable to find KV as expected: " + kv, scanner.seekTo(kv), 0);
256         }
257         reader.close();
258       }
259     }
260   }
261 
262 }