001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.io.asyncfs;
019
020import static org.apache.hbase.thirdparty.io.netty.handler.timeout.IdleState.READER_IDLE;
021import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_ENCRYPT_DATA_TRANSFER_CIPHER_SUITES_KEY;
022
023import org.apache.hbase.thirdparty.com.google.common.base.Charsets;
024import org.apache.hbase.thirdparty.com.google.common.base.Throwables;
025import org.apache.hbase.thirdparty.com.google.common.collect.ImmutableSet;
026import org.apache.hbase.thirdparty.com.google.common.collect.Maps;
027import com.google.protobuf.CodedOutputStream;
028
029import org.apache.hbase.thirdparty.io.netty.buffer.ByteBuf;
030import org.apache.hbase.thirdparty.io.netty.buffer.ByteBufOutputStream;
031import org.apache.hbase.thirdparty.io.netty.buffer.CompositeByteBuf;
032import org.apache.hbase.thirdparty.io.netty.buffer.Unpooled;
033import org.apache.hbase.thirdparty.io.netty.channel.Channel;
034import org.apache.hbase.thirdparty.io.netty.channel.ChannelDuplexHandler;
035import org.apache.hbase.thirdparty.io.netty.channel.ChannelHandlerContext;
036import org.apache.hbase.thirdparty.io.netty.channel.ChannelOutboundHandlerAdapter;
037import org.apache.hbase.thirdparty.io.netty.channel.ChannelPipeline;
038import org.apache.hbase.thirdparty.io.netty.channel.ChannelPromise;
039import org.apache.hbase.thirdparty.io.netty.channel.SimpleChannelInboundHandler;
040import org.apache.hbase.thirdparty.io.netty.handler.codec.LengthFieldBasedFrameDecoder;
041import org.apache.hbase.thirdparty.io.netty.handler.codec.MessageToByteEncoder;
042import org.apache.hbase.thirdparty.io.netty.handler.codec.protobuf.ProtobufDecoder;
043import org.apache.hbase.thirdparty.io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
044import org.apache.hbase.thirdparty.io.netty.handler.timeout.IdleStateEvent;
045import org.apache.hbase.thirdparty.io.netty.handler.timeout.IdleStateHandler;
046import org.apache.hbase.thirdparty.io.netty.util.concurrent.Promise;
047
048import java.io.IOException;
049import java.lang.reflect.Field;
050import java.lang.reflect.InvocationTargetException;
051import java.lang.reflect.Method;
052import java.net.InetAddress;
053import java.net.InetSocketAddress;
054import java.nio.ByteBuffer;
055import java.security.GeneralSecurityException;
056import java.util.Arrays;
057import java.util.Collections;
058import java.util.List;
059import java.util.Map;
060import java.util.Set;
061import java.util.concurrent.TimeUnit;
062import java.util.concurrent.atomic.AtomicBoolean;
063
064import javax.security.auth.callback.Callback;
065import javax.security.auth.callback.CallbackHandler;
066import javax.security.auth.callback.NameCallback;
067import javax.security.auth.callback.PasswordCallback;
068import javax.security.auth.callback.UnsupportedCallbackException;
069import javax.security.sasl.RealmCallback;
070import javax.security.sasl.RealmChoiceCallback;
071import javax.security.sasl.Sasl;
072import javax.security.sasl.SaslClient;
073import javax.security.sasl.SaslException;
074
075import org.apache.commons.codec.binary.Base64;
076import org.apache.commons.lang3.StringUtils;
077import org.apache.hadoop.conf.Configuration;
078import org.apache.hadoop.crypto.CipherOption;
079import org.apache.hadoop.crypto.CipherSuite;
080import org.apache.hadoop.crypto.CryptoCodec;
081import org.apache.hadoop.crypto.Decryptor;
082import org.apache.hadoop.crypto.Encryptor;
083import org.apache.hadoop.crypto.key.KeyProvider.KeyVersion;
084import org.apache.hadoop.fs.FileEncryptionInfo;
085import org.apache.yetus.audience.InterfaceAudience;
086import org.slf4j.Logger;
087import org.slf4j.LoggerFactory;
088
089import com.google.protobuf.ByteString;
090import org.apache.hadoop.hdfs.DFSClient;
091import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
092import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
093import org.apache.hadoop.hdfs.protocol.datatransfer.InvalidEncryptionKeyException;
094import org.apache.hadoop.hdfs.protocol.datatransfer.TrustedChannelResolver;
095import org.apache.hadoop.hdfs.protocol.datatransfer.sasl.SaslDataTransferClient;
096import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.DataTransferEncryptorMessageProto;
097import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.DataTransferEncryptorMessageProto.DataTransferEncryptorStatus;
098import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.CipherOptionProto;
099import org.apache.hadoop.hdfs.security.token.block.BlockTokenIdentifier;
100import org.apache.hadoop.hdfs.security.token.block.DataEncryptionKey;
101import org.apache.hadoop.security.SaslPropertiesResolver;
102import org.apache.hadoop.security.SaslRpcServer.QualityOfProtection;
103import org.apache.hadoop.security.UserGroupInformation;
104import org.apache.hadoop.security.token.Token;
105
106/**
107 * Helper class for adding sasl support for {@link FanOutOneBlockAsyncDFSOutput}.
108 */
109@InterfaceAudience.Private
110public final class FanOutOneBlockAsyncDFSOutputSaslHelper {
111  private static final Logger LOG =
112      LoggerFactory.getLogger(FanOutOneBlockAsyncDFSOutputSaslHelper.class);
113
114  private FanOutOneBlockAsyncDFSOutputSaslHelper() {
115  }
116
117  private static final String SERVER_NAME = "0";
118  private static final String PROTOCOL = "hdfs";
119  private static final String MECHANISM = "DIGEST-MD5";
120  private static final int SASL_TRANSFER_MAGIC_NUMBER = 0xDEADBEEF;
121  private static final String NAME_DELIMITER = " ";
122
123  private interface SaslAdaptor {
124
125    TrustedChannelResolver getTrustedChannelResolver(SaslDataTransferClient saslClient);
126
127    SaslPropertiesResolver getSaslPropsResolver(SaslDataTransferClient saslClient);
128
129    AtomicBoolean getFallbackToSimpleAuth(SaslDataTransferClient saslClient);
130  }
131
132  private static final SaslAdaptor SASL_ADAPTOR;
133
134  // helper class for convert protos.
135  private interface PBHelper {
136
137    List<CipherOptionProto> convertCipherOptions(List<CipherOption> options);
138
139    List<CipherOption> convertCipherOptionProtos(List<CipherOptionProto> options);
140  }
141
142  private static final PBHelper PB_HELPER;
143
144  private interface TransparentCryptoHelper {
145
146    Encryptor createEncryptor(Configuration conf, FileEncryptionInfo feInfo, DFSClient client)
147        throws IOException;
148  }
149
150  private static final TransparentCryptoHelper TRANSPARENT_CRYPTO_HELPER;
151
152  private static SaslAdaptor createSaslAdaptor()
153      throws NoSuchFieldException, NoSuchMethodException {
154    Field saslPropsResolverField =
155        SaslDataTransferClient.class.getDeclaredField("saslPropsResolver");
156    saslPropsResolverField.setAccessible(true);
157    Field trustedChannelResolverField =
158        SaslDataTransferClient.class.getDeclaredField("trustedChannelResolver");
159    trustedChannelResolverField.setAccessible(true);
160    Field fallbackToSimpleAuthField =
161        SaslDataTransferClient.class.getDeclaredField("fallbackToSimpleAuth");
162    fallbackToSimpleAuthField.setAccessible(true);
163    return new SaslAdaptor() {
164
165      @Override
166      public TrustedChannelResolver getTrustedChannelResolver(SaslDataTransferClient saslClient) {
167        try {
168          return (TrustedChannelResolver) trustedChannelResolverField.get(saslClient);
169        } catch (IllegalAccessException e) {
170          throw new RuntimeException(e);
171        }
172      }
173
174      @Override
175      public SaslPropertiesResolver getSaslPropsResolver(SaslDataTransferClient saslClient) {
176        try {
177          return (SaslPropertiesResolver) saslPropsResolverField.get(saslClient);
178        } catch (IllegalAccessException e) {
179          throw new RuntimeException(e);
180        }
181      }
182
183      @Override
184      public AtomicBoolean getFallbackToSimpleAuth(SaslDataTransferClient saslClient) {
185        try {
186          return (AtomicBoolean) fallbackToSimpleAuthField.get(saslClient);
187        } catch (IllegalAccessException e) {
188          throw new RuntimeException(e);
189        }
190      }
191    };
192  }
193
194  private static PBHelper createPBHelper() throws NoSuchMethodException {
195    Class<?> helperClass;
196    try {
197      helperClass = Class.forName("org.apache.hadoop.hdfs.protocolPB.PBHelperClient");
198    } catch (ClassNotFoundException e) {
199      LOG.debug("No PBHelperClient class found, should be hadoop 2.7-", e);
200      helperClass = org.apache.hadoop.hdfs.protocolPB.PBHelper.class;
201    }
202    Method convertCipherOptionsMethod = helperClass.getMethod("convertCipherOptions", List.class);
203    Method convertCipherOptionProtosMethod =
204        helperClass.getMethod("convertCipherOptionProtos", List.class);
205    return new PBHelper() {
206
207      @SuppressWarnings("unchecked")
208      @Override
209      public List<CipherOptionProto> convertCipherOptions(List<CipherOption> options) {
210        try {
211          return (List<CipherOptionProto>) convertCipherOptionsMethod.invoke(null, options);
212        } catch (IllegalAccessException | InvocationTargetException e) {
213          throw new RuntimeException(e);
214        }
215      }
216
217      @SuppressWarnings("unchecked")
218      @Override
219      public List<CipherOption> convertCipherOptionProtos(List<CipherOptionProto> options) {
220        try {
221          return (List<CipherOption>) convertCipherOptionProtosMethod.invoke(null, options);
222        } catch (IllegalAccessException | InvocationTargetException e) {
223          throw new RuntimeException(e);
224        }
225      }
226    };
227  }
228
229  private static TransparentCryptoHelper createTransparentCryptoHelper()
230      throws NoSuchMethodException {
231    Method decryptEncryptedDataEncryptionKeyMethod = DFSClient.class
232        .getDeclaredMethod("decryptEncryptedDataEncryptionKey", FileEncryptionInfo.class);
233    decryptEncryptedDataEncryptionKeyMethod.setAccessible(true);
234    return new TransparentCryptoHelper() {
235
236      @Override
237      public Encryptor createEncryptor(Configuration conf, FileEncryptionInfo feInfo,
238          DFSClient client) throws IOException {
239        try {
240          KeyVersion decryptedKey =
241              (KeyVersion) decryptEncryptedDataEncryptionKeyMethod.invoke(client, feInfo);
242          CryptoCodec cryptoCodec = CryptoCodec.getInstance(conf, feInfo.getCipherSuite());
243          Encryptor encryptor = cryptoCodec.createEncryptor();
244          encryptor.init(decryptedKey.getMaterial(), feInfo.getIV());
245          return encryptor;
246        } catch (InvocationTargetException e) {
247          Throwables.propagateIfPossible(e.getTargetException(), IOException.class);
248          throw new RuntimeException(e.getTargetException());
249        } catch (GeneralSecurityException e) {
250          throw new IOException(e);
251        } catch (IllegalAccessException e) {
252          throw new RuntimeException(e);
253        }
254      }
255    };
256  }
257
258  static {
259    try {
260      SASL_ADAPTOR = createSaslAdaptor();
261      PB_HELPER = createPBHelper();
262      TRANSPARENT_CRYPTO_HELPER = createTransparentCryptoHelper();
263    } catch (Exception e) {
264      String msg = "Couldn't properly initialize access to HDFS internals. Please "
265          + "update your WAL Provider to not make use of the 'asyncfs' provider. See "
266          + "HBASE-16110 for more information.";
267      LOG.error(msg, e);
268      throw new Error(msg, e);
269    }
270  }
271
272  /**
273   * Sets user name and password when asked by the client-side SASL object.
274   */
275  private static final class SaslClientCallbackHandler implements CallbackHandler {
276
277    private final char[] password;
278    private final String userName;
279
280    /**
281     * Creates a new SaslClientCallbackHandler.
282     * @param userName SASL user name
283     * @Param password SASL password
284     */
285    public SaslClientCallbackHandler(String userName, char[] password) {
286      this.password = password;
287      this.userName = userName;
288    }
289
290    @Override
291    public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
292      NameCallback nc = null;
293      PasswordCallback pc = null;
294      RealmCallback rc = null;
295      for (Callback callback : callbacks) {
296        if (callback instanceof RealmChoiceCallback) {
297          continue;
298        } else if (callback instanceof NameCallback) {
299          nc = (NameCallback) callback;
300        } else if (callback instanceof PasswordCallback) {
301          pc = (PasswordCallback) callback;
302        } else if (callback instanceof RealmCallback) {
303          rc = (RealmCallback) callback;
304        } else {
305          throw new UnsupportedCallbackException(callback, "Unrecognized SASL client callback");
306        }
307      }
308      if (nc != null) {
309        nc.setName(userName);
310      }
311      if (pc != null) {
312        pc.setPassword(password);
313      }
314      if (rc != null) {
315        rc.setText(rc.getDefaultText());
316      }
317    }
318  }
319
320  private static final class SaslNegotiateHandler extends ChannelDuplexHandler {
321
322    private final Configuration conf;
323
324    private final Map<String, String> saslProps;
325
326    private final SaslClient saslClient;
327
328    private final int timeoutMs;
329
330    private final Promise<Void> promise;
331
332    private int step = 0;
333
334    public SaslNegotiateHandler(Configuration conf, String username, char[] password,
335        Map<String, String> saslProps, int timeoutMs, Promise<Void> promise) throws SaslException {
336      this.conf = conf;
337      this.saslProps = saslProps;
338      this.saslClient = Sasl.createSaslClient(new String[] { MECHANISM }, username, PROTOCOL,
339        SERVER_NAME, saslProps, new SaslClientCallbackHandler(username, password));
340      this.timeoutMs = timeoutMs;
341      this.promise = promise;
342    }
343
344    private void sendSaslMessage(ChannelHandlerContext ctx, byte[] payload) throws IOException {
345      sendSaslMessage(ctx, payload, null);
346    }
347
348    private List<CipherOption> getCipherOptions() throws IOException {
349      // Negotiate cipher suites if configured. Currently, the only supported
350      // cipher suite is AES/CTR/NoPadding, but the protocol allows multiple
351      // values for future expansion.
352      String cipherSuites = conf.get(DFS_ENCRYPT_DATA_TRANSFER_CIPHER_SUITES_KEY);
353      if (StringUtils.isBlank(cipherSuites)) {
354        return null;
355      }
356      if (!cipherSuites.equals(CipherSuite.AES_CTR_NOPADDING.getName())) {
357        throw new IOException(String.format("Invalid cipher suite, %s=%s",
358          DFS_ENCRYPT_DATA_TRANSFER_CIPHER_SUITES_KEY, cipherSuites));
359      }
360      return Collections.singletonList(new CipherOption(CipherSuite.AES_CTR_NOPADDING));
361    }
362
363    private void sendSaslMessage(ChannelHandlerContext ctx, byte[] payload,
364        List<CipherOption> options) throws IOException {
365      DataTransferEncryptorMessageProto.Builder builder =
366          DataTransferEncryptorMessageProto.newBuilder();
367      builder.setStatus(DataTransferEncryptorStatus.SUCCESS);
368      if (payload != null) {
369        // Was ByteStringer; fix w/o using ByteStringer. Its in hbase-protocol
370        // and we want to keep that out of hbase-server.
371        builder.setPayload(ByteString.copyFrom(payload));
372      }
373      if (options != null) {
374        builder.addAllCipherOption(PB_HELPER.convertCipherOptions(options));
375      }
376      DataTransferEncryptorMessageProto proto = builder.build();
377      int size = proto.getSerializedSize();
378      size += CodedOutputStream.computeRawVarint32Size(size);
379      ByteBuf buf = ctx.alloc().buffer(size);
380      proto.writeDelimitedTo(new ByteBufOutputStream(buf));
381      ctx.write(buf);
382    }
383
384    @Override
385    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
386      ctx.write(ctx.alloc().buffer(4).writeInt(SASL_TRANSFER_MAGIC_NUMBER));
387      sendSaslMessage(ctx, new byte[0]);
388      ctx.flush();
389      step++;
390    }
391
392    @Override
393    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
394      saslClient.dispose();
395    }
396
397    private void check(DataTransferEncryptorMessageProto proto) throws IOException {
398      if (proto.getStatus() == DataTransferEncryptorStatus.ERROR_UNKNOWN_KEY) {
399        throw new InvalidEncryptionKeyException(proto.getMessage());
400      } else if (proto.getStatus() == DataTransferEncryptorStatus.ERROR) {
401        throw new IOException(proto.getMessage());
402      }
403    }
404
405    private String getNegotiatedQop() {
406      return (String) saslClient.getNegotiatedProperty(Sasl.QOP);
407    }
408
409    private boolean isNegotiatedQopPrivacy() {
410      String qop = getNegotiatedQop();
411      return qop != null && "auth-conf".equalsIgnoreCase(qop);
412    }
413
414    private boolean requestedQopContainsPrivacy() {
415      Set<String> requestedQop =
416          ImmutableSet.copyOf(Arrays.asList(saslProps.get(Sasl.QOP).split(",")));
417      return requestedQop.contains("auth-conf");
418    }
419
420    private void checkSaslComplete() throws IOException {
421      if (!saslClient.isComplete()) {
422        throw new IOException("Failed to complete SASL handshake");
423      }
424      Set<String> requestedQop =
425          ImmutableSet.copyOf(Arrays.asList(saslProps.get(Sasl.QOP).split(",")));
426      String negotiatedQop = getNegotiatedQop();
427      LOG.debug(
428        "Verifying QOP, requested QOP = " + requestedQop + ", negotiated QOP = " + negotiatedQop);
429      if (!requestedQop.contains(negotiatedQop)) {
430        throw new IOException(String.format("SASL handshake completed, but "
431            + "channel does not have acceptable quality of protection, "
432            + "requested = %s, negotiated = %s",
433          requestedQop, negotiatedQop));
434      }
435    }
436
437    private boolean useWrap() {
438      String qop = (String) saslClient.getNegotiatedProperty(Sasl.QOP);
439      return qop != null && !"auth".equalsIgnoreCase(qop);
440    }
441
442    private CipherOption unwrap(CipherOption option, SaslClient saslClient) throws IOException {
443      byte[] inKey = option.getInKey();
444      if (inKey != null) {
445        inKey = saslClient.unwrap(inKey, 0, inKey.length);
446      }
447      byte[] outKey = option.getOutKey();
448      if (outKey != null) {
449        outKey = saslClient.unwrap(outKey, 0, outKey.length);
450      }
451      return new CipherOption(option.getCipherSuite(), inKey, option.getInIv(), outKey,
452          option.getOutIv());
453    }
454
455    private CipherOption getCipherOption(DataTransferEncryptorMessageProto proto,
456        boolean isNegotiatedQopPrivacy, SaslClient saslClient) throws IOException {
457      List<CipherOption> cipherOptions =
458          PB_HELPER.convertCipherOptionProtos(proto.getCipherOptionList());
459      if (cipherOptions == null || cipherOptions.isEmpty()) {
460        return null;
461      }
462      CipherOption cipherOption = cipherOptions.get(0);
463      return isNegotiatedQopPrivacy ? unwrap(cipherOption, saslClient) : cipherOption;
464    }
465
466    @Override
467    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
468      if (msg instanceof DataTransferEncryptorMessageProto) {
469        DataTransferEncryptorMessageProto proto = (DataTransferEncryptorMessageProto) msg;
470        check(proto);
471        byte[] challenge = proto.getPayload().toByteArray();
472        byte[] response = saslClient.evaluateChallenge(challenge);
473        switch (step) {
474          case 1: {
475            List<CipherOption> cipherOptions = null;
476            if (requestedQopContainsPrivacy()) {
477              cipherOptions = getCipherOptions();
478            }
479            sendSaslMessage(ctx, response, cipherOptions);
480            ctx.flush();
481            step++;
482            break;
483          }
484          case 2: {
485            assert response == null;
486            checkSaslComplete();
487            CipherOption cipherOption =
488                getCipherOption(proto, isNegotiatedQopPrivacy(), saslClient);
489            ChannelPipeline p = ctx.pipeline();
490            while (p.first() != null) {
491              p.removeFirst();
492            }
493            if (cipherOption != null) {
494              CryptoCodec codec = CryptoCodec.getInstance(conf, cipherOption.getCipherSuite());
495              p.addLast(new EncryptHandler(codec, cipherOption.getInKey(), cipherOption.getInIv()),
496                new DecryptHandler(codec, cipherOption.getOutKey(), cipherOption.getOutIv()));
497            } else {
498              if (useWrap()) {
499                p.addLast(new SaslWrapHandler(saslClient),
500                  new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4),
501                  new SaslUnwrapHandler(saslClient));
502              }
503            }
504            promise.trySuccess(null);
505            break;
506          }
507          default:
508            throw new IllegalArgumentException("Unrecognized negotiation step: " + step);
509        }
510      } else {
511        ctx.fireChannelRead(msg);
512      }
513    }
514
515    @Override
516    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
517      promise.tryFailure(cause);
518    }
519
520    @Override
521    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
522      if (evt instanceof IdleStateEvent && ((IdleStateEvent) evt).state() == READER_IDLE) {
523        promise.tryFailure(new IOException("Timeout(" + timeoutMs + "ms) waiting for response"));
524      } else {
525        super.userEventTriggered(ctx, evt);
526      }
527    }
528  }
529
530  private static final class SaslUnwrapHandler extends SimpleChannelInboundHandler<ByteBuf> {
531
532    private final SaslClient saslClient;
533
534    public SaslUnwrapHandler(SaslClient saslClient) {
535      this.saslClient = saslClient;
536    }
537
538    @Override
539    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
540      saslClient.dispose();
541    }
542
543    @Override
544    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
545      msg.skipBytes(4);
546      byte[] b = new byte[msg.readableBytes()];
547      msg.readBytes(b);
548      ctx.fireChannelRead(Unpooled.wrappedBuffer(saslClient.unwrap(b, 0, b.length)));
549    }
550  }
551
552  private static final class SaslWrapHandler extends ChannelOutboundHandlerAdapter {
553
554    private final SaslClient saslClient;
555
556    private CompositeByteBuf cBuf;
557
558    public SaslWrapHandler(SaslClient saslClient) {
559      this.saslClient = saslClient;
560    }
561
562    @Override
563    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
564      cBuf = new CompositeByteBuf(ctx.alloc(), false, Integer.MAX_VALUE);
565    }
566
567    @Override
568    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
569        throws Exception {
570      if (msg instanceof ByteBuf) {
571        ByteBuf buf = (ByteBuf) msg;
572        cBuf.addComponent(buf);
573        cBuf.writerIndex(cBuf.writerIndex() + buf.readableBytes());
574      } else {
575        ctx.write(msg);
576      }
577    }
578
579    @Override
580    public void flush(ChannelHandlerContext ctx) throws Exception {
581      if (cBuf.isReadable()) {
582        byte[] b = new byte[cBuf.readableBytes()];
583        cBuf.readBytes(b);
584        cBuf.discardReadComponents();
585        byte[] wrapped = saslClient.wrap(b, 0, b.length);
586        ByteBuf buf = ctx.alloc().ioBuffer(4 + wrapped.length);
587        buf.writeInt(wrapped.length);
588        buf.writeBytes(wrapped);
589        ctx.write(buf);
590      }
591      ctx.flush();
592    }
593
594    @Override
595    public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
596      cBuf.release();
597      cBuf = null;
598    }
599  }
600
601  private static final class DecryptHandler extends SimpleChannelInboundHandler<ByteBuf> {
602
603    private final Decryptor decryptor;
604
605    public DecryptHandler(CryptoCodec codec, byte[] key, byte[] iv)
606        throws GeneralSecurityException, IOException {
607      this.decryptor = codec.createDecryptor();
608      this.decryptor.init(key, Arrays.copyOf(iv, iv.length));
609    }
610
611    @Override
612    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
613      ByteBuf inBuf;
614      boolean release = false;
615      if (msg.nioBufferCount() == 1) {
616        inBuf = msg;
617      } else {
618        inBuf = ctx.alloc().directBuffer(msg.readableBytes());
619        msg.readBytes(inBuf);
620        release = true;
621      }
622      ByteBuffer inBuffer = inBuf.nioBuffer();
623      ByteBuf outBuf = ctx.alloc().directBuffer(inBuf.readableBytes());
624      ByteBuffer outBuffer = outBuf.nioBuffer(0, inBuf.readableBytes());
625      decryptor.decrypt(inBuffer, outBuffer);
626      outBuf.writerIndex(inBuf.readableBytes());
627      if (release) {
628        inBuf.release();
629      }
630      ctx.fireChannelRead(outBuf);
631    }
632  }
633
634  private static final class EncryptHandler extends MessageToByteEncoder<ByteBuf> {
635
636    private final Encryptor encryptor;
637
638    public EncryptHandler(CryptoCodec codec, byte[] key, byte[] iv)
639        throws GeneralSecurityException, IOException {
640      this.encryptor = codec.createEncryptor();
641      this.encryptor.init(key, Arrays.copyOf(iv, iv.length));
642    }
643
644    @Override
645    protected ByteBuf allocateBuffer(ChannelHandlerContext ctx, ByteBuf msg, boolean preferDirect)
646        throws Exception {
647      if (preferDirect) {
648        return ctx.alloc().directBuffer(msg.readableBytes());
649      } else {
650        return ctx.alloc().buffer(msg.readableBytes());
651      }
652    }
653
654    @Override
655    protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
656      ByteBuf inBuf;
657      boolean release = false;
658      if (msg.nioBufferCount() == 1) {
659        inBuf = msg;
660      } else {
661        inBuf = ctx.alloc().directBuffer(msg.readableBytes());
662        msg.readBytes(inBuf);
663        release = true;
664      }
665      ByteBuffer inBuffer = inBuf.nioBuffer();
666      ByteBuffer outBuffer = out.nioBuffer(0, inBuf.readableBytes());
667      encryptor.encrypt(inBuffer, outBuffer);
668      out.writerIndex(inBuf.readableBytes());
669      if (release) {
670        inBuf.release();
671      }
672    }
673  }
674
675  private static String getUserNameFromEncryptionKey(DataEncryptionKey encryptionKey) {
676    return encryptionKey.keyId + NAME_DELIMITER + encryptionKey.blockPoolId + NAME_DELIMITER
677        + new String(Base64.encodeBase64(encryptionKey.nonce, false), Charsets.UTF_8);
678  }
679
680  private static char[] encryptionKeyToPassword(byte[] encryptionKey) {
681    return new String(Base64.encodeBase64(encryptionKey, false), Charsets.UTF_8).toCharArray();
682  }
683
684  private static String buildUsername(Token<BlockTokenIdentifier> blockToken) {
685    return new String(Base64.encodeBase64(blockToken.getIdentifier(), false), Charsets.UTF_8);
686  }
687
688  private static char[] buildClientPassword(Token<BlockTokenIdentifier> blockToken) {
689    return new String(Base64.encodeBase64(blockToken.getPassword(), false), Charsets.UTF_8)
690        .toCharArray();
691  }
692
693  private static Map<String, String> createSaslPropertiesForEncryption(String encryptionAlgorithm) {
694    Map<String, String> saslProps = Maps.newHashMapWithExpectedSize(3);
695    saslProps.put(Sasl.QOP, QualityOfProtection.PRIVACY.getSaslQop());
696    saslProps.put(Sasl.SERVER_AUTH, "true");
697    saslProps.put("com.sun.security.sasl.digest.cipher", encryptionAlgorithm);
698    return saslProps;
699  }
700
701  private static void doSaslNegotiation(Configuration conf, Channel channel, int timeoutMs,
702      String username, char[] password, Map<String, String> saslProps, Promise<Void> saslPromise) {
703    try {
704      channel.pipeline().addLast(new IdleStateHandler(timeoutMs, 0, 0, TimeUnit.MILLISECONDS),
705        new ProtobufVarint32FrameDecoder(),
706        new ProtobufDecoder(DataTransferEncryptorMessageProto.getDefaultInstance()),
707        new SaslNegotiateHandler(conf, username, password, saslProps, timeoutMs, saslPromise));
708    } catch (SaslException e) {
709      saslPromise.tryFailure(e);
710    }
711  }
712
713  static void trySaslNegotiate(Configuration conf, Channel channel, DatanodeInfo dnInfo,
714      int timeoutMs, DFSClient client, Token<BlockTokenIdentifier> accessToken,
715      Promise<Void> saslPromise) throws IOException {
716    SaslDataTransferClient saslClient = client.getSaslDataTransferClient();
717    SaslPropertiesResolver saslPropsResolver = SASL_ADAPTOR.getSaslPropsResolver(saslClient);
718    TrustedChannelResolver trustedChannelResolver =
719        SASL_ADAPTOR.getTrustedChannelResolver(saslClient);
720    AtomicBoolean fallbackToSimpleAuth = SASL_ADAPTOR.getFallbackToSimpleAuth(saslClient);
721    InetAddress addr = ((InetSocketAddress) channel.remoteAddress()).getAddress();
722    if (trustedChannelResolver.isTrusted() || trustedChannelResolver.isTrusted(addr)) {
723      saslPromise.trySuccess(null);
724      return;
725    }
726    DataEncryptionKey encryptionKey = client.newDataEncryptionKey();
727    if (encryptionKey != null) {
728      if (LOG.isDebugEnabled()) {
729        LOG.debug(
730          "SASL client doing encrypted handshake for addr = " + addr + ", datanodeId = " + dnInfo);
731      }
732      doSaslNegotiation(conf, channel, timeoutMs, getUserNameFromEncryptionKey(encryptionKey),
733        encryptionKeyToPassword(encryptionKey.encryptionKey),
734        createSaslPropertiesForEncryption(encryptionKey.encryptionAlgorithm), saslPromise);
735    } else if (!UserGroupInformation.isSecurityEnabled()) {
736      if (LOG.isDebugEnabled()) {
737        LOG.debug("SASL client skipping handshake in unsecured configuration for addr = " + addr
738            + ", datanodeId = " + dnInfo);
739      }
740      saslPromise.trySuccess(null);
741    } else if (dnInfo.getXferPort() < 1024) {
742      if (LOG.isDebugEnabled()) {
743        LOG.debug("SASL client skipping handshake in secured configuration with "
744            + "privileged port for addr = " + addr + ", datanodeId = " + dnInfo);
745      }
746      saslPromise.trySuccess(null);
747    } else if (fallbackToSimpleAuth != null && fallbackToSimpleAuth.get()) {
748      if (LOG.isDebugEnabled()) {
749        LOG.debug("SASL client skipping handshake in secured configuration with "
750            + "unsecured cluster for addr = " + addr + ", datanodeId = " + dnInfo);
751      }
752      saslPromise.trySuccess(null);
753    } else if (saslPropsResolver != null) {
754      if (LOG.isDebugEnabled()) {
755        LOG.debug(
756          "SASL client doing general handshake for addr = " + addr + ", datanodeId = " + dnInfo);
757      }
758      doSaslNegotiation(conf, channel, timeoutMs, buildUsername(accessToken),
759        buildClientPassword(accessToken), saslPropsResolver.getClientProperties(addr), saslPromise);
760    } else {
761      // It's a secured cluster using non-privileged ports, but no SASL. The only way this can
762      // happen is if the DataNode has ignore.secure.ports.for.testing configured, so this is a rare
763      // edge case.
764      if (LOG.isDebugEnabled()) {
765        LOG.debug("SASL client skipping handshake in secured configuration with no SASL "
766            + "protection configured for addr = " + addr + ", datanodeId = " + dnInfo);
767      }
768      saslPromise.trySuccess(null);
769    }
770  }
771
772  static Encryptor createEncryptor(Configuration conf, HdfsFileStatus stat, DFSClient client)
773      throws IOException {
774    FileEncryptionInfo feInfo = stat.getFileEncryptionInfo();
775    if (feInfo == null) {
776      return null;
777    }
778    return TRANSPARENT_CRYPTO_HELPER.createEncryptor(conf, feInfo, client);
779  }
780}