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 11KB

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