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.

KnownHostEntryReader.java 6.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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 static java.text.MessageFormat.format;
  45. import static org.apache.sshd.client.config.hosts.HostPatternsHolder.NON_STANDARD_PORT_PATTERN_ENCLOSURE_END_DELIM;
  46. import static org.apache.sshd.client.config.hosts.HostPatternsHolder.NON_STANDARD_PORT_PATTERN_ENCLOSURE_START_DELIM;
  47. import java.io.BufferedReader;
  48. import java.io.IOException;
  49. import java.nio.charset.StandardCharsets;
  50. import java.nio.file.Files;
  51. import java.nio.file.Path;
  52. import java.util.Arrays;
  53. import java.util.Collection;
  54. import java.util.LinkedList;
  55. import java.util.List;
  56. import java.util.stream.Collectors;
  57. import org.apache.sshd.client.config.hosts.HostPatternValue;
  58. import org.apache.sshd.client.config.hosts.HostPatternsHolder;
  59. import org.apache.sshd.client.config.hosts.KnownHostEntry;
  60. import org.apache.sshd.client.config.hosts.KnownHostHashValue;
  61. import org.apache.sshd.common.config.keys.AuthorizedKeyEntry;
  62. import org.slf4j.Logger;
  63. import org.slf4j.LoggerFactory;
  64. /**
  65. * Apache MINA sshd 2.0.0 KnownHostEntry cannot read a host entry line like
  66. * "host:port ssh-rsa <key>"; it complains about an illegal character in the
  67. * host name (correct would be "[host]:port"). The default known_hosts reader
  68. * also aborts reading on the first error.
  69. * <p>
  70. * This reader is a bit more robust and tries to handle this case if there is
  71. * only one colon (otherwise it might be an IPv6 address (without port)), and it
  72. * skips and logs invalid entries, but still returns all other valid entries
  73. * from the file.
  74. * </p>
  75. */
  76. public class KnownHostEntryReader {
  77. private static final Logger LOG = LoggerFactory
  78. .getLogger(KnownHostEntryReader.class);
  79. private KnownHostEntryReader() {
  80. // No instantiation
  81. }
  82. /**
  83. * Reads a known_hosts file and returns all valid entries. Invalid entries
  84. * are skipped (and a message is logged).
  85. *
  86. * @param path
  87. * of the file to read
  88. * @return a {@link List} of all valid entries read from the file
  89. * @throws IOException
  90. * if the file cannot be read.
  91. */
  92. public static List<KnownHostEntry> readFromFile(Path path)
  93. throws IOException {
  94. List<KnownHostEntry> result = new LinkedList<>();
  95. try (BufferedReader r = Files.newBufferedReader(path,
  96. StandardCharsets.UTF_8)) {
  97. r.lines().forEachOrdered(l -> {
  98. if (l == null) {
  99. return;
  100. }
  101. String line = clean(l);
  102. if (line.isEmpty()) {
  103. return;
  104. }
  105. try {
  106. KnownHostEntry entry = parseHostEntry(line);
  107. if (entry != null) {
  108. result.add(entry);
  109. } else {
  110. LOG.warn(format(SshdText.get().knownHostsInvalidLine,
  111. path, line));
  112. }
  113. } catch (RuntimeException e) {
  114. LOG.warn(format(SshdText.get().knownHostsInvalidLine, path,
  115. line), e);
  116. }
  117. });
  118. }
  119. return result;
  120. }
  121. private static String clean(String line) {
  122. int i = line.indexOf('#');
  123. return i < 0 ? line.trim() : line.substring(0, i).trim();
  124. }
  125. private static KnownHostEntry parseHostEntry(String line) {
  126. KnownHostEntry entry = new KnownHostEntry();
  127. entry.setConfigLine(line);
  128. String tmp = line;
  129. int i = 0;
  130. if (tmp.charAt(0) == KnownHostEntry.MARKER_INDICATOR) {
  131. // A marker
  132. i = tmp.indexOf(' ', 1);
  133. if (i < 0) {
  134. return null;
  135. }
  136. entry.setMarker(tmp.substring(1, i));
  137. tmp = tmp.substring(i + 1).trim();
  138. }
  139. i = tmp.indexOf(' ');
  140. if (i < 0) {
  141. return null;
  142. }
  143. // Hash, or host patterns
  144. if (tmp.charAt(0) == KnownHostHashValue.HASHED_HOST_DELIMITER) {
  145. // Hashed host entry
  146. KnownHostHashValue hash = KnownHostHashValue
  147. .parse(tmp.substring(0, i));
  148. if (hash == null) {
  149. return null;
  150. }
  151. entry.setHashedEntry(hash);
  152. entry.setPatterns(null);
  153. } else {
  154. Collection<HostPatternValue> patterns = parsePatterns(
  155. tmp.substring(0, i));
  156. if (patterns == null || patterns.isEmpty()) {
  157. return null;
  158. }
  159. entry.setHashedEntry(null);
  160. entry.setPatterns(patterns);
  161. }
  162. tmp = tmp.substring(i + 1).trim();
  163. AuthorizedKeyEntry key = AuthorizedKeyEntry
  164. .parseAuthorizedKeyEntry(tmp);
  165. if (key == null) {
  166. return null;
  167. }
  168. entry.setKeyEntry(key);
  169. return entry;
  170. }
  171. private static Collection<HostPatternValue> parsePatterns(String text) {
  172. if (text.isEmpty()) {
  173. return null;
  174. }
  175. List<String> items = Arrays.stream(text.split(",")) //$NON-NLS-1$
  176. .filter(item -> item != null && !item.isEmpty()).map(item -> {
  177. if (NON_STANDARD_PORT_PATTERN_ENCLOSURE_START_DELIM == item
  178. .charAt(0)) {
  179. return item;
  180. }
  181. int firstColon = item.indexOf(':');
  182. if (firstColon < 0) {
  183. return item;
  184. }
  185. int secondColon = item.indexOf(':', firstColon + 1);
  186. if (secondColon > 0) {
  187. // Assume an IPv6 address (without port).
  188. return item;
  189. }
  190. // We have "host:port", should be "[host]:port"
  191. return NON_STANDARD_PORT_PATTERN_ENCLOSURE_START_DELIM
  192. + item.substring(0, firstColon)
  193. + NON_STANDARD_PORT_PATTERN_ENCLOSURE_END_DELIM
  194. + item.substring(firstColon);
  195. }).collect(Collectors.toList());
  196. return items.isEmpty() ? null : HostPatternsHolder.parsePatterns(items);
  197. }
  198. }