View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit;
16  
17  import java.io.IOException;
18  import java.io.ObjectInputStream;
19  import java.io.ObjectOutputStream;
20  import java.io.Serializable;
21  import java.net.Authenticator;
22  import java.net.PasswordAuthentication;
23  import java.util.HashMap;
24  import java.util.Map;
25  
26  import org.apache.http.auth.AuthScope;
27  import org.apache.http.auth.Credentials;
28  import org.apache.http.auth.NTCredentials;
29  import org.apache.http.auth.UsernamePasswordCredentials;
30  import org.apache.http.client.CredentialsProvider;
31  import org.htmlunit.httpclient.HtmlUnitUsernamePasswordCredentials;
32  import org.htmlunit.util.SerializableLock;
33  
34  /**
35   * Default HtmlUnit implementation of the {@code CredentialsProvider} interface. Provides
36   * credentials for both web servers and proxies. Supports Digest
37   * authentication, Socks authentication and Basic HTTP authentication.
38   *
39   * @author Daniel Gredler
40   * @author Vikram Shitole
41   * @author Marc Guillemot
42   * @author Ahmed Ashour
43   * @author Nicolas Belisle
44   * @author Ronald Brill
45   */
46  public class DefaultCredentialsProvider implements CredentialsProvider, Serializable {
47  
48      /** The {@code null} value represents any host. */
49      public static final String ANY_HOST = null;
50  
51      /** The {@code -1} value represents any port. */
52      public static final int ANY_PORT = -1;
53  
54      /** The {@code null} value represents any realm. */
55      public static final String ANY_REALM = null;
56  
57      /** The {@code null} value represents any authentication scheme. */
58      public static final String ANY_SCHEME = null;
59  
60      // volatile: written only inside initSocksAuthenticatorIfNeeded (guarded by SOCKS_AUTHENTICATOR_LOCK),
61      // but declared volatile to guard against unsynchronized reads in future refactors.
62      private static volatile SocksProxyAuthenticator SocksAuthenticator_;
63      private static final Object SOCKS_AUTHENTICATOR_LOCK = new Object();
64  
65      /** Guards the {@link #credentialsMap_}. */
66      private final SerializableLock lock_ = new SerializableLock();
67      private final Map<AuthScopeProxy, Credentials> credentialsMap_ = new HashMap<>();
68  
69      // Because this is used for the whole JVM I try to make it as less invasive as possible.
70      // But in general this might disturb other application running on the same JVM.
71      private static final class SocksProxyAuthenticator extends Authenticator {
72          private CredentialsProvider credentialsProvider_;
73  
74          @Override
75          protected PasswordAuthentication getPasswordAuthentication() {
76              // java.base/java/net/SocksSocketImpl.java line 154 ff
77              // no RequestorType set from java - we have to check the requesting prompt string
78              final boolean isProxy = Authenticator.RequestorType.PROXY.equals(getRequestorType())
79                      || "SOCKS authentication".equals(getRequestingPrompt());
80              if (!isProxy) {
81                  return null;
82              }
83  
84              final AuthScope authScope = new AuthScope(getRequestingHost(), getRequestingPort(), getRequestingScheme());
85              final Credentials credentials = credentialsProvider_.getCredentials(authScope);
86              if (credentials == null) {
87                  return null;
88              }
89  
90              return new PasswordAuthentication(credentials.getUserPrincipal().getName(),
91                      credentials.getPassword().toCharArray());
92          }
93      }
94  
95      /**
96       * Adds credentials for the specified username/password for any host/port/realm combination.
97       * The credentials may be for any authentication scheme, including NTLM, digest and basic
98       * HTTP authentication. If you are using sensitive username/password information, please do
99       * NOT use this method. If you add credentials using this method, any server that requires
100      * authentication may receive the specified username and password.
101      *
102      * @param username the username for the new credentials
103      * @param password the password for the new credentials
104      * @see #addCredentials(String, char[], String, int, String)
105      */
106     public void addCredentials(final String username, final char[] password) {
107         addCredentials(username, password, ANY_HOST, ANY_PORT, ANY_REALM);
108     }
109 
110     /**
111      * Adds credentials for the specified username/password on the specified host/port for the
112      * specified realm. The credentials may be for any authentication scheme, including NTLM,
113      * digest and basic HTTP authentication.
114      *
115      * @param username the username for the new credentials
116      * @param password the password for the new credentials
117      * @param host the host to which to the new credentials apply ({@code null} if applicable to any host)
118      * @param port the port to which to the new credentials apply (negative if applicable to any port)
119      * @param realm the realm to which to the new credentials apply ({@code null} if applicable to any realm)
120      */
121     public void addCredentials(final String username, final char[] password, final String host,
122             final int port, final String realm) {
123         final AuthScope authscope = new AuthScope(host, port, realm, ANY_SCHEME);
124         final HtmlUnitUsernamePasswordCredentials credentials =
125                     new HtmlUnitUsernamePasswordCredentials(username, password);
126         setCredentials(authscope, credentials);
127     }
128 
129     /**
130      * Adds NTLM credentials for the specified username/password on the specified host/port.
131      *
132      * <p>Note: due to a limitation of the underlying {@link NTCredentials} class, the password
133      * is converted to a {@link String} internally and cannot be zeroed from memory after use.
134      * </p>
135      *
136      * @param username the username for the new credentials; should not include the domain to authenticate with;
137      *        for example: {@code "user"} is correct whereas {@code "DOMAIN\\user"} is not
138      * @param password the password for the new credentials
139      * @param host the host to which to the new credentials apply ({@code null} if applicable to any host)
140      * @param port the port to which to the new credentials apply (negative if applicable to any port)
141      * @param workstation the workstation the authentication request is originating from;
142      *        essentially, the computer name for this machine
143      * @param domain the domain to authenticate within
144      */
145     public void addNTLMCredentials(final String username, final char[] password, final String host,
146             final int port, final String workstation, final String domain) {
147         final AuthScope authscope = new AuthScope(host, port, ANY_REALM, ANY_SCHEME);
148         final NTCredentials credentials = new NTCredentials(username, String.valueOf(password), workstation, domain);
149         setCredentials(authscope, credentials);
150     }
151 
152     /**
153      * Adds Socks credentials for the specified username/password on the specified host/port.
154      *
155      * <p>Note: the SOCKS authenticator is a JVM-wide singleton. If multiple
156      * {@link DefaultCredentialsProvider} instances add SOCKS credentials, only the first
157      * instance's credentials will be used for SOCKS authentication.
158      * </p>
159      *
160      * @param username the username for the new credentials
161      * @param password the password for the new credentials
162      * @param host the host to which to the new credentials apply ({@code null} if applicable to any host)
163      * @param port the port to which to the new credentials apply (negative if applicable to any port)
164      */
165     public void addSocksCredentials(final String username, final char[] password, final String host,
166             final int port) {
167         final AuthScope authscope = new AuthScope(host, port, ANY_REALM, ANY_SCHEME);
168         final HtmlUnitUsernamePasswordCredentials credentials =
169                     new HtmlUnitUsernamePasswordCredentials(username, password);
170         setCredentials(authscope, credentials);
171 
172         initSocksAuthenticatorIfNeeded(this);
173     }
174 
175     private static void initSocksAuthenticatorIfNeeded(final CredentialsProvider provider) {
176         synchronized (SOCKS_AUTHENTICATOR_LOCK) {
177             if (SocksAuthenticator_ == null) {
178                 SocksAuthenticator_ = new SocksProxyAuthenticator();
179                 SocksAuthenticator_.credentialsProvider_ = provider;
180 
181                 Authenticator.setDefault(SocksAuthenticator_);
182             }
183         }
184     }
185 
186     /**
187      * {@inheritDoc}
188      *
189      * @throws IllegalArgumentException if {@code authscope} is {@code null}, if {@code credentials}
190      *         is {@code null}, or if the credentials type is not one of
191      *         {@link UsernamePasswordCredentials}, {@link HtmlUnitUsernamePasswordCredentials},
192      *         or {@link NTCredentials}
193      */
194     @Override
195     public void setCredentials(final AuthScope authscope, final Credentials credentials) {
196         if (authscope == null) {
197             throw new IllegalArgumentException("Authentication scope may not be null");
198         }
199         if (credentials == null) {
200             throw new IllegalArgumentException("Credentials may not be null");
201         }
202 
203         if (credentials instanceof UsernamePasswordCredentials
204                 || credentials instanceof HtmlUnitUsernamePasswordCredentials
205                 || credentials instanceof NTCredentials) {
206             synchronized (lock_) {
207                 credentialsMap_.put(new AuthScopeProxy(authscope), credentials);
208             }
209             return;
210         }
211 
212         throw new IllegalArgumentException("Unsupported Credential type: " + credentials.getClass().getName());
213     }
214 
215     // Callers must hold the lock_ of the enclosing DefaultCredentialsProvider instance.
216     private static Credentials matchCredentials(final Map<AuthScopeProxy, Credentials> map, final AuthScope authscope) {
217         Credentials creds = map.get(new AuthScopeProxy(authscope));
218         if (creds == null) {
219             int bestMatchFactor = -1;
220             AuthScopeProxy bestMatch = null;
221             for (final AuthScopeProxy proxy : map.keySet()) {
222                 final AuthScope current = proxy.getAuthScope();
223                 final int factor = authscope.match(current);
224                 if (factor > bestMatchFactor) {
225                     bestMatchFactor = factor;
226                     bestMatch = proxy;
227                 }
228             }
229             if (bestMatch != null) {
230                 creds = map.get(bestMatch);
231             }
232         }
233         return creds;
234     }
235 
236     /**
237      * {@inheritDoc}
238      */
239     @Override
240     public Credentials getCredentials(final AuthScope authscope) {
241         if (authscope == null) {
242             throw new IllegalArgumentException("Authentication scope may not be null");
243         }
244         synchronized (lock_) {
245             return matchCredentials(credentialsMap_, authscope);
246         }
247     }
248 
249     /**
250      * Removes the credentials that best match the given {@link AuthScope}.
251      * An exact scope match is preferred over a fuzzy best-match, consistent
252      * with the resolution strategy used by {@link #getCredentials(AuthScope)}.
253      *
254      * @param authscope the {@link AuthScope} whose credentials should be removed;
255      *        must not be {@code null}
256      * @return {@code true} if credentials were removed; {@code false} if no match was found
257      */
258     public boolean removeCredentials(final AuthScope authscope) {
259         if (authscope == null) {
260             throw new IllegalArgumentException("Authentication scope may not be null");
261         }
262 
263         synchronized (lock_) {
264             // try exact match first, consistent with matchCredentials
265             final AuthScopeProxy exactKey = new AuthScopeProxy(authscope);
266             if (credentialsMap_.remove(exactKey) != null) {
267                 return true;
268             }
269 
270             // fall back to best-match scoring
271             int bestMatchFactor = -1;
272             AuthScopeProxy bestMatch = null;
273             for (final AuthScopeProxy proxy : credentialsMap_.keySet()) {
274                 final AuthScope current = proxy.getAuthScope();
275                 final int factor = authscope.match(current);
276                 if (factor > bestMatchFactor) {
277                     bestMatchFactor = factor;
278                     bestMatch = proxy;
279                 }
280             }
281             return credentialsMap_.remove(bestMatch) != null;
282         }
283     }
284 
285     /**
286      * {@inheritDoc}
287      */
288     @Override
289     public String toString() {
290         synchronized (lock_) {
291             return credentialsMap_.toString();
292         }
293     }
294 
295     /**
296      * {@inheritDoc}
297      */
298     @Override
299     public void clear() {
300         synchronized (lock_) {
301             credentialsMap_.clear();
302         }
303     }
304 
305     /**
306      * Serialization proxy for {@link AuthScope}, which is not itself {@link Serializable}.
307      * Required to allow {@link DefaultCredentialsProvider} to be serialized correctly.
308      */
309     private static class AuthScopeProxy implements Serializable {
310         private AuthScope authScope_;
311 
312         AuthScopeProxy(final AuthScope authScope) {
313             authScope_ = authScope;
314         }
315 
316         public AuthScope getAuthScope() {
317             return authScope_;
318         }
319 
320         private void writeObject(final ObjectOutputStream stream) throws IOException {
321             stream.writeObject(authScope_.getHost());
322             stream.writeInt(authScope_.getPort());
323             stream.writeObject(authScope_.getRealm());
324             stream.writeObject(authScope_.getScheme());
325         }
326 
327         private void readObject(final ObjectInputStream stream) throws IOException, ClassNotFoundException {
328             final String host = (String) stream.readObject();
329             final int port = stream.readInt();
330             final String realm = (String) stream.readObject();
331             final String scheme = (String) stream.readObject();
332             authScope_ = new AuthScope(host, port, realm, scheme);
333         }
334 
335         @Override
336         public int hashCode() {
337             return authScope_.hashCode();
338         }
339 
340         @Override
341         public boolean equals(final Object obj) {
342             return obj instanceof AuthScopeProxy asp && authScope_.equals(asp.getAuthScope());
343         }
344     }
345 }