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  
19  package org.apache.hadoop.hbase.thrift;
20  
21  import java.io.IOException;
22  import java.security.PrivilegedExceptionAction;
23  
24  import javax.servlet.ServletException;
25  import javax.servlet.http.HttpServletRequest;
26  import javax.servlet.http.HttpServletResponse;
27  
28  import org.apache.commons.logging.Log;
29  import org.apache.commons.logging.LogFactory;
30  import org.apache.hadoop.conf.Configuration;
31  import org.apache.hadoop.hbase.classification.InterfaceAudience;
32  import org.apache.hadoop.hbase.security.SecurityUtil;
33  import org.apache.hadoop.hbase.util.Base64;
34  import org.apache.hadoop.security.UserGroupInformation;
35  import org.apache.hadoop.security.authorize.AuthorizationException;
36  import org.apache.hadoop.security.authorize.ProxyUsers;
37  import org.apache.thrift.TProcessor;
38  import org.apache.thrift.protocol.TProtocolFactory;
39  import org.apache.thrift.server.TServlet;
40  import org.ietf.jgss.GSSContext;
41  import org.ietf.jgss.GSSCredential;
42  import org.ietf.jgss.GSSException;
43  import org.ietf.jgss.GSSManager;
44  import org.ietf.jgss.GSSName;
45  import org.ietf.jgss.Oid;
46  
47  /**
48   * Thrift Http Servlet is used for performing Kerberos authentication if security is enabled and
49   * also used for setting the user specified in "doAs" parameter.
50   */
51  @InterfaceAudience.Private
52  public class ThriftHttpServlet extends TServlet {
53    private static final long serialVersionUID = 1L;
54    public static final Log LOG = LogFactory.getLog(ThriftHttpServlet.class.getName());
55    private transient final UserGroupInformation realUser;
56    private transient final Configuration conf;
57    private final boolean securityEnabled;
58    private final boolean doAsEnabled;
59    private transient ThriftServerRunner.HBaseHandler hbaseHandler;
60    private String outToken;
61  
62    // HTTP Header related constants.
63    public static final String WWW_AUTHENTICATE = "WWW-Authenticate";
64    public static final String AUTHORIZATION = "Authorization";
65    public static final String NEGOTIATE = "Negotiate";
66  
67    public ThriftHttpServlet(TProcessor processor, TProtocolFactory protocolFactory,
68        UserGroupInformation realUser, Configuration conf, ThriftServerRunner.HBaseHandler
69        hbaseHandler, boolean securityEnabled, boolean doAsEnabled) {
70      super(processor, protocolFactory);
71      this.realUser = realUser;
72      this.conf = conf;
73      this.hbaseHandler = hbaseHandler;
74      this.securityEnabled = securityEnabled;
75      this.doAsEnabled = doAsEnabled;
76    }
77  
78    @Override
79    protected void doPost(HttpServletRequest request, HttpServletResponse response)
80        throws ServletException, IOException {
81      String effectiveUser = request.getRemoteUser();
82      if (securityEnabled) {
83        try {
84          // As Thrift HTTP transport doesn't support SPNEGO yet (THRIFT-889),
85          // Kerberos authentication is being done at servlet level.
86          effectiveUser = doKerberosAuth(request);
87          // It is standard for client applications expect this header.
88          // Please see http://tools.ietf.org/html/rfc4559 for more details.
89          response.addHeader(WWW_AUTHENTICATE,  NEGOTIATE + " " + outToken);
90        } catch (HttpAuthenticationException e) {
91          LOG.error("Kerberos Authentication failed", e);
92          // Send a 401 to the client
93          response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
94          response.addHeader(WWW_AUTHENTICATE, NEGOTIATE);
95          response.getWriter().println("Authentication Error: " + e.getMessage());
96          return;
97        }
98      }
99      String doAsUserFromQuery = request.getHeader("doAs");
100     if(effectiveUser == null) {
101       effectiveUser = realUser.getShortUserName();
102     }
103     if (doAsUserFromQuery != null) {
104       if (!doAsEnabled) {
105         throw new ServletException("Support for proxyuser is not configured");
106       }
107       // The authenticated remote user is attempting to perform 'doAs' proxy user.
108       UserGroupInformation remoteUser = UserGroupInformation.createRemoteUser(effectiveUser);
109       // create and attempt to authorize a proxy user (the client is attempting
110       // to do proxy user)
111       UserGroupInformation ugi = UserGroupInformation.createProxyUser(doAsUserFromQuery,
112           remoteUser);
113       // validate the proxy user authorization
114       try {
115         ProxyUsers.authorize(ugi, request.getRemoteAddr(), conf);
116       } catch (AuthorizationException e) {
117         throw new ServletException(e.getMessage());
118       }
119       effectiveUser = doAsUserFromQuery;
120     }
121     hbaseHandler.setEffectiveUser(effectiveUser);
122     super.doPost(request, response);
123   }
124 
125   /**
126    * Do the GSS-API kerberos authentication.
127    * We already have a logged in subject in the form of serviceUGI,
128    * which GSS-API will extract information from.
129    */
130   private String doKerberosAuth(HttpServletRequest request)
131       throws HttpAuthenticationException {
132     HttpKerberosServerAction action = new HttpKerberosServerAction(request, realUser);
133     try {
134       String principal = realUser.doAs(action);
135       outToken = action.outToken;
136       return principal;
137     } catch (Exception e) {
138       LOG.error("Failed to perform authentication");
139       throw new HttpAuthenticationException(e);
140     }
141   }
142 
143 
144   private static class HttpKerberosServerAction implements PrivilegedExceptionAction<String> {
145     HttpServletRequest request;
146     UserGroupInformation serviceUGI;
147     String outToken = null;
148     HttpKerberosServerAction(HttpServletRequest request, UserGroupInformation serviceUGI) {
149       this.request = request;
150       this.serviceUGI = serviceUGI;
151     }
152 
153     @Override
154     public String run() throws HttpAuthenticationException {
155       // Get own Kerberos credentials for accepting connection
156       GSSManager manager = GSSManager.getInstance();
157       GSSContext gssContext = null;
158       String serverPrincipal = SecurityUtil.getPrincipalWithoutRealm(serviceUGI.getUserName());
159       try {
160         // This Oid for Kerberos GSS-API mechanism.
161         Oid kerberosMechOid = new Oid("1.2.840.113554.1.2.2");
162         // Oid for SPNego GSS-API mechanism.
163         Oid spnegoMechOid = new Oid("1.3.6.1.5.5.2");
164         // Oid for kerberos principal name
165         Oid krb5PrincipalOid = new Oid("1.2.840.113554.1.2.2.1");
166         // GSS name for server
167         GSSName serverName = manager.createName(serverPrincipal, krb5PrincipalOid);
168         // GSS credentials for server
169         GSSCredential serverCreds = manager.createCredential(serverName,
170             GSSCredential.DEFAULT_LIFETIME,
171             new Oid[]{kerberosMechOid, spnegoMechOid},
172             GSSCredential.ACCEPT_ONLY);
173         // Create a GSS context
174         gssContext = manager.createContext(serverCreds);
175         // Get service ticket from the authorization header
176         String serviceTicketBase64 = getAuthHeader(request);
177         byte[] inToken = Base64.decode(serviceTicketBase64);
178         byte[] res = gssContext.acceptSecContext(inToken, 0, inToken.length);
179         if(res != null) {
180           outToken = Base64.encodeBytes(res).replace("\n", "");
181         }
182         // Authenticate or deny based on its context completion
183         if (!gssContext.isEstablished()) {
184           throw new HttpAuthenticationException("Kerberos authentication failed: " +
185               "unable to establish context with the service ticket " +
186               "provided by the client.");
187         }
188         return SecurityUtil.getUserFromPrincipal(gssContext.getSrcName().toString());
189       } catch (GSSException e) {
190         throw new HttpAuthenticationException("Kerberos authentication failed: ", e);
191       } finally {
192         if (gssContext != null) {
193           try {
194             gssContext.dispose();
195           } catch (GSSException e) {
196             LOG.warn("Error while disposing GSS Context", e);
197           }
198         }
199       }
200     }
201 
202     /**
203      * Returns the base64 encoded auth header payload
204      *
205      * @throws HttpAuthenticationException if a remote or network exception occurs
206      */
207     private String getAuthHeader(HttpServletRequest request)
208         throws HttpAuthenticationException {
209       String authHeader = request.getHeader(AUTHORIZATION);
210       // Each http request must have an Authorization header
211       if (authHeader == null || authHeader.isEmpty()) {
212         throw new HttpAuthenticationException("Authorization header received " +
213             "from the client is empty.");
214       }
215       String authHeaderBase64String;
216       int beginIndex = (NEGOTIATE + " ").length();
217       authHeaderBase64String = authHeader.substring(beginIndex);
218       // Authorization header must have a payload
219       if (authHeaderBase64String == null || authHeaderBase64String.isEmpty()) {
220         throw new HttpAuthenticationException("Authorization header received " +
221             "from the client does not contain any data.");
222       }
223       return authHeaderBase64String;
224     }
225   }
226 }