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.win;
28  
29  import java.io.IOException;
30  
31  import com.sun.jna.platform.win32.Sspi.CtxtHandle;
32  import com.sun.jna.platform.win32.Sspi.SecBufferDesc;
33  import com.sun.jna.platform.win32.Win32Exception;
34  import com.sun.jna.platform.win32.WinError;
35  import org.apache.http.HttpException;
36  import org.apache.http.HttpHost;
37  import org.apache.http.HttpRequest;
38  import org.apache.http.HttpResponse;
39  import org.apache.http.HttpStatus;
40  import org.apache.http.auth.AUTH;
41  import org.apache.http.auth.AuthScheme;
42  import org.apache.http.auth.AuthSchemeProvider;
43  import org.apache.http.client.CredentialsProvider;
44  import org.apache.http.client.config.AuthSchemes;
45  import org.apache.http.client.methods.CloseableHttpResponse;
46  import org.apache.http.client.methods.HttpGet;
47  import org.apache.http.config.Registry;
48  import org.apache.http.config.RegistryBuilder;
49  import org.apache.http.impl.client.CloseableHttpClient;
50  import org.apache.http.impl.client.HttpClientBuilder;
51  import org.apache.http.impl.client.SystemDefaultCredentialsProvider;
52  import org.apache.http.impl.client.WinHttpClients;
53  import org.apache.http.localserver.LocalServerTestBase;
54  import org.apache.http.protocol.HttpContext;
55  import org.apache.http.protocol.HttpRequestHandler;
56  import org.apache.http.util.EntityUtils;
57  import org.junit.After;
58  import org.junit.Assume;
59  import org.junit.Before;
60  import org.junit.Test;
61  
62  /**
63   * Unit tests for Windows negotiate authentication.
64   */
65  public class TestWindowsNegotiateScheme extends LocalServerTestBase {
66  
67      @Before @Override
68      public void setUp() throws Exception {
69          super.setUp();
70          this.serverBootstrap.registerHandler("/", new HttpRequestHandler() {
71  
72              @Override
73              public void handle(
74                      final HttpRequest request,
75                      final HttpResponse response,
76                      final HttpContext context) throws HttpException, IOException {
77                  response.addHeader(AUTH.WWW_AUTH, AuthSchemes.SPNEGO);
78                  response.setStatusCode(HttpStatus.SC_UNAUTHORIZED);
79              }
80  
81          });
82      }
83  
84      @After @Override
85      public void shutDown() throws Exception {
86          super.shutDown();
87      }
88  
89      @Test(timeout=30000) // this timeout (in ms) needs to be extended if you're actively debugging the code
90      public void testNoInfiniteLoopOnSPNOutsideDomain() throws Exception {
91          Assume.assumeTrue("Test can only be run on Windows", WinHttpClients.isWinAuthAvailable());
92  
93          // HTTPCLIENT-1545
94          // If a service principal name (SPN) from outside your Windows domain tree (e.g., HTTP/example.com) is used,
95          // InitializeSecurityContext will return SEC_E_DOWNGRADE_DETECTED (decimal: -2146892976, hex: 0x80090350).
96          // Because WindowsNegotiateScheme wasn't setting the completed state correctly when authentication fails,
97          // HttpClient goes into an infinite loop, constantly retrying the negotiate authentication to kingdom
98          // come. This error message, "The system detected a possible attempt to compromise security. Please ensure that
99          // you can contact the server that authenticated you." is associated with SEC_E_DOWNGRADE_DETECTED.
100 
101         final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
102             .register(AuthSchemes.SPNEGO, new AuthSchemeProvider() {
103                 @Override
104                 public AuthScheme create(final HttpContext context) {
105                     return new WindowsNegotiateSchemeGetTokenFail(AuthSchemes.SPNEGO, "HTTP/example.com");
106                 }
107             }).build();
108         final CredentialsProvider credsProvider =
109                 new WindowsCredentialsProvider(new SystemDefaultCredentialsProvider());
110         final CloseableHttpClient customClient = HttpClientBuilder.create()
111                 .setDefaultCredentialsProvider(credsProvider)
112                 .setDefaultAuthSchemeRegistry(authSchemeRegistry).build();
113         try {
114             final HttpHost target = start();
115             final HttpGet httpGet = new HttpGet("/");
116             final CloseableHttpResponse response = customClient.execute(target, httpGet);
117             try {
118                 EntityUtils.consume(response.getEntity());
119             } finally {
120                 response.close();
121             }
122         }finally {
123             customClient.close();
124         }
125     }
126 
127     private final class WindowsNegotiateSchemeGetTokenFail extends WindowsNegotiateScheme {
128 
129         public WindowsNegotiateSchemeGetTokenFail(final String scheme, final String servicePrincipalName) {
130             super(scheme, servicePrincipalName);
131         }
132 
133         @Override
134         String getToken(final CtxtHandle continueCtx, final SecBufferDesc continueToken, final String targetName) {
135             dispose();
136             /* We will rather throw SEC_E_TARGET_UNKNOWN because SEC_E_DOWNGRADE_DETECTED is not
137              * available on Windows XP and this unit test always fails.
138              */
139             throw new Win32Exception(WinError.SEC_E_TARGET_UNKNOWN);
140         }
141 
142     }
143 
144 }