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  
32  import org.apache.commons.codec.binary.Base64;
33  import org.apache.commons.logging.Log;
34  import org.apache.commons.logging.LogFactory;
35  import org.apache.http.Header;
36  import org.apache.http.HttpHost;
37  import org.apache.http.HttpRequest;
38  import org.apache.http.annotation.NotThreadSafe;
39  import org.apache.http.auth.AUTH;
40  import org.apache.http.auth.AuthenticationException;
41  import org.apache.http.auth.Credentials;
42  import org.apache.http.auth.InvalidCredentialsException;
43  import org.apache.http.auth.KerberosCredentials;
44  import org.apache.http.auth.MalformedChallengeException;
45  import org.apache.http.client.protocol.HttpClientContext;
46  import org.apache.http.conn.routing.HttpRoute;
47  import org.apache.http.message.BufferedHeader;
48  import org.apache.http.protocol.HttpContext;
49  import org.apache.http.util.Args;
50  import org.apache.http.util.CharArrayBuffer;
51  import org.ietf.jgss.GSSContext;
52  import org.ietf.jgss.GSSCredential;
53  import org.ietf.jgss.GSSException;
54  import org.ietf.jgss.GSSManager;
55  import org.ietf.jgss.GSSName;
56  import org.ietf.jgss.Oid;
57  
58  /**
59   * @since 4.2
60   */
61  @NotThreadSafe
62  public abstract class GGSSchemeBase extends AuthSchemeBase {
63  
64      enum State {
65          UNINITIATED,
66          CHALLENGE_RECEIVED,
67          TOKEN_GENERATED,
68          FAILED,
69      }
70  
71      private final Log log = LogFactory.getLog(getClass());
72  
73      private final Base64 base64codec;
74      private final boolean stripPort;
75      private final boolean useCanonicalHostname;
76  
77      /** Authentication process state */
78      private State state;
79  
80      /** base64 decoded challenge **/
81      private byte[] token;
82  
83      GGSSchemeBase(final boolean stripPort, final boolean useCanonicalHostname) {
84          super();
85          this.base64codec = new Base64(0);
86          this.stripPort = stripPort;
87          this.useCanonicalHostname = useCanonicalHostname;
88          this.state = State.UNINITIATED;
89      }
90  
91      GGSSchemeBase(final boolean stripPort) {
92          this(stripPort, true);
93      }
94  
95      GGSSchemeBase() {
96          this(true,true);
97      }
98  
99      protected GSSManager getManager() {
100         return GSSManager.getInstance();
101     }
102 
103     protected byte[] generateGSSToken(
104             final byte[] input, final Oid oid, final String authServer) throws GSSException {
105         return generateGSSToken(input, oid, authServer, null);
106     }
107 
108     /**
109      * @since 4.4
110      */
111     protected byte[] generateGSSToken(
112             final byte[] input, final Oid oid, final String authServer,
113             final Credentials credentials) throws GSSException {
114         byte[] inputBuff = input;
115         if (inputBuff == null) {
116             inputBuff = new byte[0];
117         }
118         final GSSManager manager = getManager();
119         final GSSName serverName = manager.createName("HTTP@" + authServer, GSSName.NT_HOSTBASED_SERVICE);
120 
121         final GSSCredential gssCredential;
122         if (credentials instanceof KerberosCredentials) {
123             gssCredential = ((KerberosCredentials) credentials).getGSSCredential();
124         } else {
125             gssCredential = null;
126         }
127 
128         final GSSContext gssContext = manager.createContext(
129                 serverName.canonicalize(oid), oid, gssCredential, GSSContext.DEFAULT_LIFETIME);
130         gssContext.requestMutualAuth(true);
131         gssContext.requestCredDeleg(true);
132         return gssContext.initSecContext(inputBuff, 0, inputBuff.length);
133     }
134 
135     /**
136      * @deprecated (4.4) Use {@link #generateToken(byte[], String, org.apache.http.auth.Credentials)}.
137      */
138     @Deprecated
139     protected byte[] generateToken(final byte[] input, final String authServer) throws GSSException {
140         return null;
141     }
142 
143     /**
144      * @since 4.4
145      */
146     //TODO: make this method abstract
147     @SuppressWarnings("deprecation")
148     protected byte[] generateToken(
149             final byte[] input, final String authServer, final Credentials credentials) throws GSSException {
150         return generateToken(input, authServer);
151     }
152 
153     @Override
154     public boolean isComplete() {
155         return this.state == State.TOKEN_GENERATED || this.state == State.FAILED;
156     }
157 
158     /**
159      * @deprecated (4.2) Use {@link org.apache.http.auth.ContextAwareAuthScheme#authenticate(
160      *   Credentials, HttpRequest, org.apache.http.protocol.HttpContext)}
161      */
162     @Override
163     @Deprecated
164     public Header authenticate(
165             final Credentials credentials,
166             final HttpRequest request) throws AuthenticationException {
167         return authenticate(credentials, request, null);
168     }
169 
170     @Override
171     public Header authenticate(
172             final Credentials credentials,
173             final HttpRequest request,
174             final HttpContext context) throws AuthenticationException {
175         Args.notNull(request, "HTTP request");
176         switch (state) {
177         case UNINITIATED:
178             throw new AuthenticationException(getSchemeName() + " authentication has not been initiated");
179         case FAILED:
180             throw new AuthenticationException(getSchemeName() + " authentication has failed");
181         case CHALLENGE_RECEIVED:
182             try {
183                 final HttpRoute route = (HttpRoute) context.getAttribute(HttpClientContext.HTTP_ROUTE);
184                 if (route == null) {
185                     throw new AuthenticationException("Connection route is not available");
186                 }
187                 HttpHost host;
188                 if (isProxy()) {
189                     host = route.getProxyHost();
190                     if (host == null) {
191                         host = route.getTargetHost();
192                     }
193                 } else {
194                     host = route.getTargetHost();
195                 }
196                 final String authServer;
197                 String hostname = host.getHostName();
198 
199                 if (this.useCanonicalHostname){
200                     try {
201                          //TODO: uncomment this statement and delete the resolveCanonicalHostname,
202                          //TODO: as soon canonical hostname resolving is implemented in the SystemDefaultDnsResolver
203                          //final DnsResolver dnsResolver = SystemDefaultDnsResolver.INSTANCE;
204                          //hostname = dnsResolver.resolveCanonicalHostname(host.getHostName());
205                          hostname = resolveCanonicalHostname(hostname);
206                     } catch (UnknownHostException ignore){
207                     }
208                 }
209                 if (this.stripPort) { // || host.getPort()==80 || host.getPort()==443) {
210                     authServer = hostname;
211                 } else {
212                     authServer = hostname + ":" + host.getPort();
213                 }
214 
215                 if (log.isDebugEnabled()) {
216                     log.debug("init " + authServer);
217                 }
218                 token = generateToken(token, authServer, credentials);
219                 state = State.TOKEN_GENERATED;
220             } catch (final GSSException gsse) {
221                 state = State.FAILED;
222                 if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL
223                         || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED) {
224                     throw new InvalidCredentialsException(gsse.getMessage(), gsse);
225                 }
226                 if (gsse.getMajor() == GSSException.NO_CRED ) {
227                     throw new InvalidCredentialsException(gsse.getMessage(), gsse);
228                 }
229                 if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN
230                         || gsse.getMajor() == GSSException.DUPLICATE_TOKEN
231                         || gsse.getMajor() == GSSException.OLD_TOKEN) {
232                     throw new AuthenticationException(gsse.getMessage(), gsse);
233                 }
234                 // other error
235                 throw new AuthenticationException(gsse.getMessage());
236             }
237         case TOKEN_GENERATED:
238             final String tokenstr = new String(base64codec.encode(token));
239             if (log.isDebugEnabled()) {
240                 log.debug("Sending response '" + tokenstr + "' back to the auth server");
241             }
242             final CharArrayBuffer buffer = new CharArrayBuffer(32);
243             if (isProxy()) {
244                 buffer.append(AUTH.PROXY_AUTH_RESP);
245             } else {
246                 buffer.append(AUTH.WWW_AUTH_RESP);
247             }
248             buffer.append(": Negotiate ");
249             buffer.append(tokenstr);
250             return new BufferedHeader(buffer);
251         default:
252             throw new IllegalStateException("Illegal state: " + state);
253         }
254     }
255 
256     @Override
257     protected void parseChallenge(
258             final CharArrayBuffer buffer,
259             final int beginIndex, final int endIndex) throws MalformedChallengeException {
260         final String challenge = buffer.substringTrimmed(beginIndex, endIndex);
261         if (log.isDebugEnabled()) {
262             log.debug("Received challenge '" + challenge + "' from the auth server");
263         }
264         if (state == State.UNINITIATED) {
265             token = Base64.decodeBase64(challenge.getBytes());
266             state = State.CHALLENGE_RECEIVED;
267         } else {
268             log.debug("Authentication already attempted");
269             state = State.FAILED;
270         }
271     }
272 
273     private String resolveCanonicalHostname(final String host) throws UnknownHostException {
274         final InetAddress in = InetAddress.getByName(host);
275         final String canonicalServer = in.getCanonicalHostName();
276         if (in.getHostAddress().contentEquals(canonicalServer)) {
277             return host;
278         }
279         return canonicalServer;
280     }
281 
282 }