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