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