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.security;
019
020import org.apache.hbase.thirdparty.io.netty.buffer.ByteBuf;
021import org.apache.hbase.thirdparty.io.netty.channel.ChannelHandlerContext;
022import org.apache.hbase.thirdparty.io.netty.channel.SimpleChannelInboundHandler;
023import org.apache.hbase.thirdparty.io.netty.util.concurrent.Promise;
024
025import java.io.IOException;
026import java.security.PrivilegedExceptionAction;
027
028import org.apache.hadoop.conf.Configuration;
029import org.apache.yetus.audience.InterfaceAudience;
030import org.slf4j.Logger;
031import org.slf4j.LoggerFactory;
032import org.apache.hadoop.hbase.ipc.FallbackDisallowedException;
033import org.apache.hadoop.security.UserGroupInformation;
034import org.apache.hadoop.security.token.Token;
035import org.apache.hadoop.security.token.TokenIdentifier;
036
037/**
038 * Implement SASL logic for netty rpc client.
039 * @since 2.0.0
040 */
041@InterfaceAudience.Private
042public class NettyHBaseSaslRpcClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
043
044  private static final Logger LOG = LoggerFactory.getLogger(NettyHBaseSaslRpcClientHandler.class);
045
046  private final Promise<Boolean> saslPromise;
047
048  private final UserGroupInformation ugi;
049
050  private final NettyHBaseSaslRpcClient saslRpcClient;
051
052  private final Configuration conf;
053
054  // flag to mark if Crypto AES encryption is enable
055  private boolean needProcessConnectionHeader = false;
056
057  /**
058   * @param saslPromise {@code true} if success, {@code false} if server tells us to fallback to
059   *          simple.
060   */
061  public NettyHBaseSaslRpcClientHandler(Promise<Boolean> saslPromise, UserGroupInformation ugi,
062      AuthMethod method, Token<? extends TokenIdentifier> token, String serverPrincipal,
063      boolean fallbackAllowed, Configuration conf)
064      throws IOException {
065    this.saslPromise = saslPromise;
066    this.ugi = ugi;
067    this.conf = conf;
068    this.saslRpcClient = new NettyHBaseSaslRpcClient(method, token, serverPrincipal,
069        fallbackAllowed, conf.get(
070        "hbase.rpc.protection", SaslUtil.QualityOfProtection.AUTHENTICATION.name().toLowerCase()));
071  }
072
073  private void writeResponse(ChannelHandlerContext ctx, byte[] response) {
074    if (LOG.isDebugEnabled()) {
075      LOG.debug("Will send token of size " + response.length + " from initSASLContext.");
076    }
077    ctx.writeAndFlush(
078      ctx.alloc().buffer(4 + response.length).writeInt(response.length).writeBytes(response));
079  }
080
081  private void tryComplete(ChannelHandlerContext ctx) {
082    if (!saslRpcClient.isComplete()) {
083      return;
084    }
085
086    saslRpcClient.setupSaslHandler(ctx.pipeline());
087    setCryptoAESOption();
088
089    saslPromise.setSuccess(true);
090  }
091
092  private void setCryptoAESOption() {
093    boolean saslEncryptionEnabled = SaslUtil.QualityOfProtection.PRIVACY.
094        getSaslQop().equalsIgnoreCase(saslRpcClient.getSaslQOP());
095    needProcessConnectionHeader = saslEncryptionEnabled && conf.getBoolean(
096        "hbase.rpc.crypto.encryption.aes.enabled", false);
097  }
098
099  public boolean isNeedProcessConnectionHeader() {
100    return needProcessConnectionHeader;
101  }
102
103  @Override
104  public void handlerAdded(ChannelHandlerContext ctx) {
105    try {
106      byte[] initialResponse = ugi.doAs(new PrivilegedExceptionAction<byte[]>() {
107
108        @Override
109        public byte[] run() throws Exception {
110          return saslRpcClient.getInitialResponse();
111        }
112      });
113      if (initialResponse != null) {
114        writeResponse(ctx, initialResponse);
115      }
116      tryComplete(ctx);
117    } catch (Exception e) {
118      // the exception thrown by handlerAdded will not be passed to the exceptionCaught below
119      // because netty will remove a handler if handlerAdded throws an exception.
120      exceptionCaught(ctx, e);
121    }
122  }
123
124  @Override
125  protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
126    int len = msg.readInt();
127    if (len == SaslUtil.SWITCH_TO_SIMPLE_AUTH) {
128      saslRpcClient.dispose();
129      if (saslRpcClient.fallbackAllowed) {
130        saslPromise.trySuccess(false);
131      } else {
132        saslPromise.tryFailure(new FallbackDisallowedException());
133      }
134      return;
135    }
136    if (LOG.isDebugEnabled()) {
137      LOG.debug("Will read input token of size " + len + " for processing by initSASLContext");
138    }
139    final byte[] challenge = new byte[len];
140    msg.readBytes(challenge);
141    byte[] response = ugi.doAs(new PrivilegedExceptionAction<byte[]>() {
142
143      @Override
144      public byte[] run() throws Exception {
145        return saslRpcClient.evaluateChallenge(challenge);
146      }
147    });
148    if (response != null) {
149      writeResponse(ctx, response);
150    }
151    tryComplete(ctx);
152  }
153
154  @Override
155  public void channelInactive(ChannelHandlerContext ctx) throws Exception {
156    saslRpcClient.dispose();
157    saslPromise.tryFailure(new IOException("Connection closed"));
158    ctx.fireChannelInactive();
159  }
160
161  @Override
162  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
163    saslRpcClient.dispose();
164    saslPromise.tryFailure(cause);
165  }
166}