1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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 Cipher aes = Encryption.getCipher(conf, "AES");
72 assertNotNull(aes);
73 cryptoContext.setCipher(aes);
74 byte[] key = new byte[aes.getKeyLength()];
75 RNG.nextBytes(key);
76 cryptoContext.setKey(key);
77 }
78
79 private int writeBlock(FSDataOutputStream os, HFileContext fileContext, int size)
80 throws IOException {
81 HFileBlock.Writer hbw = new HFileBlock.Writer(null, fileContext);
82 DataOutputStream dos = hbw.startWriting(BlockType.DATA);
83 for (int j = 0; j < size; j++) {
84 dos.writeInt(j);
85 }
86 hbw.writeHeaderAndData(os);
87 LOG.info("Wrote a block at " + os.getPos() + " with" +
88 " onDiskSizeWithHeader=" + hbw.getOnDiskSizeWithHeader() +
89 " uncompressedSizeWithoutHeader=" + hbw.getOnDiskSizeWithoutHeader() +
90 " uncompressedSizeWithoutHeader=" + hbw.getUncompressedSizeWithoutHeader());
91 return hbw.getOnDiskSizeWithHeader();
92 }
93
94 private long readAndVerifyBlock(long pos, HFileContext ctx, HFileBlock.FSReaderV2 hbr, int size)
95 throws IOException {
96 HFileBlock b = hbr.readBlockData(pos, -1, -1, false);
97 assertEquals(0, HFile.getChecksumFailuresCount());
98 b.sanityCheck();
99 assertFalse(b.isUnpacked());
100 b = b.unpack(ctx, hbr);
101 LOG.info("Read a block at " + pos + " with" +
102 " onDiskSizeWithHeader=" + b.getOnDiskSizeWithHeader() +
103 " uncompressedSizeWithoutHeader=" + b.getOnDiskSizeWithoutHeader() +
104 " uncompressedSizeWithoutHeader=" + b.getUncompressedSizeWithoutHeader());
105 DataInputStream dis = b.getByteStream();
106 for (int i = 0; i < size; i++) {
107 int read = dis.readInt();
108 if (read != i) {
109 fail("Block data corrupt at element " + i);
110 }
111 }
112 return b.getOnDiskSizeWithHeader();
113 }
114
115 @Test(timeout=20000)
116 public void testDataBlockEncryption() throws IOException {
117 final int blocks = 10;
118 final int[] blockSizes = new int[blocks];
119 for (int i = 0; i < blocks; i++) {
120 blockSizes[i] = (1024 + RNG.nextInt(1024 * 63)) / Bytes.SIZEOF_INT;
121 }
122 for (Compression.Algorithm compression : TestHFileBlock.COMPRESSION_ALGORITHMS) {
123 Path path = new Path(TEST_UTIL.getDataTestDir(), "block_v3_" + compression + "_AES");
124 LOG.info("testDataBlockEncryption: encryption=AES compression=" + compression);
125 long totalSize = 0;
126 HFileContext fileContext = new HFileContextBuilder()
127 .withCompression(compression)
128 .withEncryptionContext(cryptoContext)
129 .build();
130 FSDataOutputStream os = fs.create(path);
131 try {
132 for (int i = 0; i < blocks; i++) {
133 totalSize += writeBlock(os, fileContext, blockSizes[i]);
134 }
135 } finally {
136 os.close();
137 }
138 FSDataInputStream is = fs.open(path);
139 try {
140 HFileBlock.FSReaderV2 hbr = new HFileBlock.FSReaderV2(is, totalSize, fileContext);
141 long pos = 0;
142 for (int i = 0; i < blocks; i++) {
143 pos += readAndVerifyBlock(pos, fileContext, hbr, blockSizes[i]);
144 }
145 } finally {
146 is.close();
147 }
148 }
149 }
150
151 @Test(timeout=20000)
152 public void testHFileEncryptionMetadata() throws Exception {
153 Configuration conf = TEST_UTIL.getConfiguration();
154 CacheConfig cacheConf = new CacheConfig(conf);
155
156 HFileContext fileContext = new HFileContextBuilder()
157 .withEncryptionContext(cryptoContext)
158 .build();
159
160
161 Path path = new Path(TEST_UTIL.getDataTestDir(), "cryptometa.hfile");
162 FSDataOutputStream out = fs.create(path);
163 HFile.Writer writer = HFile.getWriterFactory(conf, cacheConf)
164 .withOutputStream(out)
165 .withFileContext(fileContext)
166 .create();
167 writer.append("foo".getBytes(), "value".getBytes());
168 writer.close();
169 out.close();
170
171
172 HFile.Reader reader = HFile.createReader(fs, path, cacheConf, conf);
173 reader.loadFileInfo();
174 FixedFileTrailer trailer = reader.getTrailer();
175 assertNotNull(trailer.getEncryptionKey());
176 Encryption.Context readerContext = reader.getFileContext().getEncryptionContext();
177 assertEquals(readerContext.getCipher().getName(), cryptoContext.getCipher().getName());
178 assertTrue(Bytes.equals(readerContext.getKeyBytes(),
179 cryptoContext.getKeyBytes()));
180 }
181
182 @Test(timeout=60000)
183 public void testHFileEncryption() throws Exception {
184
185 RedundantKVGenerator generator = new RedundantKVGenerator();
186 List<KeyValue> testKvs = generator.generateTestKeyValues(1000);
187
188
189 Configuration conf = TEST_UTIL.getConfiguration();
190 CacheConfig cacheConf = new CacheConfig(conf);
191 for (DataBlockEncoding encoding: DataBlockEncoding.values()) {
192 for (Compression.Algorithm compression: TestHFileBlock.COMPRESSION_ALGORITHMS) {
193 HFileContext fileContext = new HFileContextBuilder()
194 .withBlockSize(4096)
195 .withEncryptionContext(cryptoContext)
196 .withCompression(compression)
197 .withDataBlockEncoding(encoding)
198 .build();
199
200 LOG.info("Writing with " + fileContext);
201 Path path = new Path(TEST_UTIL.getDataTestDir(), UUID.randomUUID().toString() + ".hfile");
202 FSDataOutputStream out = fs.create(path);
203 HFile.Writer writer = HFile.getWriterFactory(conf, cacheConf)
204 .withOutputStream(out)
205 .withFileContext(fileContext)
206 .create();
207 for (KeyValue kv: testKvs) {
208 writer.append(kv);
209 }
210 writer.close();
211 out.close();
212
213
214 LOG.info("Reading with " + fileContext);
215 HFile.Reader reader = HFile.createReader(fs, path, cacheConf, conf);
216 reader.loadFileInfo();
217 FixedFileTrailer trailer = reader.getTrailer();
218 assertNotNull(trailer.getEncryptionKey());
219 HFileScanner scanner = reader.getScanner(false, false);
220 assertTrue("Initial seekTo failed", scanner.seekTo());
221 int i = 0;
222 do {
223 KeyValue kv = scanner.getKeyValue();
224 assertTrue("Read back an unexpected or invalid KV", testKvs.contains(kv));
225 i++;
226 } while (scanner.next());
227 reader.close();
228
229 assertEquals("Did not read back as many KVs as written", i, testKvs.size());
230
231
232 LOG.info("Random seeking with " + fileContext);
233 reader = HFile.createReader(fs, path, cacheConf, conf);
234 scanner = reader.getScanner(false, true);
235 assertTrue("Initial seekTo failed", scanner.seekTo());
236 for (i = 0; i < 100; i++) {
237 KeyValue kv = testKvs.get(RNG.nextInt(testKvs.size()));
238 assertEquals("Unable to find KV as expected: " + kv, scanner.seekTo(kv.getKey()), 0);
239 }
240 reader.close();
241 }
242 }
243 }
244
245 }