View Javadoc

1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  package org.apache.http.impl.auth;
28  
29  import java.net.InetAddress;
30  import java.net.UnknownHostException;
31  import java.util.Locale;
32  
33  import org.apache.commons.codec.binary.Base64;
34  import org.apache.commons.logging.Log;
35  import org.apache.commons.logging.LogFactory;
36  import org.apache.http.Header;
37  import org.apache.http.HttpHost;
38  import org.apache.http.HttpRequest;
39  import org.apache.http.annotation.NotThreadSafe;
40  import org.apache.http.auth.AUTH;
41  import org.apache.http.auth.AuthenticationException;
42  import org.apache.http.auth.Credentials;
43  import org.apache.http.auth.InvalidCredentialsException;
44  import org.apache.http.auth.KerberosCredentials;
45  import org.apache.http.auth.MalformedChallengeException;
46  import org.apache.http.client.protocol.HttpClientContext;
47  import org.apache.http.conn.routing.HttpRoute;
48  import org.apache.http.message.BufferedHeader;
49  import org.apache.http.protocol.HttpContext;
50  import org.apache.http.util.Args;
51  import org.apache.http.util.CharArrayBuffer;
52  import org.ietf.jgss.GSSContext;
53  import org.ietf.jgss.GSSCredential;
54  import org.ietf.jgss.GSSException;
55  import org.ietf.jgss.GSSManager;
56  import org.ietf.jgss.GSSName;
57  import org.ietf.jgss.Oid;
58  
59  /**
60   * @since 4.2
61   */
62  @NotThreadSafe
63  public abstract class GGSSchemeBase extends AuthSchemeBase {
64  
65      enum State {
66          UNINITIATED,
67          CHALLENGE_RECEIVED,
68          TOKEN_GENERATED,
69          FAILED,
70      }
71  
72      private final Log log = LogFactory.getLog(getClass());
73  
74      private final Base64 base64codec;
75      private final boolean stripPort;
76      private final boolean useCanonicalHostname;
77  
78      /** Authentication process state */
79      private State state;
80  
81      /** base64 decoded challenge **/
82      private byte[] token;
83      private String service;
84  
85      GGSSchemeBase(final boolean stripPort, final boolean useCanonicalHostname) {
86          super();
87          this.base64codec = new Base64(0);
88          this.stripPort = stripPort;
89          this.useCanonicalHostname = useCanonicalHostname;
90          this.state = State.UNINITIATED;
91      }
92  
93      GGSSchemeBase(final boolean stripPort) {
94          this(stripPort, true);
95      }
96  
97      GGSSchemeBase() {
98          this(true,true);
99      }
100 
101     protected GSSManager getManager() {
102         return GSSManager.getInstance();
103     }
104 
105     protected byte[] generateGSSToken(
106             final byte[] input, final Oid oid, final String authServer) throws GSSException {
107         return generateGSSToken(input, oid, authServer, null);
108     }
109 
110     /**
111      * @since 4.4
112      */
113     protected byte[] generateGSSToken(
114             final byte[] input, final Oid oid, final String authServer,
115             final Credentials credentials) throws GSSException {
116         byte[] inputBuff = input;
117         if (inputBuff == null) {
118             inputBuff = new byte[0];
119         }
120         final GSSManager manager = getManager();
121         final GSSName serverName = manager.createName(service + "@" + authServer, GSSName.NT_HOSTBASED_SERVICE);
122 
123         final GSSCredential gssCredential;
124         if (credentials instanceof KerberosCredentials) {
125             gssCredential = ((KerberosCredentials) credentials).getGSSCredential();
126         } else {
127             gssCredential = null;
128         }
129 
130         final GSSContext gssContext = manager.createContext(
131                 serverName.canonicalize(oid), oid, gssCredential, GSSContext.DEFAULT_LIFETIME);
132         gssContext.requestMutualAuth(true);
133         gssContext.requestCredDeleg(true);
134         return gssContext.initSecContext(inputBuff, 0, inputBuff.length);
135     }
136 
137     /**
138      * @deprecated (4.4) Use {@link #generateToken(byte[], String, org.apache.http.auth.Credentials)}.
139      */
140     @Deprecated
141     protected byte[] generateToken(final byte[] input, final String authServer) throws GSSException {
142         return null;
143     }
144 
145     /**
146      * @since 4.4
147      */
148     //TODO: make this method abstract
149     @SuppressWarnings("deprecation")
150     protected byte[] generateToken(
151             final byte[] input, final String authServer, final Credentials credentials) throws GSSException {
152         return generateToken(input, authServer);
153     }
154 
155     @Override
156     public boolean isComplete() {
157         return this.state == State.TOKEN_GENERATED || this.state == State.FAILED;
158     }
159 
160     /**
161      * @deprecated (4.2) Use {@link org.apache.http.auth.ContextAwareAuthScheme#authenticate(
162      *   Credentials, HttpRequest, org.apache.http.protocol.HttpContext)}
163      */
164     @Override
165     @Deprecated
166     public Header authenticate(
167             final Credentials credentials,
168             final HttpRequest request) throws AuthenticationException {
169         return authenticate(credentials, request, null);
170     }
171 
172     @Override
173     public Header authenticate(
174             final Credentials credentials,
175             final HttpRequest request,
176             final HttpContext context) throws AuthenticationException {
177         Args.notNull(request, "HTTP request");
178         switch (state) {
179         case UNINITIATED:
180             throw new AuthenticationException(getSchemeName() + " authentication has not been initiated");
181         case FAILED:
182             throw new AuthenticationException(getSchemeName() + " authentication has failed");
183         case CHALLENGE_RECEIVED:
184             try {
185                 final HttpRoute route = (HttpRoute) context.getAttribute(HttpClientContext.HTTP_ROUTE);
186                 if (route == null) {
187                     throw new AuthenticationException("Connection route is not available");
188                 }
189                 HttpHost host;
190                 if (isProxy()) {
191                     host = route.getProxyHost();
192                     if (host == null) {
193                         host = route.getTargetHost();
194                     }
195                 } else {
196                     host = route.getTargetHost();
197                 }
198                 final String authServer;
199                 String hostname = host.getHostName();
200 
201                 if (this.useCanonicalHostname){
202                     try {
203                          //TODO: uncomment this statement and delete the resolveCanonicalHostname,
204                          //TODO: as soon canonical hostname resolving is implemented in the SystemDefaultDnsResolver
205                          //final DnsResolver dnsResolver = SystemDefaultDnsResolver.INSTANCE;
206                          //hostname = dnsResolver.resolveCanonicalHostname(host.getHostName());
207                          hostname = resolveCanonicalHostname(hostname);
208                     } catch (final UnknownHostException ignore){
209                     }
210                 }
211                 if (this.stripPort) { // || host.getPort()==80 || host.getPort()==443) {
212                     authServer = hostname;
213                 } else {
214                     authServer = hostname + ":" + host.getPort();
215                 }
216 
217                 service = host.getSchemeName().toUpperCase(Locale.ROOT);
218 
219                 if (log.isDebugEnabled()) {
220                     log.debug("init " + authServer);
221                 }
222                 token = generateToken(token, authServer, credentials);
223                 state = State.TOKEN_GENERATED;
224             } catch (final GSSException gsse) {
225                 state = State.FAILED;
226                 if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL
227                         || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED) {
228                     throw new InvalidCredentialsException(gsse.getMessage(), gsse);
229                 }
230                 if (gsse.getMajor() == GSSException.NO_CRED ) {
231                     throw new InvalidCredentialsException(gsse.getMessage(), gsse);
232                 }
233                 if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN
234                         || gsse.getMajor() == GSSException.DUPLICATE_TOKEN
235                         || gsse.getMajor() == GSSException.OLD_TOKEN) {
236                     throw new AuthenticationException(gsse.getMessage(), gsse);
237                 }
238                 // other error
239                 throw new AuthenticationException(gsse.getMessage());
240             }
241         case TOKEN_GENERATED:
242             final String tokenstr = new String(base64codec.encode(token));
243             if (log.isDebugEnabled()) {
244                 log.debug("Sending response '" + tokenstr + "' back to the auth server");
245             }
246             final CharArrayBuffer buffer = new CharArrayBuffer(32);
247             if (isProxy()) {
248                 buffer.append(AUTH.PROXY_AUTH_RESP);
249             } else {
250                 buffer.append(AUTH.WWW_AUTH_RESP);
251             }
252             buffer.append(": Negotiate ");
253             buffer.append(tokenstr);
254             return new BufferedHeader(buffer);
255         default:
256             throw new IllegalStateException("Illegal state: " + state);
257         }
258     }
259 
260     @Override
261     protected void parseChallenge(
262             final CharArrayBuffer buffer,
263             final int beginIndex, final int endIndex) throws MalformedChallengeException {
264         final String challenge = buffer.substringTrimmed(beginIndex, endIndex);
265         if (log.isDebugEnabled()) {
266             log.debug("Received challenge '" + challenge + "' from the auth server");
267         }
268         if (state == State.UNINITIATED) {
269             token = Base64.decodeBase64(challenge.getBytes());
270             state = State.CHALLENGE_RECEIVED;
271         } else {
272             log.debug("Authentication already attempted");
273             state = State.FAILED;
274         }
275     }
276 
277     private String resolveCanonicalHostname(final String host) throws UnknownHostException {
278         final InetAddress in = InetAddress.getByName(host);
279         final String canonicalServer = in.getCanonicalHostName();
280         if (in.getHostAddress().contentEquals(canonicalServer)) {
281             return host;
282         }
283         return canonicalServer;
284     }
285 
286 }