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.regionserver.wal;
19  
20  import java.io.ByteArrayInputStream;
21  import java.io.ByteArrayOutputStream;
22  import java.io.IOException;
23  import java.io.InputStream;
24  import java.io.OutputStream;
25  import java.security.SecureRandom;
26  
27  import org.apache.commons.io.IOUtils;
28  import org.apache.hadoop.hbase.classification.InterfaceAudience;
29  import org.apache.hadoop.conf.Configuration;
30  import org.apache.hadoop.hbase.Cell;
31  import org.apache.hadoop.hbase.KeyValue;
32  import org.apache.hadoop.hbase.KeyValueUtil;
33  import org.apache.hadoop.hbase.codec.KeyValueCodecWithTags;
34  import org.apache.hadoop.hbase.io.crypto.Decryptor;
35  import org.apache.hadoop.hbase.io.crypto.Encryption;
36  import org.apache.hadoop.hbase.io.crypto.Encryptor;
37  import org.apache.hadoop.hbase.io.util.StreamUtils;
38  import org.apache.hadoop.hbase.util.Bytes;
39  
40  /**
41   * A WALCellCodec that encrypts the WALedits.
42   */
43  @InterfaceAudience.Private
44  public class SecureWALCellCodec extends WALCellCodec {
45  
46    private Encryptor encryptor;
47    private Decryptor decryptor;
48  
49    public SecureWALCellCodec(Configuration conf, CompressionContext compression) {
50      super(conf, compression);
51    }
52  
53    public SecureWALCellCodec(Configuration conf, Encryptor encryptor) {
54      super(conf, null);
55      this.encryptor = encryptor;
56    }
57  
58    public SecureWALCellCodec(Configuration conf, Decryptor decryptor) {
59      super(conf, null);
60      this.decryptor = decryptor;
61    }
62  
63    static class EncryptedKvDecoder extends KeyValueCodecWithTags.KeyValueDecoder {
64  
65      private Decryptor decryptor;
66      private byte[] iv;
67  
68      public EncryptedKvDecoder(InputStream in) {
69        super(in);
70      }
71  
72      public EncryptedKvDecoder(InputStream in, Decryptor decryptor) {
73        super(in);
74        this.decryptor = decryptor;
75        if (decryptor != null) {
76          this.iv = new byte[decryptor.getIvLength()];
77        }
78      }
79  
80      @Override
81      protected Cell parseCell() throws IOException {
82        if (this.decryptor == null) {
83          return super.parseCell();
84        }
85        int ivLength = 0;
86  
87        ivLength = StreamUtils.readRawVarint32(in);
88  
89        // TODO: An IV length of 0 could signify an unwrapped cell, when the
90        // encoder supports that just read the remainder in directly
91  
92        if (ivLength != this.iv.length) {
93          throw new IOException("Incorrect IV length: expected=" + iv.length + " have=" +
94            ivLength);
95        }
96        IOUtils.readFully(in, this.iv);
97  
98        int codedLength = StreamUtils.readRawVarint32(in);
99        byte[] codedBytes = new byte[codedLength];
100       IOUtils.readFully(in, codedBytes);
101 
102       decryptor.setIv(iv);
103       decryptor.reset();
104 
105       InputStream cin = decryptor.createDecryptionStream(new ByteArrayInputStream(codedBytes));
106 
107       // TODO: Add support for WAL compression
108 
109       int keylength = StreamUtils.readRawVarint32(cin);
110       int vlength = StreamUtils.readRawVarint32(cin);
111       int tagsLength = StreamUtils.readRawVarint32(cin);
112       int length = 0;
113       if (tagsLength == 0) {
114         length = KeyValue.KEYVALUE_INFRASTRUCTURE_SIZE + keylength + vlength;
115       } else {
116         length = KeyValue.KEYVALUE_WITH_TAGS_INFRASTRUCTURE_SIZE + keylength + vlength + tagsLength;
117       }
118 
119       byte[] backingArray = new byte[length];
120       int pos = 0;
121       pos = Bytes.putInt(backingArray, pos, keylength);
122       pos = Bytes.putInt(backingArray, pos, vlength);
123 
124       // Row
125       int elemLen = StreamUtils.readRawVarint32(cin);
126       pos = Bytes.putShort(backingArray, pos, (short)elemLen);
127       IOUtils.readFully(cin, backingArray, pos, elemLen);
128       pos += elemLen;
129       // Family
130       elemLen = StreamUtils.readRawVarint32(cin);
131       pos = Bytes.putByte(backingArray, pos, (byte)elemLen);
132       IOUtils.readFully(cin, backingArray, pos, elemLen);
133       pos += elemLen;
134       // Qualifier
135       elemLen = StreamUtils.readRawVarint32(cin);
136       IOUtils.readFully(cin, backingArray, pos, elemLen);
137       pos += elemLen;
138       // Remainder
139       IOUtils.readFully(cin, backingArray, pos, length - pos);
140       return new KeyValue(backingArray, 0, length);
141     }
142 
143   }
144 
145   static class EncryptedKvEncoder extends KeyValueCodecWithTags.KeyValueEncoder {
146 
147     private Encryptor encryptor;
148     private final ThreadLocal<byte[]> iv = new ThreadLocal<byte[]>() {
149       @Override
150       protected byte[] initialValue() {
151         byte[] iv = new byte[encryptor.getIvLength()];
152         new SecureRandom().nextBytes(iv);
153         return iv;
154       }
155     };
156 
157     protected byte[] nextIv() {
158       byte[] b = iv.get(), ret = new byte[b.length];
159       System.arraycopy(b, 0, ret, 0, b.length);
160       return ret;
161     }
162 
163     protected void incrementIv(int v) {
164       Encryption.incrementIv(iv.get(), 1 + (v / encryptor.getBlockSize()));
165     }
166 
167     public EncryptedKvEncoder(OutputStream os) {
168       super(os);
169     }
170 
171     public EncryptedKvEncoder(OutputStream os, Encryptor encryptor) {
172       super(os);
173       this.encryptor = encryptor;
174     }
175 
176     @Override
177     public void write(Cell cell) throws IOException {
178       if (!(cell instanceof KeyValue)) throw new IOException("Cannot write non-KV cells to WAL");
179       if (encryptor == null) {
180         super.write(cell);
181         return;
182       }
183 
184       KeyValue kv = (KeyValue)cell;
185       byte[] kvBuffer = kv.getBuffer();
186       int offset = kv.getOffset();
187 
188       byte[] iv = nextIv();
189       encryptor.setIv(iv);
190       encryptor.reset();
191 
192       // TODO: Check if this is a cell for an encrypted CF. If not, we can
193       // write a 0 here to signal an unwrapped cell and just dump the KV bytes
194       // afterward
195 
196       StreamUtils.writeRawVInt32(out, iv.length);
197       out.write(iv);
198 
199       // TODO: Add support for WAL compression
200 
201       ByteArrayOutputStream baos = new ByteArrayOutputStream();
202       OutputStream cout = encryptor.createEncryptionStream(baos);
203 
204       // Write the KeyValue infrastructure as VInts.
205       StreamUtils.writeRawVInt32(cout, kv.getKeyLength());
206       StreamUtils.writeRawVInt32(cout, kv.getValueLength());
207       // To support tags
208       StreamUtils.writeRawVInt32(cout, kv.getTagsLengthUnsigned());
209 
210       // Write row, qualifier, and family
211       StreamUtils.writeRawVInt32(cout, kv.getRowLength());
212       cout.write(kvBuffer, kv.getRowOffset(), kv.getRowLength());
213       StreamUtils.writeRawVInt32(cout, kv.getFamilyLength());
214       cout.write(kvBuffer, kv.getFamilyOffset(), kv.getFamilyLength());
215       StreamUtils.writeRawVInt32(cout, kv.getQualifierLength());
216       cout.write(kvBuffer, kv.getQualifierOffset(), kv.getQualifierLength());
217       // Write the rest
218       int pos = kv.getTimestampOffset();
219       int remainingLength = kv.getLength() + offset - pos;
220       cout.write(kvBuffer, pos, remainingLength);
221       cout.close();
222 
223       StreamUtils.writeRawVInt32(out, baos.size());
224       baos.writeTo(out);
225 
226       // Increment IV given the final payload length
227       incrementIv(baos.size());
228     }
229 
230   }
231 
232   @Override
233   public Decoder getDecoder(InputStream is) {
234     return new EncryptedKvDecoder(is, decryptor);
235   }
236 
237   @Override
238   public Encoder getEncoder(OutputStream os) {
239     return new EncryptedKvEncoder(os, encryptor);
240   }
241 
242   public static WALCellCodec getCodec(Configuration conf, Encryptor encryptor) {
243     return new SecureWALCellCodec(conf, encryptor);
244   }
245 
246   public static WALCellCodec getCodec(Configuration conf, Decryptor decryptor) {
247     return new SecureWALCellCodec(conf, decryptor);
248   }
249 
250 }