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

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