1/* 2 * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26package sun.net.www.protocol.http; 27 28import java.net.URL; 29import java.io.IOException; 30import java.net.Authenticator.RequestorType; 31import java.util.Base64; 32import java.util.HashMap; 33import sun.net.www.HeaderParser; 34import sun.util.logging.PlatformLogger; 35import static sun.net.www.protocol.http.AuthScheme.NEGOTIATE; 36import static sun.net.www.protocol.http.AuthScheme.KERBEROS; 37import sun.security.action.GetPropertyAction; 38 39/** 40 * NegotiateAuthentication: 41 * 42 * @author weijun.wang@sun.com 43 * @since 1.6 44 */ 45 46class NegotiateAuthentication extends AuthenticationInfo { 47 48 private static final long serialVersionUID = 100L; 49 private static final PlatformLogger logger = HttpURLConnection.getHttpLogger(); 50 51 private final HttpCallerInfo hci; 52 53 // These maps are used to manage the GSS availability for diffrent 54 // hosts. The key for both maps is the host name. 55 // <code>supported</code> is set when isSupported is checked, 56 // if it's true, a cached Negotiator is put into <code>cache</code>. 57 // the cache can be used only once, so after the first use, it's cleaned. 58 static HashMap <String, Boolean> supported = null; 59 static ThreadLocal <HashMap <String, Negotiator>> cache = null; 60 /* Whether cache is enabled for Negotiate/Kerberos */ 61 private static final boolean cacheSPNEGO; 62 static { 63 String spnegoCacheProp = 64 GetPropertyAction.privilegedGetProperty("jdk.spnego.cache", "true"); 65 cacheSPNEGO = Boolean.parseBoolean(spnegoCacheProp); 66 } 67 68 // The HTTP Negotiate Helper 69 private Negotiator negotiator = null; 70 71 /** 72 * Constructor used for both WWW and proxy entries. 73 * @param hci a schemed object. 74 */ 75 public NegotiateAuthentication(HttpCallerInfo hci) { 76 super(RequestorType.PROXY==hci.authType ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION, 77 hci.scheme.equalsIgnoreCase("Negotiate") ? NEGOTIATE : KERBEROS, 78 hci.url, 79 "", 80 AuthenticatorKeys.getKey(hci.authenticator)); 81 this.hci = hci; 82 } 83 84 /** 85 * @return true if this authentication supports preemptive authorization 86 */ 87 @Override 88 public boolean supportsPreemptiveAuthorization() { 89 return false; 90 } 91 92 /** 93 * Find out if the HttpCallerInfo supports Negotiate protocol. 94 * @return true if supported 95 */ 96 public static boolean isSupported(HttpCallerInfo hci) { 97 ClassLoader loader = null; 98 try { 99 loader = Thread.currentThread().getContextClassLoader(); 100 } catch (SecurityException se) { 101 if (logger.isLoggable(PlatformLogger.Level.FINER)) { 102 logger.finer("NegotiateAuthentication: " + 103 "Attempt to get the context class loader failed - " + se); 104 } 105 } 106 107 if (loader != null) { 108 // Lock on the class loader instance to avoid the deadlock engaging 109 // the lock in "ClassLoader.loadClass(String, boolean)" method. 110 synchronized (loader) { 111 return isSupportedImpl(hci); 112 } 113 } 114 return isSupportedImpl(hci); 115 } 116 117 /** 118 * Find out if the HttpCallerInfo supports Negotiate protocol. In order to 119 * find out yes or no, an initialization of a Negotiator object against it 120 * is tried. The generated object will be cached under the name of ths 121 * hostname at a success try.<br> 122 * 123 * If this method is called for the second time on an HttpCallerInfo with 124 * the same hostname, the answer is retrieved from cache. 125 * 126 * @return true if supported 127 */ 128 private static synchronized boolean isSupportedImpl(HttpCallerInfo hci) { 129 if (supported == null) { 130 supported = new HashMap<>(); 131 } 132 String hostname = hci.host; 133 hostname = hostname.toLowerCase(); 134 if (supported.containsKey(hostname)) { 135 return supported.get(hostname); 136 } 137 138 Negotiator neg = Negotiator.getNegotiator(hci); 139 if (neg != null) { 140 supported.put(hostname, true); 141 // the only place cache.put is called. here we can make sure 142 // the object is valid and the oneToken inside is not null 143 if (cache == null) { 144 cache = new ThreadLocal<>() { 145 @Override 146 protected HashMap<String, Negotiator> initialValue() { 147 return new HashMap<>(); 148 } 149 }; 150 } 151 cache.get().put(hostname, neg); 152 return true; 153 } else { 154 supported.put(hostname, false); 155 return false; 156 } 157 } 158 159 private static synchronized HashMap<String, Negotiator> getCache() { 160 if (cache == null) return null; 161 return cache.get(); 162 } 163 164 @Override 165 protected boolean useAuthCache() { 166 return super.useAuthCache() && cacheSPNEGO; 167 } 168 169 /** 170 * Not supported. Must use the setHeaders() method 171 */ 172 @Override 173 public String getHeaderValue(URL url, String method) { 174 throw new RuntimeException ("getHeaderValue not supported"); 175 } 176 177 /** 178 * Check if the header indicates that the current auth. parameters are stale. 179 * If so, then replace the relevant field with the new value 180 * and return true. Otherwise return false. 181 * returning true means the request can be retried with the same userid/password 182 * returning false means we have to go back to the user to ask for a new 183 * username password. 184 */ 185 @Override 186 public boolean isAuthorizationStale (String header) { 187 return false; /* should not be called for Negotiate */ 188 } 189 190 /** 191 * Set header(s) on the given connection. 192 * @param conn The connection to apply the header(s) to 193 * @param p A source of header values for this connection, not used because 194 * HeaderParser converts the fields to lower case, use raw instead 195 * @param raw The raw header field. 196 * @return true if all goes well, false if no headers were set. 197 */ 198 @Override 199 public synchronized boolean setHeaders(HttpURLConnection conn, HeaderParser p, String raw) { 200 201 try { 202 String response; 203 byte[] incoming = null; 204 String[] parts = raw.split("\\s+"); 205 if (parts.length > 1) { 206 incoming = Base64.getDecoder().decode(parts[1]); 207 } 208 response = hci.scheme + " " + Base64.getEncoder().encodeToString( 209 incoming==null?firstToken():nextToken(incoming)); 210 211 conn.setAuthenticationProperty(getHeaderName(), response); 212 return true; 213 } catch (IOException e) { 214 return false; 215 } 216 } 217 218 /** 219 * return the first token. 220 * @return the token 221 * @throws IOException if <code>Negotiator.getNegotiator()</code> or 222 * <code>Negotiator.firstToken()</code> failed. 223 */ 224 private byte[] firstToken() throws IOException { 225 negotiator = null; 226 HashMap <String, Negotiator> cachedMap = getCache(); 227 if (cachedMap != null) { 228 negotiator = cachedMap.get(getHost()); 229 if (negotiator != null) { 230 cachedMap.remove(getHost()); // so that it is only used once 231 } 232 } 233 if (negotiator == null) { 234 negotiator = Negotiator.getNegotiator(hci); 235 if (negotiator == null) { 236 IOException ioe = new IOException("Cannot initialize Negotiator"); 237 throw ioe; 238 } 239 } 240 241 return negotiator.firstToken(); 242 } 243 244 /** 245 * return more tokens 246 * @param token the token to be fed into <code>negotiator.nextToken()</code> 247 * @return the token 248 * @throws IOException if <code>negotiator.nextToken()</code> throws Exception. 249 * May happen if the input token is invalid. 250 */ 251 private byte[] nextToken(byte[] token) throws IOException { 252 return negotiator.nextToken(token); 253 } 254 255 // MS will send a final WWW-Authenticate even if the status is already 256 // 200 OK. The token can be fed into initSecContext() again to determine 257 // if the server can be trusted. This is not the same concept as Digest's 258 // Authentication-Info header. 259 // 260 // Currently we ignore this header. 261 262} 263