You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

HttpAuthMethod.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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. package org.eclipse.jgit.transport;
  44. import static org.eclipse.jgit.util.HttpSupport.HDR_AUTHORIZATION;
  45. import static org.eclipse.jgit.util.HttpSupport.HDR_WWW_AUTHENTICATE;
  46. import java.io.IOException;
  47. import java.io.UnsupportedEncodingException;
  48. import java.net.HttpURLConnection;
  49. import java.net.URL;
  50. import java.security.MessageDigest;
  51. import java.security.NoSuchAlgorithmException;
  52. import java.util.Collections;
  53. import java.util.HashMap;
  54. import java.util.LinkedHashMap;
  55. import java.util.List;
  56. import java.util.Map;
  57. import java.util.Map.Entry;
  58. import java.util.Random;
  59. import org.eclipse.jgit.util.Base64;
  60. /**
  61. * Support class to populate user authentication data on a connection.
  62. * <p>
  63. * Instances of an HttpAuthMethod are not thread-safe, as some implementations
  64. * may need to maintain per-connection state information.
  65. */
  66. abstract class HttpAuthMethod {
  67. /** No authentication is configured. */
  68. static final HttpAuthMethod NONE = new None();
  69. static final String EMPTY_STRING = ""; //$NON-NLS-1$
  70. static final String SCHEMA_NAME_SEPARATOR = " "; //$NON-NLS-1$
  71. /**
  72. * Handle an authentication failure and possibly return a new response.
  73. *
  74. * @param conn
  75. * the connection that failed.
  76. * @return new authentication method to try.
  77. */
  78. static HttpAuthMethod scanResponse(final HttpURLConnection conn) {
  79. final Map<String, List<String>> headers = conn.getHeaderFields();
  80. HttpAuthMethod authentication = NONE;
  81. for (final Entry<String, List<String>> entry : headers.entrySet()) {
  82. if (HDR_WWW_AUTHENTICATE.equalsIgnoreCase(entry.getKey())) {
  83. if (entry.getValue() != null) {
  84. for (final String value : entry.getValue()) {
  85. if (value != null && value.length() != 0) {
  86. final String[] valuePart = value.split(
  87. SCHEMA_NAME_SEPARATOR, 2);
  88. if (Digest.NAME.equalsIgnoreCase(valuePart[0])) {
  89. final String param;
  90. if (valuePart.length == 1)
  91. param = EMPTY_STRING;
  92. else
  93. param = valuePart[1];
  94. authentication = new Digest(param);
  95. break;
  96. }
  97. if (Basic.NAME.equalsIgnoreCase(valuePart[0]))
  98. authentication = new Basic();
  99. }
  100. }
  101. }
  102. break;
  103. }
  104. }
  105. return authentication;
  106. }
  107. /**
  108. * Update this method with the credentials from the URIish.
  109. *
  110. * @param uri
  111. * the URI used to create the connection.
  112. * @param credentialsProvider
  113. * the credentials provider, or null. If provided,
  114. * {@link URIish#getPass() credentials in the URI} are ignored.
  115. *
  116. * @return true if the authentication method is able to provide
  117. * authorization for the given URI
  118. */
  119. boolean authorize(URIish uri, CredentialsProvider credentialsProvider) {
  120. String username;
  121. String password;
  122. if (credentialsProvider != null) {
  123. CredentialItem.Username u = new CredentialItem.Username();
  124. CredentialItem.Password p = new CredentialItem.Password();
  125. if (credentialsProvider.supports(u, p)
  126. && credentialsProvider.get(uri, u, p)) {
  127. username = u.getValue();
  128. password = new String(p.getValue());
  129. p.clear();
  130. } else
  131. return false;
  132. } else {
  133. username = uri.getUser();
  134. password = uri.getPass();
  135. }
  136. if (username != null) {
  137. authorize(username, password);
  138. return true;
  139. }
  140. return false;
  141. }
  142. /**
  143. * Update this method with the given username and password pair.
  144. *
  145. * @param user
  146. * @param pass
  147. */
  148. abstract void authorize(String user, String pass);
  149. /**
  150. * Update connection properties based on this authentication method.
  151. *
  152. * @param conn
  153. * @throws IOException
  154. */
  155. abstract void configureRequest(HttpURLConnection conn) throws IOException;
  156. /** Performs no user authentication. */
  157. private static class None extends HttpAuthMethod {
  158. @Override
  159. void authorize(String user, String pass) {
  160. // Do nothing when no authentication is enabled.
  161. }
  162. @Override
  163. void configureRequest(HttpURLConnection conn) throws IOException {
  164. // Do nothing when no authentication is enabled.
  165. }
  166. }
  167. /** Performs HTTP basic authentication (plaintext username/password). */
  168. private static class Basic extends HttpAuthMethod {
  169. static final String NAME = "Basic"; //$NON-NLS-1$
  170. private String user;
  171. private String pass;
  172. @Override
  173. void authorize(final String username, final String password) {
  174. this.user = username;
  175. this.pass = password;
  176. }
  177. @Override
  178. void configureRequest(final HttpURLConnection conn) throws IOException {
  179. String ident = user + ":" + pass; //$NON-NLS-1$
  180. String enc = Base64.encodeBytes(ident.getBytes("UTF-8")); //$NON-NLS-1$
  181. conn.setRequestProperty(HDR_AUTHORIZATION, NAME + " " + enc); //$NON-NLS-1$
  182. }
  183. }
  184. /** Performs HTTP digest authentication. */
  185. private static class Digest extends HttpAuthMethod {
  186. static final String NAME = "Digest"; //$NON-NLS-1$
  187. private static final Random PRNG = new Random();
  188. private final Map<String, String> params;
  189. private int requestCount;
  190. private String user;
  191. private String pass;
  192. Digest(String hdr) {
  193. params = parse(hdr);
  194. final String qop = params.get("qop"); //$NON-NLS-1$
  195. if ("auth".equals(qop)) { //$NON-NLS-1$
  196. final byte[] bin = new byte[8];
  197. PRNG.nextBytes(bin);
  198. params.put("cnonce", Base64.encodeBytes(bin)); //$NON-NLS-1$
  199. }
  200. }
  201. @Override
  202. void authorize(final String username, final String password) {
  203. this.user = username;
  204. this.pass = password;
  205. }
  206. @SuppressWarnings("boxing")
  207. @Override
  208. void configureRequest(final HttpURLConnection conn) throws IOException {
  209. final Map<String, String> r = new LinkedHashMap<String, String>();
  210. final String realm = params.get("realm"); //$NON-NLS-1$
  211. final String nonce = params.get("nonce"); //$NON-NLS-1$
  212. final String cnonce = params.get("cnonce"); //$NON-NLS-1$
  213. final String uri = uri(conn.getURL());
  214. final String qop = params.get("qop"); //$NON-NLS-1$
  215. final String method = conn.getRequestMethod();
  216. final String A1 = user + ":" + realm + ":" + pass; //$NON-NLS-1$ //$NON-NLS-2$
  217. final String A2 = method + ":" + uri; //$NON-NLS-1$
  218. r.put("username", user); //$NON-NLS-1$
  219. r.put("realm", realm); //$NON-NLS-1$
  220. r.put("nonce", nonce); //$NON-NLS-1$
  221. r.put("uri", uri); //$NON-NLS-1$
  222. final String response, nc;
  223. if ("auth".equals(qop)) { //$NON-NLS-1$
  224. nc = String.format("%08x", ++requestCount); //$NON-NLS-1$
  225. response = KD(H(A1), nonce + ":" + nc + ":" + cnonce + ":" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
  226. + qop + ":" //$NON-NLS-1$
  227. + H(A2));
  228. } else {
  229. nc = null;
  230. response = KD(H(A1), nonce + ":" + H(A2)); //$NON-NLS-1$
  231. }
  232. r.put("response", response); //$NON-NLS-1$
  233. if (params.containsKey("algorithm")) //$NON-NLS-1$
  234. r.put("algorithm", "MD5"); //$NON-NLS-1$ //$NON-NLS-2$
  235. if (cnonce != null && qop != null)
  236. r.put("cnonce", cnonce); //$NON-NLS-1$
  237. if (params.containsKey("opaque")) //$NON-NLS-1$
  238. r.put("opaque", params.get("opaque")); //$NON-NLS-1$ //$NON-NLS-2$
  239. if (qop != null)
  240. r.put("qop", qop); //$NON-NLS-1$
  241. if (nc != null)
  242. r.put("nc", nc); //$NON-NLS-1$
  243. StringBuilder v = new StringBuilder();
  244. for (Map.Entry<String, String> e : r.entrySet()) {
  245. if (v.length() > 0)
  246. v.append(", "); //$NON-NLS-1$
  247. v.append(e.getKey());
  248. v.append('=');
  249. v.append('"');
  250. v.append(e.getValue());
  251. v.append('"');
  252. }
  253. conn.setRequestProperty(HDR_AUTHORIZATION, NAME + " " + v); //$NON-NLS-1$
  254. }
  255. private static String uri(URL u) {
  256. StringBuilder r = new StringBuilder();
  257. r.append(u.getProtocol());
  258. r.append("://"); //$NON-NLS-1$
  259. r.append(u.getHost());
  260. if (0 < u.getPort()) {
  261. if (u.getPort() == 80 && "http".equals(u.getProtocol())) { //$NON-NLS-1$
  262. /* nothing */
  263. } else if (u.getPort() == 443
  264. && "https".equals(u.getProtocol())) { //$NON-NLS-1$
  265. /* nothing */
  266. } else {
  267. r.append(':').append(u.getPort());
  268. }
  269. }
  270. r.append(u.getPath());
  271. if (u.getQuery() != null)
  272. r.append('?').append(u.getQuery());
  273. return r.toString();
  274. }
  275. private static String H(String data) {
  276. try {
  277. MessageDigest md = newMD5();
  278. md.update(data.getBytes("UTF-8")); //$NON-NLS-1$
  279. return LHEX(md.digest());
  280. } catch (UnsupportedEncodingException e) {
  281. throw new RuntimeException("UTF-8 encoding not available", e); //$NON-NLS-1$
  282. }
  283. }
  284. private static String KD(String secret, String data) {
  285. try {
  286. MessageDigest md = newMD5();
  287. md.update(secret.getBytes("UTF-8")); //$NON-NLS-1$
  288. md.update((byte) ':');
  289. md.update(data.getBytes("UTF-8")); //$NON-NLS-1$
  290. return LHEX(md.digest());
  291. } catch (UnsupportedEncodingException e) {
  292. throw new RuntimeException("UTF-8 encoding not available", e); //$NON-NLS-1$
  293. }
  294. }
  295. private static MessageDigest newMD5() {
  296. try {
  297. return MessageDigest.getInstance("MD5"); //$NON-NLS-1$
  298. } catch (NoSuchAlgorithmException e) {
  299. throw new RuntimeException("No MD5 available", e); //$NON-NLS-1$
  300. }
  301. }
  302. private static final char[] LHEX = { '0', '1', '2', '3', '4', '5', '6',
  303. '7', '8', '9', //
  304. 'a', 'b', 'c', 'd', 'e', 'f' };
  305. private static String LHEX(byte[] bin) {
  306. StringBuilder r = new StringBuilder(bin.length * 2);
  307. for (int i = 0; i < bin.length; i++) {
  308. byte b = bin[i];
  309. r.append(LHEX[(b >>> 4) & 0x0f]);
  310. r.append(LHEX[b & 0x0f]);
  311. }
  312. return r.toString();
  313. }
  314. private static Map<String, String> parse(String auth) {
  315. Map<String, String> p = new HashMap<String, String>();
  316. int next = 0;
  317. while (next < auth.length()) {
  318. if (next < auth.length() && auth.charAt(next) == ',') {
  319. next++;
  320. }
  321. while (next < auth.length()
  322. && Character.isWhitespace(auth.charAt(next))) {
  323. next++;
  324. }
  325. int eq = auth.indexOf('=', next);
  326. if (eq < 0 || eq + 1 == auth.length()) {
  327. return Collections.emptyMap();
  328. }
  329. final String name = auth.substring(next, eq);
  330. final String value;
  331. if (auth.charAt(eq + 1) == '"') {
  332. int dq = auth.indexOf('"', eq + 2);
  333. if (dq < 0) {
  334. return Collections.emptyMap();
  335. }
  336. value = auth.substring(eq + 2, dq);
  337. next = dq + 1;
  338. } else {
  339. int space = auth.indexOf(' ', eq + 1);
  340. int comma = auth.indexOf(',', eq + 1);
  341. if (space < 0)
  342. space = auth.length();
  343. if (comma < 0)
  344. comma = auth.length();
  345. final int e = Math.min(space, comma);
  346. value = auth.substring(eq + 1, e);
  347. next = e + 1;
  348. }
  349. p.put(name, value);
  350. }
  351. return p;
  352. }
  353. }
  354. }