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

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