View Javadoc
1   /*
2    * Copyright (C) 2010, 2013, Google Inc.
3    * and other copyright owners as documented in the project's IP log.
4    *
5    * This program and the accompanying materials are made available
6    * under the terms of the Eclipse Distribution License v1.0 which
7    * accompanies this distribution, is reproduced below, and is
8    * available at http://www.eclipse.org/org/documents/edl-v10.php
9    *
10   * All rights reserved.
11   *
12   * Redistribution and use in source and binary forms, with or
13   * without modification, are permitted provided that the following
14   * conditions are met:
15   *
16   * - Redistributions of source code must retain the above copyright
17   *   notice, this list of conditions and the following disclaimer.
18   *
19   * - Redistributions in binary form must reproduce the above
20   *   copyright notice, this list of conditions and the following
21   *   disclaimer in the documentation and/or other materials provided
22   *   with the distribution.
23   *
24   * - Neither the name of the Eclipse Foundation, Inc. nor the
25   *   names of its contributors may be used to endorse or promote
26   *   products derived from this software without specific prior
27   *   written permission.
28   *
29   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
30   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
31   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
34   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
38   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42   */
43  
44  package org.eclipse.jgit.transport;
45  
46  import static org.eclipse.jgit.util.HttpSupport.HDR_AUTHORIZATION;
47  import static org.eclipse.jgit.util.HttpSupport.HDR_WWW_AUTHENTICATE;
48  
49  import java.io.IOException;
50  import java.io.UnsupportedEncodingException;
51  import java.net.URL;
52  import java.security.MessageDigest;
53  import java.security.NoSuchAlgorithmException;
54  import java.util.Collection;
55  import java.util.Collections;
56  import java.util.HashMap;
57  import java.util.LinkedHashMap;
58  import java.util.List;
59  import java.util.Locale;
60  import java.util.Map;
61  import java.util.Map.Entry;
62  import java.util.Random;
63  
64  import org.eclipse.jgit.transport.http.HttpConnection;
65  import org.eclipse.jgit.util.Base64;
66  import org.eclipse.jgit.util.GSSManagerFactory;
67  import org.ietf.jgss.GSSContext;
68  import org.ietf.jgss.GSSException;
69  import org.ietf.jgss.GSSManager;
70  import org.ietf.jgss.GSSName;
71  import org.ietf.jgss.Oid;
72  
73  /**
74   * Support class to populate user authentication data on a connection.
75   * <p>
76   * Instances of an HttpAuthMethod are not thread-safe, as some implementations
77   * may need to maintain per-connection state information.
78   */
79  abstract class HttpAuthMethod {
80  	/**
81  	 * Enum listing the http authentication method types supported by jgit. They
82  	 * are sorted by priority order!!!
83  	 */
84  	public enum Type {
85  		NONE {
86  			@Override
87  			public HttpAuthMethod method(String hdr) {
88  				return None.INSTANCE;
89  			}
90  
91  			@Override
92  			public String getSchemeName() {
93  				return "None"; //$NON-NLS-1$
94  			}
95  		},
96  		BASIC {
97  			@Override
98  			public HttpAuthMethod method(String hdr) {
99  				return new Basic();
100 			}
101 
102 			@Override
103 			public String getSchemeName() {
104 				return "Basic"; //$NON-NLS-1$
105 			}
106 		},
107 		DIGEST {
108 			@Override
109 			public HttpAuthMethod method(String hdr) {
110 				return new Digest(hdr);
111 			}
112 
113 			@Override
114 			public String getSchemeName() {
115 				return "Digest"; //$NON-NLS-1$
116 			}
117 		},
118 		NEGOTIATE {
119 			@Override
120 			public HttpAuthMethod method(String hdr) {
121 				return new Negotiate(hdr);
122 			}
123 
124 			@Override
125 			public String getSchemeName() {
126 				return "Negotiate"; //$NON-NLS-1$
127 			}
128 		};
129 		/**
130 		 * Creates a HttpAuthMethod instance configured with the provided HTTP
131 		 * WWW-Authenticate header.
132 		 *
133 		 * @param hdr the http header
134 		 * @return a configured HttpAuthMethod instance
135 		 */
136 		public abstract HttpAuthMethod method(String hdr);
137 
138 		/**
139 		 * @return the name of the authentication scheme in the form to be used
140 		 *         in HTTP authentication headers as specified in RFC2617 and
141 		 *         RFC4559
142 		 */
143 		public abstract String getSchemeName();
144 	}
145 
146 	static final String EMPTY_STRING = ""; //$NON-NLS-1$
147 	static final String SCHEMA_NAME_SEPARATOR = " "; //$NON-NLS-1$
148 
149 	/**
150 	 * Handle an authentication failure and possibly return a new response.
151 	 *
152 	 * @param conn
153 	 *            the connection that failed.
154 	 * @param ignoreTypes
155 	 *            authentication types to be ignored.
156 	 * @return new authentication method to try.
157 	 */
158 	static HttpAuthMethod scanResponse(final HttpConnection conn,
159 			Collection<Type> ignoreTypes) {
160 		final Map<String, List<String>> headers = conn.getHeaderFields();
161 		HttpAuthMethod authentication = Type.NONE.method(EMPTY_STRING);
162 
163 		for (final Entry<String, List<String>> entry : headers.entrySet()) {
164 			if (HDR_WWW_AUTHENTICATE.equalsIgnoreCase(entry.getKey())) {
165 				if (entry.getValue() != null) {
166 					for (final String value : entry.getValue()) {
167 						if (value != null && value.length() != 0) {
168 							final String[] valuePart = value.split(
169 									SCHEMA_NAME_SEPARATOR, 2);
170 
171 							try {
172 								Type methodType = Type.valueOf(
173 										valuePart[0].toUpperCase(Locale.ROOT));
174 
175 								if ((ignoreTypes != null)
176 										&& (ignoreTypes.contains(methodType))) {
177 									continue;
178 								}
179 
180 								if (authentication.getType().compareTo(methodType) >= 0) {
181 									continue;
182 								}
183 
184 								final String param;
185 								if (valuePart.length == 1)
186 									param = EMPTY_STRING;
187 								else
188 									param = valuePart[1];
189 
190 								authentication = methodType
191 										.method(param);
192 							} catch (IllegalArgumentException e) {
193 								// This auth method is not supported
194 							}
195 						}
196 					}
197 				}
198 				break;
199 			}
200 		}
201 
202 		return authentication;
203 	}
204 
205 	protected final Type type;
206 
207 	protected HttpAuthMethod(Type type) {
208 		this.type = type;
209 	}
210 
211 	/**
212 	 * Update this method with the credentials from the URIish.
213 	 *
214 	 * @param uri
215 	 *            the URI used to create the connection.
216 	 * @param credentialsProvider
217 	 *            the credentials provider, or null. If provided,
218 	 *            {@link URIish#getPass() credentials in the URI} are ignored.
219 	 *
220 	 * @return true if the authentication method is able to provide
221 	 *         authorization for the given URI
222 	 */
223 	boolean authorize(URIish uri, CredentialsProvider credentialsProvider) {
224 		String username;
225 		String password;
226 
227 		if (credentialsProvider != null) {
228 			CredentialItem.Username u = new CredentialItem.Username();
229 			CredentialItem.Password p = new CredentialItem.Password();
230 
231 			if (credentialsProvider.supports(u, p)
232 					&& credentialsProvider.get(uri, u, p)) {
233 				username = u.getValue();
234 				char[] v = p.getValue();
235 				password = (v == null) ? null : new String(p.getValue());
236 				p.clear();
237 			} else
238 				return false;
239 		} else {
240 			username = uri.getUser();
241 			password = uri.getPass();
242 		}
243 		if (username != null) {
244 			authorize(username, password);
245 			return true;
246 		}
247 		return false;
248 	}
249 
250 	/**
251 	 * Update this method with the given username and password pair.
252 	 *
253 	 * @param user
254 	 * @param pass
255 	 */
256 	abstract void authorize(String user, String pass);
257 
258 	/**
259 	 * Update connection properties based on this authentication method.
260 	 *
261 	 * @param conn
262 	 * @throws IOException
263 	 */
264 	abstract void configureRequest(HttpConnection conn) throws IOException;
265 
266 	/**
267 	 * Gives the method type associated to this http auth method
268 	 *
269 	 * @return the method type
270 	 */
271 	public Type getType() {
272 		return type;
273 	}
274 
275 	/** Performs no user authentication. */
276 	private static class None extends HttpAuthMethod {
277 		static final None INSTANCE = new None();
278 		public None() {
279 			super(Type.NONE);
280 		}
281 
282 		@Override
283 		void authorize(String user, String pass) {
284 			// Do nothing when no authentication is enabled.
285 		}
286 
287 		@Override
288 		void configureRequest(HttpConnection conn) throws IOException {
289 			// Do nothing when no authentication is enabled.
290 		}
291 	}
292 
293 	/** Performs HTTP basic authentication (plaintext username/password). */
294 	private static class Basic extends HttpAuthMethod {
295 		private String user;
296 
297 		private String pass;
298 
299 		public Basic() {
300 			super(Type.BASIC);
301 		}
302 
303 		@Override
304 		void authorize(final String username, final String password) {
305 			this.user = username;
306 			this.pass = password;
307 		}
308 
309 		@Override
310 		void configureRequest(final HttpConnection conn) throws IOException {
311 			String ident = user + ":" + pass; //$NON-NLS-1$
312 			String enc = Base64.encodeBytes(ident.getBytes("UTF-8")); //$NON-NLS-1$
313 			conn.setRequestProperty(HDR_AUTHORIZATION, type.getSchemeName()
314 					+ " " + enc); //$NON-NLS-1$
315 		}
316 	}
317 
318 	/** Performs HTTP digest authentication. */
319 	private static class Digest extends HttpAuthMethod {
320 		private static final Random PRNG = new Random();
321 
322 		private final Map<String, String> params;
323 
324 		private int requestCount;
325 
326 		private String user;
327 
328 		private String pass;
329 
330 		Digest(String hdr) {
331 			super(Type.DIGEST);
332 			params = parse(hdr);
333 
334 			final String qop = params.get("qop"); //$NON-NLS-1$
335 			if ("auth".equals(qop)) { //$NON-NLS-1$
336 				final byte[] bin = new byte[8];
337 				PRNG.nextBytes(bin);
338 				params.put("cnonce", Base64.encodeBytes(bin)); //$NON-NLS-1$
339 			}
340 		}
341 
342 		@Override
343 		void authorize(final String username, final String password) {
344 			this.user = username;
345 			this.pass = password;
346 		}
347 
348 		@SuppressWarnings("boxing")
349 		@Override
350 		void configureRequest(final HttpConnection conn) throws IOException {
351 			final Map<String, String> r = new LinkedHashMap<>();
352 
353 			final String realm = params.get("realm"); //$NON-NLS-1$
354 			final String nonce = params.get("nonce"); //$NON-NLS-1$
355 			final String cnonce = params.get("cnonce"); //$NON-NLS-1$
356 			final String uri = uri(conn.getURL());
357 			final String qop = params.get("qop"); //$NON-NLS-1$
358 			final String method = conn.getRequestMethod();
359 
360 			final String A1 = user + ":" + realm + ":" + pass; //$NON-NLS-1$ //$NON-NLS-2$
361 			final String A2 = method + ":" + uri; //$NON-NLS-1$
362 
363 			r.put("username", user); //$NON-NLS-1$
364 			r.put("realm", realm); //$NON-NLS-1$
365 			r.put("nonce", nonce); //$NON-NLS-1$
366 			r.put("uri", uri); //$NON-NLS-1$
367 
368 			final String response, nc;
369 			if ("auth".equals(qop)) { //$NON-NLS-1$
370 				nc = String.format("%08x", ++requestCount); //$NON-NLS-1$
371 				response = KD(H(A1), nonce + ":" + nc + ":" + cnonce + ":" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
372 						+ qop + ":" //$NON-NLS-1$
373 						+ H(A2));
374 			} else {
375 				nc = null;
376 				response = KD(H(A1), nonce + ":" + H(A2)); //$NON-NLS-1$
377 			}
378 			r.put("response", response); //$NON-NLS-1$
379 			if (params.containsKey("algorithm")) //$NON-NLS-1$
380 				r.put("algorithm", "MD5"); //$NON-NLS-1$ //$NON-NLS-2$
381 			if (cnonce != null && qop != null)
382 				r.put("cnonce", cnonce); //$NON-NLS-1$
383 			if (params.containsKey("opaque")) //$NON-NLS-1$
384 				r.put("opaque", params.get("opaque")); //$NON-NLS-1$ //$NON-NLS-2$
385 			if (qop != null)
386 				r.put("qop", qop); //$NON-NLS-1$
387 			if (nc != null)
388 				r.put("nc", nc); //$NON-NLS-1$
389 
390 			StringBuilder v = new StringBuilder();
391 			for (Map.Entry<String, String> e : r.entrySet()) {
392 				if (v.length() > 0)
393 					v.append(", "); //$NON-NLS-1$
394 				v.append(e.getKey());
395 				v.append('=');
396 				v.append('"');
397 				v.append(e.getValue());
398 				v.append('"');
399 			}
400 			conn.setRequestProperty(HDR_AUTHORIZATION, type.getSchemeName()
401 					+ " " + v); //$NON-NLS-1$
402 		}
403 
404 		private static String uri(URL u) {
405 			StringBuilder r = new StringBuilder();
406 			r.append(u.getProtocol());
407 			r.append("://"); //$NON-NLS-1$
408 			r.append(u.getHost());
409 			if (0 < u.getPort()) {
410 				if (u.getPort() == 80 && "http".equals(u.getProtocol())) { //$NON-NLS-1$
411 					/* nothing */
412 				} else if (u.getPort() == 443
413 						&& "https".equals(u.getProtocol())) { //$NON-NLS-1$
414 					/* nothing */
415 				} else {
416 					r.append(':').append(u.getPort());
417 				}
418 			}
419 			r.append(u.getPath());
420 			if (u.getQuery() != null)
421 				r.append('?').append(u.getQuery());
422 			return r.toString();
423 		}
424 
425 		private static String H(String data) {
426 			try {
427 				MessageDigest md = newMD5();
428 				md.update(data.getBytes("UTF-8")); //$NON-NLS-1$
429 				return LHEX(md.digest());
430 			} catch (UnsupportedEncodingException e) {
431 				throw new RuntimeException("UTF-8 encoding not available", e); //$NON-NLS-1$
432 			}
433 		}
434 
435 		private static String KD(String secret, String data) {
436 			try {
437 				MessageDigest md = newMD5();
438 				md.update(secret.getBytes("UTF-8")); //$NON-NLS-1$
439 				md.update((byte) ':');
440 				md.update(data.getBytes("UTF-8")); //$NON-NLS-1$
441 				return LHEX(md.digest());
442 			} catch (UnsupportedEncodingException e) {
443 				throw new RuntimeException("UTF-8 encoding not available", e); //$NON-NLS-1$
444 			}
445 		}
446 
447 		private static MessageDigest newMD5() {
448 			try {
449 				return MessageDigest.getInstance("MD5"); //$NON-NLS-1$
450 			} catch (NoSuchAlgorithmException e) {
451 				throw new RuntimeException("No MD5 available", e); //$NON-NLS-1$
452 			}
453 		}
454 
455 		private static final char[] LHEX = { '0', '1', '2', '3', '4', '5', '6',
456 				'7', '8', '9', //
457 				'a', 'b', 'c', 'd', 'e', 'f' };
458 
459 		private static String LHEX(byte[] bin) {
460 			StringBuilder r = new StringBuilder(bin.length * 2);
461 			for (int i = 0; i < bin.length; i++) {
462 				byte b = bin[i];
463 				r.append(LHEX[(b >>> 4) & 0x0f]);
464 				r.append(LHEX[b & 0x0f]);
465 			}
466 			return r.toString();
467 		}
468 
469 		private static Map<String, String> parse(String auth) {
470 			Map<String, String> p = new HashMap<>();
471 			int next = 0;
472 			while (next < auth.length()) {
473 				if (next < auth.length() && auth.charAt(next) == ',') {
474 					next++;
475 				}
476 				while (next < auth.length()
477 						&& Character.isWhitespace(auth.charAt(next))) {
478 					next++;
479 				}
480 
481 				int eq = auth.indexOf('=', next);
482 				if (eq < 0 || eq + 1 == auth.length()) {
483 					return Collections.emptyMap();
484 				}
485 
486 				final String name = auth.substring(next, eq);
487 				final String value;
488 				if (auth.charAt(eq + 1) == '"') {
489 					int dq = auth.indexOf('"', eq + 2);
490 					if (dq < 0) {
491 						return Collections.emptyMap();
492 					}
493 					value = auth.substring(eq + 2, dq);
494 					next = dq + 1;
495 
496 				} else {
497 					int space = auth.indexOf(' ', eq + 1);
498 					int comma = auth.indexOf(',', eq + 1);
499 					if (space < 0)
500 						space = auth.length();
501 					if (comma < 0)
502 						comma = auth.length();
503 
504 					final int e = Math.min(space, comma);
505 					value = auth.substring(eq + 1, e);
506 					next = e + 1;
507 				}
508 				p.put(name, value);
509 			}
510 			return p;
511 		}
512 	}
513 
514 	private static class Negotiate extends HttpAuthMethod {
515 		private static final GSSManagerFactory GSS_MANAGER_FACTORY = GSSManagerFactory
516 				.detect();
517 
518 		private static final Oid OID;
519 		static {
520 			try {
521 				// OID for SPNEGO
522 				OID = new Oid("1.3.6.1.5.5.2"); //$NON-NLS-1$
523 			} catch (GSSException e) {
524 				throw new Error("Cannot create NEGOTIATE oid.", e); //$NON-NLS-1$
525 			}
526 		}
527 
528 		private final byte[] prevToken;
529 
530 		public Negotiate(String hdr) {
531 			super(Type.NEGOTIATE);
532 			prevToken = Base64.decode(hdr);
533 		}
534 
535 		@Override
536 		void authorize(String user, String pass) {
537 			// not used
538 		}
539 
540 		@Override
541 		void configureRequest(HttpConnection conn) throws IOException {
542 			GSSManager gssManager = GSS_MANAGER_FACTORY.newInstance(conn
543 					.getURL());
544 			String host = conn.getURL().getHost();
545 			String peerName = "HTTP@" + host.toLowerCase(Locale.ROOT); //$NON-NLS-1$
546 			try {
547 				GSSName gssName = gssManager.createName(peerName,
548 						GSSName.NT_HOSTBASED_SERVICE);
549 				GSSContext context = gssManager.createContext(gssName, OID,
550 						null, GSSContext.DEFAULT_LIFETIME);
551 				// Respect delegation policy in HTTP/SPNEGO.
552 				context.requestCredDeleg(true);
553 
554 				byte[] token = context.initSecContext(prevToken, 0,
555 						prevToken.length);
556 
557 				conn.setRequestProperty(HDR_AUTHORIZATION, getType().getSchemeName()
558 						+ " " + Base64.encodeBytes(token)); //$NON-NLS-1$
559 			} catch (GSSException e) {
560 				IOException ioe = new IOException();
561 				ioe.initCause(e);
562 				throw ioe;
563 			}
564 		}
565 	}
566 }