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.

JGitPublicKeyIterator.java 8.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. /*
  2. * Copyright (C) 2018, Thomas Wolf <thomas.wolf@paranor.ch>
  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.internal.transport.sshd;
  44. import java.io.IOException;
  45. import java.nio.channels.Channel;
  46. import java.security.KeyPair;
  47. import java.security.PublicKey;
  48. import java.util.ArrayList;
  49. import java.util.Iterator;
  50. import java.util.List;
  51. import java.util.Map;
  52. import java.util.NoSuchElementException;
  53. import java.util.concurrent.atomic.AtomicBoolean;
  54. import org.apache.sshd.agent.SshAgent;
  55. import org.apache.sshd.agent.SshAgentFactory;
  56. import org.apache.sshd.client.auth.pubkey.AbstractKeyPairIterator;
  57. import org.apache.sshd.client.auth.pubkey.KeyAgentIdentity;
  58. import org.apache.sshd.client.auth.pubkey.KeyPairIdentity;
  59. import org.apache.sshd.client.auth.pubkey.PublicKeyIdentity;
  60. import org.apache.sshd.client.config.hosts.HostConfigEntry;
  61. import org.apache.sshd.client.session.ClientSession;
  62. import org.apache.sshd.common.FactoryManager;
  63. import org.apache.sshd.common.keyprovider.KeyIdentityProvider;
  64. import org.apache.sshd.common.signature.SignatureFactoriesManager;
  65. /**
  66. * A new iterator over key pairs that we use instead of the default
  67. * {@link org.apache.sshd.client.auth.pubkey.UserAuthPublicKeyIterator}, which
  68. * in its constructor does some strange {@link java.util.stream.Stream} "magic"
  69. * that ends up loading keys prematurely. This class uses plain
  70. * {@link Iterator}s instead to avoid that problem. Used in
  71. * {@link JGitPublicKeyAuthentication}.
  72. *
  73. * @see <a href=
  74. * "https://issues.apache.org/jira/projects/SSHD/issues/SSHD-860">Upstream
  75. * issue SSHD-860</a>
  76. */
  77. public class JGitPublicKeyIterator
  78. extends AbstractKeyPairIterator<PublicKeyIdentity> implements Channel {
  79. // Re: the cause for the problem mentioned above has not been determined.
  80. // It looks as if either the Apache code inadvertently calls
  81. // GenericUtils.isEmpty() on all streams (which would load the first key
  82. // of each stream), or the Java stream implementation does some prefetching.
  83. // It's not entirely clear. Using Iterators we have more control over
  84. // what happens when.
  85. private final AtomicBoolean open = new AtomicBoolean(true);
  86. private SshAgent agent;
  87. private final List<Iterator<PublicKeyIdentity>> keys = new ArrayList<>(3);
  88. private final Iterator<Iterator<PublicKeyIdentity>> keyIter;
  89. private Iterator<PublicKeyIdentity> current;
  90. private Boolean hasElement;
  91. /**
  92. * Creates a new {@link JGitPublicKeyIterator}.
  93. *
  94. * @param session
  95. * we're trying to authenticate
  96. * @param signatureFactories
  97. * to use
  98. * @throws Exception
  99. * if an {@link SshAgentFactory} is configured and getting
  100. * identities from the agent fails
  101. */
  102. public JGitPublicKeyIterator(ClientSession session,
  103. SignatureFactoriesManager signatureFactories) throws Exception {
  104. super(session);
  105. boolean useAgent = true;
  106. if (session instanceof JGitClientSession) {
  107. HostConfigEntry config = ((JGitClientSession) session)
  108. .getHostConfigEntry();
  109. useAgent = !config.isIdentitiesOnly();
  110. }
  111. if (useAgent) {
  112. FactoryManager manager = session.getFactoryManager();
  113. SshAgentFactory factory = manager == null ? null
  114. : manager.getAgentFactory();
  115. if (factory != null) {
  116. try {
  117. agent = factory.createClient(manager);
  118. keys.add(new AgentIdentityIterator(agent));
  119. } catch (IOException e) {
  120. try {
  121. closeAgent();
  122. } catch (IOException err) {
  123. e.addSuppressed(err);
  124. }
  125. throw e;
  126. }
  127. }
  128. }
  129. keys.add(
  130. new KeyPairIdentityIterator(session.getRegisteredIdentities(),
  131. session, signatureFactories));
  132. keys.add(new KeyPairIdentityIterator(session.getKeyPairProvider(),
  133. session, signatureFactories));
  134. keyIter = keys.iterator();
  135. }
  136. @Override
  137. public boolean isOpen() {
  138. return open.get();
  139. }
  140. @Override
  141. public void close() throws IOException {
  142. if (open.getAndSet(false)) {
  143. closeAgent();
  144. }
  145. }
  146. @Override
  147. public boolean hasNext() {
  148. if (!isOpen()) {
  149. return false;
  150. }
  151. if (hasElement != null) {
  152. return hasElement.booleanValue();
  153. }
  154. while (current == null || !current.hasNext()) {
  155. if (keyIter.hasNext()) {
  156. current = keyIter.next();
  157. } else {
  158. current = null;
  159. hasElement = Boolean.FALSE;
  160. return false;
  161. }
  162. }
  163. hasElement = Boolean.TRUE;
  164. return true;
  165. }
  166. @Override
  167. public PublicKeyIdentity next() {
  168. if (!isOpen() || hasElement == null && !hasNext()
  169. || !hasElement.booleanValue()) {
  170. throw new NoSuchElementException();
  171. }
  172. hasElement = null;
  173. PublicKeyIdentity result;
  174. try {
  175. result = current.next();
  176. } catch (NoSuchElementException e) {
  177. result = null;
  178. }
  179. return result;
  180. }
  181. private void closeAgent() throws IOException {
  182. if (agent == null) {
  183. return;
  184. }
  185. try {
  186. agent.close();
  187. } finally {
  188. agent = null;
  189. }
  190. }
  191. /**
  192. * An {@link Iterator} that maps the data obtained from an agent to
  193. * {@link PublicKeyIdentity}.
  194. */
  195. private static class AgentIdentityIterator
  196. implements Iterator<PublicKeyIdentity> {
  197. private final SshAgent agent;
  198. private final Iterator<? extends Map.Entry<PublicKey, String>> iter;
  199. public AgentIdentityIterator(SshAgent agent) throws IOException {
  200. this.agent = agent;
  201. iter = agent == null ? null : agent.getIdentities().iterator();
  202. }
  203. @Override
  204. public boolean hasNext() {
  205. return iter != null && iter.hasNext();
  206. }
  207. @Override
  208. public PublicKeyIdentity next() {
  209. if (iter == null) {
  210. throw new NoSuchElementException();
  211. }
  212. Map.Entry<PublicKey, String> entry = iter.next();
  213. return new KeyAgentIdentity(agent, entry.getKey(),
  214. entry.getValue());
  215. }
  216. }
  217. /**
  218. * An {@link Iterator} that maps {@link KeyPair} to
  219. * {@link PublicKeyIdentity}.
  220. */
  221. private static class KeyPairIdentityIterator
  222. implements Iterator<PublicKeyIdentity> {
  223. private final Iterator<KeyPair> keyPairs;
  224. private final ClientSession session;
  225. private final SignatureFactoriesManager signatureFactories;
  226. public KeyPairIdentityIterator(KeyIdentityProvider provider,
  227. ClientSession session,
  228. SignatureFactoriesManager signatureFactories) {
  229. this.session = session;
  230. this.signatureFactories = signatureFactories;
  231. keyPairs = provider == null ? null : provider.loadKeys().iterator();
  232. }
  233. @Override
  234. public boolean hasNext() {
  235. return keyPairs != null && keyPairs.hasNext();
  236. }
  237. @Override
  238. public PublicKeyIdentity next() {
  239. if (keyPairs == null) {
  240. throw new NoSuchElementException();
  241. }
  242. KeyPair key = keyPairs.next();
  243. return new KeyPairIdentity(signatureFactories, session, key);
  244. }
  245. }
  246. }