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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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.URL;
  49. import java.security.MessageDigest;
  50. import java.security.NoSuchAlgorithmException;
  51. import java.util.Collections;
  52. import java.util.HashMap;
  53. import java.util.LinkedHashMap;
  54. import java.util.List;
  55. import java.util.Map;
  56. import java.util.Map.Entry;
  57. import java.util.Random;
  58. import org.eclipse.jgit.transport.http.HttpConnection;
  59. import org.eclipse.jgit.util.Base64;
  60. import org.eclipse.jgit.util.GSSManagerFactory;
  61. import org.ietf.jgss.GSSContext;
  62. import org.ietf.jgss.GSSException;
  63. import org.ietf.jgss.GSSManager;
  64. import org.ietf.jgss.GSSName;
  65. import org.ietf.jgss.Oid;
  66. /**
  67. * Support class to populate user authentication data on a connection.
  68. * <p>
  69. * Instances of an HttpAuthMethod are not thread-safe, as some implementations
  70. * may need to maintain per-connection state information.
  71. */
  72. abstract class HttpAuthMethod {
  73. /**
  74. * Enum listing the http authentication method types supported by jgit. They
  75. * are sorted by priority order!!!
  76. */
  77. public enum Type {
  78. NONE {
  79. @Override
  80. public HttpAuthMethod method(String hdr) {
  81. return None.INSTANCE;
  82. }
  83. @Override
  84. public String getSchemeName() {
  85. return "None"; //$NON-NLS-1$
  86. }
  87. },
  88. BASIC {
  89. @Override
  90. public HttpAuthMethod method(String hdr) {
  91. return new Basic();
  92. }
  93. @Override
  94. public String getSchemeName() {
  95. return "Basic"; //$NON-NLS-1$
  96. }
  97. },
  98. DIGEST {
  99. @Override
  100. public HttpAuthMethod method(String hdr) {
  101. return new Digest(hdr);
  102. }
  103. @Override
  104. public String getSchemeName() {
  105. return "Digest"; //$NON-NLS-1$
  106. }
  107. },
  108. NEGOTIATE {
  109. @Override
  110. public HttpAuthMethod method(String hdr) {
  111. return new Negotiate(hdr);
  112. }
  113. @Override
  114. public String getSchemeName() {
  115. return "Negotiate"; //$NON-NLS-1$
  116. }
  117. };
  118. /**
  119. * Creates a HttpAuthMethod instance configured with the provided HTTP
  120. * WWW-Authenticate header.
  121. *
  122. * @param hdr the http header
  123. * @return a configured HttpAuthMethod instance
  124. */
  125. public abstract HttpAuthMethod method(String hdr);
  126. /**
  127. * @return the name of the authentication scheme in the form to be used
  128. * in HTTP authentication headers as specified in RFC2617 and
  129. * RFC4559
  130. */
  131. public abstract String getSchemeName();
  132. }
  133. static final String EMPTY_STRING = ""; //$NON-NLS-1$
  134. static final String SCHEMA_NAME_SEPARATOR = " "; //$NON-NLS-1$
  135. /**
  136. * Handle an authentication failure and possibly return a new response.
  137. *
  138. * @param conn
  139. * the connection that failed.
  140. * @return new authentication method to try.
  141. */
  142. static HttpAuthMethod scanResponse(final HttpConnection conn) {
  143. final Map<String, List<String>> headers = conn.getHeaderFields();
  144. HttpAuthMethod authentication = Type.NONE.method(EMPTY_STRING);
  145. for (final Entry<String, List<String>> entry : headers.entrySet()) {
  146. if (HDR_WWW_AUTHENTICATE.equalsIgnoreCase(entry.getKey())) {
  147. if (entry.getValue() != null) {
  148. for (final String value : entry.getValue()) {
  149. if (value != null && value.length() != 0) {
  150. final String[] valuePart = value.split(
  151. SCHEMA_NAME_SEPARATOR, 2);
  152. try {
  153. Type methodType = Type.valueOf(valuePart[0].toUpperCase());
  154. if (authentication.getType().compareTo(methodType) >= 0) {
  155. continue;
  156. }
  157. final String param;
  158. if (valuePart.length == 1)
  159. param = EMPTY_STRING;
  160. else
  161. param = valuePart[1];
  162. authentication = methodType
  163. .method(param);
  164. } catch (IllegalArgumentException e) {
  165. // This auth method is not supported
  166. }
  167. }
  168. }
  169. }
  170. break;
  171. }
  172. }
  173. return authentication;
  174. }
  175. protected final Type type;
  176. protected HttpAuthMethod(Type type) {
  177. this.type = type;
  178. }
  179. /**
  180. * Update this method with the credentials from the URIish.
  181. *
  182. * @param uri
  183. * the URI used to create the connection.
  184. * @param credentialsProvider
  185. * the credentials provider, or null. If provided,
  186. * {@link URIish#getPass() credentials in the URI} are ignored.
  187. *
  188. * @return true if the authentication method is able to provide
  189. * authorization for the given URI
  190. */
  191. boolean authorize(URIish uri, CredentialsProvider credentialsProvider) {
  192. String username;
  193. String password;
  194. if (credentialsProvider != null) {
  195. CredentialItem.Username u = new CredentialItem.Username();
  196. CredentialItem.Password p = new CredentialItem.Password();
  197. if (credentialsProvider.supports(u, p)
  198. && credentialsProvider.get(uri, u, p)) {
  199. username = u.getValue();
  200. password = new String(p.getValue());
  201. p.clear();
  202. } else
  203. return false;
  204. } else {
  205. username = uri.getUser();
  206. password = uri.getPass();
  207. }
  208. if (username != null) {
  209. authorize(username, password);
  210. return true;
  211. }
  212. return false;
  213. }
  214. /**
  215. * Update this method with the given username and password pair.
  216. *
  217. * @param user
  218. * @param pass
  219. */
  220. abstract void authorize(String user, String pass);
  221. /**
  222. * Update connection properties based on this authentication method.
  223. *
  224. * @param conn
  225. * @throws IOException
  226. */
  227. abstract void configureRequest(HttpConnection conn) throws IOException;
  228. /**
  229. * Gives the method type associated to this http auth method
  230. *
  231. * @return the method type
  232. */
  233. public Type getType() {
  234. return type;
  235. }
  236. /** Performs no user authentication. */
  237. private static class None extends HttpAuthMethod {
  238. static final None INSTANCE = new None();
  239. public None() {
  240. super(Type.NONE);
  241. }
  242. @Override
  243. void authorize(String user, String pass) {
  244. // Do nothing when no authentication is enabled.
  245. }
  246. @Override
  247. void configureRequest(HttpConnection conn) throws IOException {
  248. // Do nothing when no authentication is enabled.
  249. }
  250. }
  251. /** Performs HTTP basic authentication (plaintext username/password). */
  252. private static class Basic extends HttpAuthMethod {
  253. private String user;
  254. private String pass;
  255. public Basic() {
  256. super(Type.BASIC);
  257. }
  258. @Override
  259. void authorize(final String username, final String password) {
  260. this.user = username;
  261. this.pass = password;
  262. }
  263. @Override
  264. void configureRequest(final HttpConnection conn) throws IOException {
  265. String ident = user + ":" + pass; //$NON-NLS-1$
  266. String enc = Base64.encodeBytes(ident.getBytes("UTF-8")); //$NON-NLS-1$
  267. conn.setRequestProperty(HDR_AUTHORIZATION, type.getSchemeName()
  268. + " " + enc); //$NON-NLS-1$
  269. }
  270. }
  271. /** Performs HTTP digest authentication. */
  272. private static class Digest extends HttpAuthMethod {
  273. private static final Random PRNG = new Random();
  274. private final Map<String, String> params;
  275. private int requestCount;
  276. private String user;
  277. private String pass;
  278. Digest(String hdr) {
  279. super(Type.DIGEST);
  280. params = parse(hdr);
  281. final String qop = params.get("qop"); //$NON-NLS-1$
  282. if ("auth".equals(qop)) { //$NON-NLS-1$
  283. final byte[] bin = new byte[8];
  284. PRNG.nextBytes(bin);
  285. params.put("cnonce", Base64.encodeBytes(bin)); //$NON-NLS-1$
  286. }
  287. }
  288. @Override
  289. void authorize(final String username, final String password) {
  290. this.user = username;
  291. this.pass = password;
  292. }
  293. @SuppressWarnings("boxing")
  294. @Override
  295. void configureRequest(final HttpConnection conn) throws IOException {
  296. final Map<String, String> r = new LinkedHashMap<String, String>();
  297. final String realm = params.get("realm"); //$NON-NLS-1$
  298. final String nonce = params.get("nonce"); //$NON-NLS-1$
  299. final String cnonce = params.get("cnonce"); //$NON-NLS-1$
  300. final String uri = uri(conn.getURL());
  301. final String qop = params.get("qop"); //$NON-NLS-1$
  302. final String method = conn.getRequestMethod();
  303. final String A1 = user + ":" + realm + ":" + pass; //$NON-NLS-1$ //$NON-NLS-2$
  304. final String A2 = method + ":" + uri; //$NON-NLS-1$
  305. r.put("username", user); //$NON-NLS-1$
  306. r.put("realm", realm); //$NON-NLS-1$
  307. r.put("nonce", nonce); //$NON-NLS-1$
  308. r.put("uri", uri); //$NON-NLS-1$
  309. final String response, nc;
  310. if ("auth".equals(qop)) { //$NON-NLS-1$
  311. nc = String.format("%08x", ++requestCount); //$NON-NLS-1$
  312. response = KD(H(A1), nonce + ":" + nc + ":" + cnonce + ":" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
  313. + qop + ":" //$NON-NLS-1$
  314. + H(A2));
  315. } else {
  316. nc = null;
  317. response = KD(H(A1), nonce + ":" + H(A2)); //$NON-NLS-1$
  318. }
  319. r.put("response", response); //$NON-NLS-1$
  320. if (params.containsKey("algorithm")) //$NON-NLS-1$
  321. r.put("algorithm", "MD5"); //$NON-NLS-1$ //$NON-NLS-2$
  322. if (cnonce != null && qop != null)
  323. r.put("cnonce", cnonce); //$NON-NLS-1$
  324. if (params.containsKey("opaque")) //$NON-NLS-1$
  325. r.put("opaque", params.get("opaque")); //$NON-NLS-1$ //$NON-NLS-2$
  326. if (qop != null)
  327. r.put("qop", qop); //$NON-NLS-1$
  328. if (nc != null)
  329. r.put("nc", nc); //$NON-NLS-1$
  330. StringBuilder v = new StringBuilder();
  331. for (Map.Entry<String, String> e : r.entrySet()) {
  332. if (v.length() > 0)
  333. v.append(", "); //$NON-NLS-1$
  334. v.append(e.getKey());
  335. v.append('=');
  336. v.append('"');
  337. v.append(e.getValue());
  338. v.append('"');
  339. }
  340. conn.setRequestProperty(HDR_AUTHORIZATION, type.getSchemeName()
  341. + " " + v); //$NON-NLS-1$
  342. }
  343. private static String uri(URL u) {
  344. StringBuilder r = new StringBuilder();
  345. r.append(u.getProtocol());
  346. r.append("://"); //$NON-NLS-1$
  347. r.append(u.getHost());
  348. if (0 < u.getPort()) {
  349. if (u.getPort() == 80 && "http".equals(u.getProtocol())) { //$NON-NLS-1$
  350. /* nothing */
  351. } else if (u.getPort() == 443
  352. && "https".equals(u.getProtocol())) { //$NON-NLS-1$
  353. /* nothing */
  354. } else {
  355. r.append(':').append(u.getPort());
  356. }
  357. }
  358. r.append(u.getPath());
  359. if (u.getQuery() != null)
  360. r.append('?').append(u.getQuery());
  361. return r.toString();
  362. }
  363. private static String H(String data) {
  364. try {
  365. MessageDigest md = newMD5();
  366. md.update(data.getBytes("UTF-8")); //$NON-NLS-1$
  367. return LHEX(md.digest());
  368. } catch (UnsupportedEncodingException e) {
  369. throw new RuntimeException("UTF-8 encoding not available", e); //$NON-NLS-1$
  370. }
  371. }
  372. private static String KD(String secret, String data) {
  373. try {
  374. MessageDigest md = newMD5();
  375. md.update(secret.getBytes("UTF-8")); //$NON-NLS-1$
  376. md.update((byte) ':');
  377. md.update(data.getBytes("UTF-8")); //$NON-NLS-1$
  378. return LHEX(md.digest());
  379. } catch (UnsupportedEncodingException e) {
  380. throw new RuntimeException("UTF-8 encoding not available", e); //$NON-NLS-1$
  381. }
  382. }
  383. private static MessageDigest newMD5() {
  384. try {
  385. return MessageDigest.getInstance("MD5"); //$NON-NLS-1$
  386. } catch (NoSuchAlgorithmException e) {
  387. throw new RuntimeException("No MD5 available", e); //$NON-NLS-1$
  388. }
  389. }
  390. private static final char[] LHEX = { '0', '1', '2', '3', '4', '5', '6',
  391. '7', '8', '9', //
  392. 'a', 'b', 'c', 'd', 'e', 'f' };
  393. private static String LHEX(byte[] bin) {
  394. StringBuilder r = new StringBuilder(bin.length * 2);
  395. for (int i = 0; i < bin.length; i++) {
  396. byte b = bin[i];
  397. r.append(LHEX[(b >>> 4) & 0x0f]);
  398. r.append(LHEX[b & 0x0f]);
  399. }
  400. return r.toString();
  401. }
  402. private static Map<String, String> parse(String auth) {
  403. Map<String, String> p = new HashMap<String, String>();
  404. int next = 0;
  405. while (next < auth.length()) {
  406. if (next < auth.length() && auth.charAt(next) == ',') {
  407. next++;
  408. }
  409. while (next < auth.length()
  410. && Character.isWhitespace(auth.charAt(next))) {
  411. next++;
  412. }
  413. int eq = auth.indexOf('=', next);
  414. if (eq < 0 || eq + 1 == auth.length()) {
  415. return Collections.emptyMap();
  416. }
  417. final String name = auth.substring(next, eq);
  418. final String value;
  419. if (auth.charAt(eq + 1) == '"') {
  420. int dq = auth.indexOf('"', eq + 2);
  421. if (dq < 0) {
  422. return Collections.emptyMap();
  423. }
  424. value = auth.substring(eq + 2, dq);
  425. next = dq + 1;
  426. } else {
  427. int space = auth.indexOf(' ', eq + 1);
  428. int comma = auth.indexOf(',', eq + 1);
  429. if (space < 0)
  430. space = auth.length();
  431. if (comma < 0)
  432. comma = auth.length();
  433. final int e = Math.min(space, comma);
  434. value = auth.substring(eq + 1, e);
  435. next = e + 1;
  436. }
  437. p.put(name, value);
  438. }
  439. return p;
  440. }
  441. }
  442. private static class Negotiate extends HttpAuthMethod {
  443. private static final GSSManagerFactory GSS_MANAGER_FACTORY = GSSManagerFactory
  444. .detect();
  445. private static final Oid OID;
  446. static {
  447. try {
  448. // OID for SPNEGO
  449. OID = new Oid("1.3.6.1.5.5.2"); //$NON-NLS-1$
  450. } catch (GSSException e) {
  451. throw new Error("Cannot create NEGOTIATE oid.", e); //$NON-NLS-1$
  452. }
  453. }
  454. private final byte[] prevToken;
  455. public Negotiate(String hdr) {
  456. super(Type.NEGOTIATE);
  457. prevToken = Base64.decode(hdr);
  458. }
  459. @Override
  460. void authorize(String user, String pass) {
  461. // not used
  462. }
  463. @Override
  464. void configureRequest(HttpConnection conn) throws IOException {
  465. GSSManager gssManager = GSS_MANAGER_FACTORY.newInstance(conn
  466. .getURL());
  467. String host = conn.getURL().getHost();
  468. String peerName = "HTTP@" + host.toLowerCase(); //$NON-NLS-1$
  469. try {
  470. GSSName gssName = gssManager.createName(peerName,
  471. GSSName.NT_HOSTBASED_SERVICE);
  472. GSSContext context = gssManager.createContext(gssName, OID,
  473. null, GSSContext.DEFAULT_LIFETIME);
  474. // Respect delegation policy in HTTP/SPNEGO.
  475. context.requestCredDeleg(true);
  476. byte[] token = context.initSecContext(prevToken, 0,
  477. prevToken.length);
  478. conn.setRequestProperty(HDR_AUTHORIZATION, getType().getSchemeName()
  479. + " " + Base64.encodeBytes(token)); //$NON-NLS-1$
  480. } catch (GSSException e) {
  481. IOException ioe = new IOException();
  482. ioe.initCause(e);
  483. throw ioe;
  484. }
  485. }
  486. }
  487. }