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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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. char[] v = p.getValue();
  201. password = (v == null) ? null : new String(p.getValue());
  202. p.clear();
  203. } else
  204. return false;
  205. } else {
  206. username = uri.getUser();
  207. password = uri.getPass();
  208. }
  209. if (username != null) {
  210. authorize(username, password);
  211. return true;
  212. }
  213. return false;
  214. }
  215. /**
  216. * Update this method with the given username and password pair.
  217. *
  218. * @param user
  219. * @param pass
  220. */
  221. abstract void authorize(String user, String pass);
  222. /**
  223. * Update connection properties based on this authentication method.
  224. *
  225. * @param conn
  226. * @throws IOException
  227. */
  228. abstract void configureRequest(HttpConnection conn) throws IOException;
  229. /**
  230. * Gives the method type associated to this http auth method
  231. *
  232. * @return the method type
  233. */
  234. public Type getType() {
  235. return type;
  236. }
  237. /** Performs no user authentication. */
  238. private static class None extends HttpAuthMethod {
  239. static final None INSTANCE = new None();
  240. public None() {
  241. super(Type.NONE);
  242. }
  243. @Override
  244. void authorize(String user, String pass) {
  245. // Do nothing when no authentication is enabled.
  246. }
  247. @Override
  248. void configureRequest(HttpConnection conn) throws IOException {
  249. // Do nothing when no authentication is enabled.
  250. }
  251. }
  252. /** Performs HTTP basic authentication (plaintext username/password). */
  253. private static class Basic extends HttpAuthMethod {
  254. private String user;
  255. private String pass;
  256. public Basic() {
  257. super(Type.BASIC);
  258. }
  259. @Override
  260. void authorize(final String username, final String password) {
  261. this.user = username;
  262. this.pass = password;
  263. }
  264. @Override
  265. void configureRequest(final HttpConnection conn) throws IOException {
  266. String ident = user + ":" + pass; //$NON-NLS-1$
  267. String enc = Base64.encodeBytes(ident.getBytes("UTF-8")); //$NON-NLS-1$
  268. conn.setRequestProperty(HDR_AUTHORIZATION, type.getSchemeName()
  269. + " " + enc); //$NON-NLS-1$
  270. }
  271. }
  272. /** Performs HTTP digest authentication. */
  273. private static class Digest extends HttpAuthMethod {
  274. private static final Random PRNG = new Random();
  275. private final Map<String, String> params;
  276. private int requestCount;
  277. private String user;
  278. private String pass;
  279. Digest(String hdr) {
  280. super(Type.DIGEST);
  281. params = parse(hdr);
  282. final String qop = params.get("qop"); //$NON-NLS-1$
  283. if ("auth".equals(qop)) { //$NON-NLS-1$
  284. final byte[] bin = new byte[8];
  285. PRNG.nextBytes(bin);
  286. params.put("cnonce", Base64.encodeBytes(bin)); //$NON-NLS-1$
  287. }
  288. }
  289. @Override
  290. void authorize(final String username, final String password) {
  291. this.user = username;
  292. this.pass = password;
  293. }
  294. @SuppressWarnings("boxing")
  295. @Override
  296. void configureRequest(final HttpConnection conn) throws IOException {
  297. final Map<String, String> r = new LinkedHashMap<String, String>();
  298. final String realm = params.get("realm"); //$NON-NLS-1$
  299. final String nonce = params.get("nonce"); //$NON-NLS-1$
  300. final String cnonce = params.get("cnonce"); //$NON-NLS-1$
  301. final String uri = uri(conn.getURL());
  302. final String qop = params.get("qop"); //$NON-NLS-1$
  303. final String method = conn.getRequestMethod();
  304. final String A1 = user + ":" + realm + ":" + pass; //$NON-NLS-1$ //$NON-NLS-2$
  305. final String A2 = method + ":" + uri; //$NON-NLS-1$
  306. r.put("username", user); //$NON-NLS-1$
  307. r.put("realm", realm); //$NON-NLS-1$
  308. r.put("nonce", nonce); //$NON-NLS-1$
  309. r.put("uri", uri); //$NON-NLS-1$
  310. final String response, nc;
  311. if ("auth".equals(qop)) { //$NON-NLS-1$
  312. nc = String.format("%08x", ++requestCount); //$NON-NLS-1$
  313. response = KD(H(A1), nonce + ":" + nc + ":" + cnonce + ":" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
  314. + qop + ":" //$NON-NLS-1$
  315. + H(A2));
  316. } else {
  317. nc = null;
  318. response = KD(H(A1), nonce + ":" + H(A2)); //$NON-NLS-1$
  319. }
  320. r.put("response", response); //$NON-NLS-1$
  321. if (params.containsKey("algorithm")) //$NON-NLS-1$
  322. r.put("algorithm", "MD5"); //$NON-NLS-1$ //$NON-NLS-2$
  323. if (cnonce != null && qop != null)
  324. r.put("cnonce", cnonce); //$NON-NLS-1$
  325. if (params.containsKey("opaque")) //$NON-NLS-1$
  326. r.put("opaque", params.get("opaque")); //$NON-NLS-1$ //$NON-NLS-2$
  327. if (qop != null)
  328. r.put("qop", qop); //$NON-NLS-1$
  329. if (nc != null)
  330. r.put("nc", nc); //$NON-NLS-1$
  331. StringBuilder v = new StringBuilder();
  332. for (Map.Entry<String, String> e : r.entrySet()) {
  333. if (v.length() > 0)
  334. v.append(", "); //$NON-NLS-1$
  335. v.append(e.getKey());
  336. v.append('=');
  337. v.append('"');
  338. v.append(e.getValue());
  339. v.append('"');
  340. }
  341. conn.setRequestProperty(HDR_AUTHORIZATION, type.getSchemeName()
  342. + " " + v); //$NON-NLS-1$
  343. }
  344. private static String uri(URL u) {
  345. StringBuilder r = new StringBuilder();
  346. r.append(u.getProtocol());
  347. r.append("://"); //$NON-NLS-1$
  348. r.append(u.getHost());
  349. if (0 < u.getPort()) {
  350. if (u.getPort() == 80 && "http".equals(u.getProtocol())) { //$NON-NLS-1$
  351. /* nothing */
  352. } else if (u.getPort() == 443
  353. && "https".equals(u.getProtocol())) { //$NON-NLS-1$
  354. /* nothing */
  355. } else {
  356. r.append(':').append(u.getPort());
  357. }
  358. }
  359. r.append(u.getPath());
  360. if (u.getQuery() != null)
  361. r.append('?').append(u.getQuery());
  362. return r.toString();
  363. }
  364. private static String H(String data) {
  365. try {
  366. MessageDigest md = newMD5();
  367. md.update(data.getBytes("UTF-8")); //$NON-NLS-1$
  368. return LHEX(md.digest());
  369. } catch (UnsupportedEncodingException e) {
  370. throw new RuntimeException("UTF-8 encoding not available", e); //$NON-NLS-1$
  371. }
  372. }
  373. private static String KD(String secret, String data) {
  374. try {
  375. MessageDigest md = newMD5();
  376. md.update(secret.getBytes("UTF-8")); //$NON-NLS-1$
  377. md.update((byte) ':');
  378. md.update(data.getBytes("UTF-8")); //$NON-NLS-1$
  379. return LHEX(md.digest());
  380. } catch (UnsupportedEncodingException e) {
  381. throw new RuntimeException("UTF-8 encoding not available", e); //$NON-NLS-1$
  382. }
  383. }
  384. private static MessageDigest newMD5() {
  385. try {
  386. return MessageDigest.getInstance("MD5"); //$NON-NLS-1$
  387. } catch (NoSuchAlgorithmException e) {
  388. throw new RuntimeException("No MD5 available", e); //$NON-NLS-1$
  389. }
  390. }
  391. private static final char[] LHEX = { '0', '1', '2', '3', '4', '5', '6',
  392. '7', '8', '9', //
  393. 'a', 'b', 'c', 'd', 'e', 'f' };
  394. private static String LHEX(byte[] bin) {
  395. StringBuilder r = new StringBuilder(bin.length * 2);
  396. for (int i = 0; i < bin.length; i++) {
  397. byte b = bin[i];
  398. r.append(LHEX[(b >>> 4) & 0x0f]);
  399. r.append(LHEX[b & 0x0f]);
  400. }
  401. return r.toString();
  402. }
  403. private static Map<String, String> parse(String auth) {
  404. Map<String, String> p = new HashMap<String, String>();
  405. int next = 0;
  406. while (next < auth.length()) {
  407. if (next < auth.length() && auth.charAt(next) == ',') {
  408. next++;
  409. }
  410. while (next < auth.length()
  411. && Character.isWhitespace(auth.charAt(next))) {
  412. next++;
  413. }
  414. int eq = auth.indexOf('=', next);
  415. if (eq < 0 || eq + 1 == auth.length()) {
  416. return Collections.emptyMap();
  417. }
  418. final String name = auth.substring(next, eq);
  419. final String value;
  420. if (auth.charAt(eq + 1) == '"') {
  421. int dq = auth.indexOf('"', eq + 2);
  422. if (dq < 0) {
  423. return Collections.emptyMap();
  424. }
  425. value = auth.substring(eq + 2, dq);
  426. next = dq + 1;
  427. } else {
  428. int space = auth.indexOf(' ', eq + 1);
  429. int comma = auth.indexOf(',', eq + 1);
  430. if (space < 0)
  431. space = auth.length();
  432. if (comma < 0)
  433. comma = auth.length();
  434. final int e = Math.min(space, comma);
  435. value = auth.substring(eq + 1, e);
  436. next = e + 1;
  437. }
  438. p.put(name, value);
  439. }
  440. return p;
  441. }
  442. }
  443. private static class Negotiate extends HttpAuthMethod {
  444. private static final GSSManagerFactory GSS_MANAGER_FACTORY = GSSManagerFactory
  445. .detect();
  446. private static final Oid OID;
  447. static {
  448. try {
  449. // OID for SPNEGO
  450. OID = new Oid("1.3.6.1.5.5.2"); //$NON-NLS-1$
  451. } catch (GSSException e) {
  452. throw new Error("Cannot create NEGOTIATE oid.", e); //$NON-NLS-1$
  453. }
  454. }
  455. private final byte[] prevToken;
  456. public Negotiate(String hdr) {
  457. super(Type.NEGOTIATE);
  458. prevToken = Base64.decode(hdr);
  459. }
  460. @Override
  461. void authorize(String user, String pass) {
  462. // not used
  463. }
  464. @Override
  465. void configureRequest(HttpConnection conn) throws IOException {
  466. GSSManager gssManager = GSS_MANAGER_FACTORY.newInstance(conn
  467. .getURL());
  468. String host = conn.getURL().getHost();
  469. String peerName = "HTTP@" + host.toLowerCase(); //$NON-NLS-1$
  470. try {
  471. GSSName gssName = gssManager.createName(peerName,
  472. GSSName.NT_HOSTBASED_SERVICE);
  473. GSSContext context = gssManager.createContext(gssName, OID,
  474. null, GSSContext.DEFAULT_LIFETIME);
  475. // Respect delegation policy in HTTP/SPNEGO.
  476. context.requestCredDeleg(true);
  477. byte[] token = context.initSecContext(prevToken, 0,
  478. prevToken.length);
  479. conn.setRequestProperty(HDR_AUTHORIZATION, getType().getSchemeName()
  480. + " " + Base64.encodeBytes(token)); //$NON-NLS-1$
  481. } catch (GSSException e) {
  482. IOException ioe = new IOException();
  483. ioe.initCause(e);
  484. throw ioe;
  485. }
  486. }
  487. }
  488. }