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.

OpenSshServerKeyDatabase.java 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  1. /*
  2. * Copyright (C) 2018, 2019 Thomas Wolf <thomas.wolf@paranor.ch> and others
  3. *
  4. * This program and the accompanying materials are made available under the
  5. * terms of the Eclipse Distribution License v. 1.0 which is available at
  6. * https://www.eclipse.org/org/documents/edl-v10.php.
  7. *
  8. * SPDX-License-Identifier: BSD-3-Clause
  9. */
  10. package org.eclipse.jgit.internal.transport.sshd;
  11. import static java.nio.charset.StandardCharsets.UTF_8;
  12. import static java.text.MessageFormat.format;
  13. import java.io.BufferedReader;
  14. import java.io.BufferedWriter;
  15. import java.io.FileNotFoundException;
  16. import java.io.IOException;
  17. import java.io.OutputStreamWriter;
  18. import java.net.InetSocketAddress;
  19. import java.net.SocketAddress;
  20. import java.nio.file.Files;
  21. import java.nio.file.InvalidPathException;
  22. import java.nio.file.NoSuchFileException;
  23. import java.nio.file.Path;
  24. import java.nio.file.Paths;
  25. import java.security.GeneralSecurityException;
  26. import java.security.PublicKey;
  27. import java.security.SecureRandom;
  28. import java.util.ArrayList;
  29. import java.util.Arrays;
  30. import java.util.Collection;
  31. import java.util.Collections;
  32. import java.util.LinkedList;
  33. import java.util.List;
  34. import java.util.Map;
  35. import java.util.TreeSet;
  36. import java.util.concurrent.ConcurrentHashMap;
  37. import java.util.function.Supplier;
  38. import org.apache.sshd.client.config.hosts.HostPatternsHolder;
  39. import org.apache.sshd.client.config.hosts.KnownHostDigest;
  40. import org.apache.sshd.client.config.hosts.KnownHostEntry;
  41. import org.apache.sshd.client.config.hosts.KnownHostHashValue;
  42. import org.apache.sshd.client.keyverifier.KnownHostsServerKeyVerifier.HostEntryPair;
  43. import org.apache.sshd.client.session.ClientSession;
  44. import org.apache.sshd.common.NamedFactory;
  45. import org.apache.sshd.common.config.keys.AuthorizedKeyEntry;
  46. import org.apache.sshd.common.config.keys.KeyUtils;
  47. import org.apache.sshd.common.config.keys.PublicKeyEntry;
  48. import org.apache.sshd.common.config.keys.PublicKeyEntryResolver;
  49. import org.apache.sshd.common.digest.BuiltinDigests;
  50. import org.apache.sshd.common.mac.Mac;
  51. import org.apache.sshd.common.util.io.ModifiableFileWatcher;
  52. import org.apache.sshd.common.util.net.SshdSocketAddress;
  53. import org.eclipse.jgit.annotations.NonNull;
  54. import org.eclipse.jgit.internal.storage.file.LockFile;
  55. import org.eclipse.jgit.transport.CredentialItem;
  56. import org.eclipse.jgit.transport.CredentialsProvider;
  57. import org.eclipse.jgit.transport.URIish;
  58. import org.eclipse.jgit.transport.sshd.ServerKeyDatabase;
  59. import org.slf4j.Logger;
  60. import org.slf4j.LoggerFactory;
  61. /**
  62. * A sever host key verifier that honors the {@code StrictHostKeyChecking} and
  63. * {@code UserKnownHostsFile} values from the ssh configuration.
  64. * <p>
  65. * The verifier can be given default known_hosts files in the constructor, which
  66. * will be used if the ssh config does not specify a {@code UserKnownHostsFile}.
  67. * If the ssh config <em>does</em> set {@code UserKnownHostsFile}, the verifier
  68. * uses the given files in the order given. Non-existing or unreadable files are
  69. * ignored.
  70. * <p>
  71. * {@code StrictHostKeyChecking} accepts the following values:
  72. * </p>
  73. * <dl>
  74. * <dt>ask</dt>
  75. * <dd>Ask the user whether new or changed keys shall be accepted and be added
  76. * to the known_hosts file.</dd>
  77. * <dt>yes/true</dt>
  78. * <dd>Accept only keys listed in the known_hosts file.</dd>
  79. * <dt>no/false</dt>
  80. * <dd>Silently accept all new or changed keys, add new keys to the known_hosts
  81. * file.</dd>
  82. * <dt>accept-new</dt>
  83. * <dd>Silently accept keys for new hosts and add them to the known_hosts
  84. * file.</dd>
  85. * </dl>
  86. * <p>
  87. * If {@code StrictHostKeyChecking} is not set, or set to any other value, the
  88. * default value <b>ask</b> is active.
  89. * </p>
  90. * <p>
  91. * This implementation relies on the {@link ClientSession} being a
  92. * {@link JGitClientSession}. By default Apache MINA sshd does not forward the
  93. * config file host entry to the session, so it would be unknown here which
  94. * entry it was and what setting of {@code StrictHostKeyChecking} should be
  95. * used. If used with some other session type, the implementation assumes
  96. * "<b>ask</b>".
  97. * <p>
  98. * <p>
  99. * Asking the user is done via a {@link CredentialsProvider} obtained from the
  100. * session. If none is set, the implementation falls back to strict host key
  101. * checking ("<b>yes</b>").
  102. * </p>
  103. * <p>
  104. * Note that adding a key to the known hosts file may create the file. You can
  105. * specify in the constructor whether the user shall be asked about that, too.
  106. * If the user declines updating the file, but the key was otherwise
  107. * accepted (user confirmed for "<b>ask</b>", or "no" or "accept-new" are
  108. * active), the key is accepted for this session only.
  109. * </p>
  110. * <p>
  111. * If several known hosts files are specified, a new key is always added to the
  112. * first file (even if it doesn't exist yet; see the note about file creation
  113. * above).
  114. * </p>
  115. *
  116. * @see <a href="http://man.openbsd.org/OpenBSD-current/man5/ssh_config.5">man
  117. * ssh-config</a>
  118. */
  119. public class OpenSshServerKeyDatabase
  120. implements ServerKeyDatabase {
  121. // TODO: GlobalKnownHostsFile? May need some kind of LRU caching; these
  122. // files may be large!
  123. private static final Logger LOG = LoggerFactory
  124. .getLogger(OpenSshServerKeyDatabase.class);
  125. /** Can be used to mark revoked known host lines. */
  126. private static final String MARKER_REVOKED = "revoked"; //$NON-NLS-1$
  127. private final boolean askAboutNewFile;
  128. private final Map<Path, HostKeyFile> knownHostsFiles = new ConcurrentHashMap<>();
  129. private final List<HostKeyFile> defaultFiles = new ArrayList<>();
  130. /**
  131. * Creates a new {@link OpenSshServerKeyDatabase}.
  132. *
  133. * @param askAboutNewFile
  134. * whether to ask the user, if possible, about creating a new
  135. * non-existing known_hosts file
  136. * @param defaultFiles
  137. * typically ~/.ssh/known_hosts and ~/.ssh/known_hosts2. May be
  138. * empty or {@code null}, in which case no default files are
  139. * installed. The files need not exist.
  140. */
  141. public OpenSshServerKeyDatabase(boolean askAboutNewFile,
  142. List<Path> defaultFiles) {
  143. if (defaultFiles != null) {
  144. for (Path file : defaultFiles) {
  145. HostKeyFile newFile = new HostKeyFile(file);
  146. knownHostsFiles.put(file, newFile);
  147. this.defaultFiles.add(newFile);
  148. }
  149. }
  150. this.askAboutNewFile = askAboutNewFile;
  151. }
  152. private List<HostKeyFile> getFilesToUse(@NonNull Configuration config) {
  153. List<HostKeyFile> filesToUse = defaultFiles;
  154. List<HostKeyFile> userFiles = addUserHostKeyFiles(
  155. config.getUserKnownHostsFiles());
  156. if (!userFiles.isEmpty()) {
  157. filesToUse = userFiles;
  158. }
  159. return filesToUse;
  160. }
  161. @Override
  162. public List<PublicKey> lookup(@NonNull String connectAddress,
  163. @NonNull InetSocketAddress remoteAddress,
  164. @NonNull Configuration config) {
  165. List<HostKeyFile> filesToUse = getFilesToUse(config);
  166. List<PublicKey> result = new ArrayList<>();
  167. Collection<SshdSocketAddress> candidates = getCandidates(
  168. connectAddress, remoteAddress);
  169. for (HostKeyFile file : filesToUse) {
  170. for (HostEntryPair current : file.get()) {
  171. KnownHostEntry entry = current.getHostEntry();
  172. for (SshdSocketAddress host : candidates) {
  173. if (entry.isHostMatch(host.getHostName(), host.getPort())) {
  174. result.add(current.getServerKey());
  175. break;
  176. }
  177. }
  178. }
  179. }
  180. return result;
  181. }
  182. @Override
  183. public boolean accept(@NonNull String connectAddress,
  184. @NonNull InetSocketAddress remoteAddress,
  185. @NonNull PublicKey serverKey,
  186. @NonNull Configuration config, CredentialsProvider provider) {
  187. List<HostKeyFile> filesToUse = getFilesToUse(config);
  188. AskUser ask = new AskUser(config, provider);
  189. HostEntryPair[] modified = { null };
  190. Path path = null;
  191. Collection<SshdSocketAddress> candidates = getCandidates(connectAddress,
  192. remoteAddress);
  193. for (HostKeyFile file : filesToUse) {
  194. try {
  195. if (find(candidates, serverKey, file.get(), modified)) {
  196. return true;
  197. }
  198. } catch (RevokedKeyException e) {
  199. ask.revokedKey(remoteAddress, serverKey, file.getPath());
  200. return false;
  201. }
  202. if (path == null && modified[0] != null) {
  203. // Remember the file in which we might need to update the
  204. // entry
  205. path = file.getPath();
  206. }
  207. }
  208. if (modified[0] != null) {
  209. // We found an entry, but with a different key
  210. AskUser.ModifiedKeyHandling toDo = ask.acceptModifiedServerKey(
  211. remoteAddress, modified[0].getServerKey(),
  212. serverKey, path);
  213. if (toDo == AskUser.ModifiedKeyHandling.ALLOW_AND_STORE) {
  214. try {
  215. updateModifiedServerKey(serverKey, modified[0], path);
  216. knownHostsFiles.get(path).resetReloadAttributes();
  217. } catch (IOException e) {
  218. LOG.warn(format(SshdText.get().knownHostsCouldNotUpdate,
  219. path));
  220. }
  221. }
  222. if (toDo == AskUser.ModifiedKeyHandling.DENY) {
  223. return false;
  224. }
  225. // TODO: OpenSsh disables password and keyboard-interactive
  226. // authentication in this case. Also agent and local port forwarding
  227. // are switched off. (Plus a few other things such as X11 forwarding
  228. // that are of no interest to a git client.)
  229. return true;
  230. } else if (ask.acceptUnknownKey(remoteAddress, serverKey)) {
  231. if (!filesToUse.isEmpty()) {
  232. HostKeyFile toUpdate = filesToUse.get(0);
  233. path = toUpdate.getPath();
  234. try {
  235. if (Files.exists(path) || !askAboutNewFile
  236. || ask.createNewFile(path)) {
  237. updateKnownHostsFile(candidates, serverKey, path,
  238. config);
  239. toUpdate.resetReloadAttributes();
  240. }
  241. } catch (Exception e) {
  242. LOG.warn(format(SshdText.get().knownHostsCouldNotUpdate,
  243. path), e);
  244. }
  245. }
  246. return true;
  247. }
  248. return false;
  249. }
  250. private static class RevokedKeyException extends Exception {
  251. private static final long serialVersionUID = 1L;
  252. }
  253. private boolean find(Collection<SshdSocketAddress> candidates,
  254. PublicKey serverKey, List<HostEntryPair> entries,
  255. HostEntryPair[] modified) throws RevokedKeyException {
  256. for (HostEntryPair current : entries) {
  257. KnownHostEntry entry = current.getHostEntry();
  258. for (SshdSocketAddress host : candidates) {
  259. if (entry.isHostMatch(host.getHostName(), host.getPort())) {
  260. boolean isRevoked = MARKER_REVOKED
  261. .equals(entry.getMarker());
  262. if (KeyUtils.compareKeys(serverKey,
  263. current.getServerKey())) {
  264. // Exact match
  265. if (isRevoked) {
  266. throw new RevokedKeyException();
  267. }
  268. modified[0] = null;
  269. return true;
  270. } else if (!isRevoked) {
  271. // Server sent a different key
  272. modified[0] = current;
  273. // Keep going -- maybe there's another entry for this
  274. // host
  275. }
  276. }
  277. }
  278. }
  279. return false;
  280. }
  281. private List<HostKeyFile> addUserHostKeyFiles(List<String> fileNames) {
  282. if (fileNames == null || fileNames.isEmpty()) {
  283. return Collections.emptyList();
  284. }
  285. List<HostKeyFile> userFiles = new ArrayList<>();
  286. for (String name : fileNames) {
  287. try {
  288. Path path = Paths.get(name);
  289. HostKeyFile file = knownHostsFiles.computeIfAbsent(path,
  290. p -> new HostKeyFile(path));
  291. userFiles.add(file);
  292. } catch (InvalidPathException e) {
  293. LOG.warn(format(SshdText.get().knownHostsInvalidPath,
  294. name));
  295. }
  296. }
  297. return userFiles;
  298. }
  299. private void updateKnownHostsFile(Collection<SshdSocketAddress> candidates,
  300. PublicKey serverKey, Path path, Configuration config)
  301. throws Exception {
  302. String newEntry = createHostKeyLine(candidates, serverKey, config);
  303. if (newEntry == null) {
  304. return;
  305. }
  306. LockFile lock = new LockFile(path.toFile());
  307. if (lock.lockForAppend()) {
  308. try {
  309. try (BufferedWriter writer = new BufferedWriter(
  310. new OutputStreamWriter(lock.getOutputStream(),
  311. UTF_8))) {
  312. writer.newLine();
  313. writer.write(newEntry);
  314. writer.newLine();
  315. }
  316. lock.commit();
  317. } catch (IOException e) {
  318. lock.unlock();
  319. throw e;
  320. }
  321. } else {
  322. LOG.warn(format(SshdText.get().knownHostsFileLockedUpdate,
  323. path));
  324. }
  325. }
  326. private void updateModifiedServerKey(PublicKey serverKey,
  327. HostEntryPair entry, Path path)
  328. throws IOException {
  329. KnownHostEntry hostEntry = entry.getHostEntry();
  330. String oldLine = hostEntry.getConfigLine();
  331. if (oldLine == null) {
  332. return;
  333. }
  334. String newLine = updateHostKeyLine(oldLine, serverKey);
  335. if (newLine == null || newLine.isEmpty()) {
  336. return;
  337. }
  338. if (oldLine.isEmpty() || newLine.equals(oldLine)) {
  339. // Shouldn't happen.
  340. return;
  341. }
  342. LockFile lock = new LockFile(path.toFile());
  343. if (lock.lock()) {
  344. try {
  345. try (BufferedWriter writer = new BufferedWriter(
  346. new OutputStreamWriter(lock.getOutputStream(), UTF_8));
  347. BufferedReader reader = Files.newBufferedReader(path,
  348. UTF_8)) {
  349. boolean done = false;
  350. String line;
  351. while ((line = reader.readLine()) != null) {
  352. String toWrite = line;
  353. if (!done) {
  354. int pos = line.indexOf('#');
  355. String toTest = pos < 0 ? line
  356. : line.substring(0, pos);
  357. if (toTest.trim().equals(oldLine)) {
  358. toWrite = newLine;
  359. done = true;
  360. }
  361. }
  362. writer.write(toWrite);
  363. writer.newLine();
  364. }
  365. }
  366. lock.commit();
  367. } catch (IOException e) {
  368. lock.unlock();
  369. throw e;
  370. }
  371. } else {
  372. LOG.warn(format(SshdText.get().knownHostsFileLockedUpdate,
  373. path));
  374. }
  375. }
  376. private static class AskUser {
  377. public enum ModifiedKeyHandling {
  378. DENY, ALLOW, ALLOW_AND_STORE
  379. }
  380. private enum Check {
  381. ASK, DENY, ALLOW;
  382. }
  383. private final @NonNull Configuration config;
  384. private final CredentialsProvider provider;
  385. public AskUser(@NonNull Configuration config,
  386. CredentialsProvider provider) {
  387. this.config = config;
  388. this.provider = provider;
  389. }
  390. private static boolean askUser(CredentialsProvider provider, URIish uri,
  391. String prompt, String... messages) {
  392. List<CredentialItem> items = new ArrayList<>(messages.length + 1);
  393. for (String message : messages) {
  394. items.add(new CredentialItem.InformationalMessage(message));
  395. }
  396. if (prompt != null) {
  397. CredentialItem.YesNoType answer = new CredentialItem.YesNoType(
  398. prompt);
  399. items.add(answer);
  400. return provider.get(uri, items) && answer.getValue();
  401. }
  402. return provider.get(uri, items);
  403. }
  404. private Check checkMode(SocketAddress remoteAddress, boolean changed) {
  405. if (!(remoteAddress instanceof InetSocketAddress)) {
  406. return Check.DENY;
  407. }
  408. switch (config.getStrictHostKeyChecking()) {
  409. case REQUIRE_MATCH:
  410. return Check.DENY;
  411. case ACCEPT_ANY:
  412. return Check.ALLOW;
  413. case ACCEPT_NEW:
  414. return changed ? Check.DENY : Check.ALLOW;
  415. default:
  416. return provider == null ? Check.DENY : Check.ASK;
  417. }
  418. }
  419. public void revokedKey(SocketAddress remoteAddress, PublicKey serverKey,
  420. Path path) {
  421. if (provider == null) {
  422. return;
  423. }
  424. InetSocketAddress remote = (InetSocketAddress) remoteAddress;
  425. URIish uri = JGitUserInteraction.toURI(config.getUsername(),
  426. remote);
  427. String sha256 = KeyUtils.getFingerPrint(BuiltinDigests.sha256,
  428. serverKey);
  429. String md5 = KeyUtils.getFingerPrint(BuiltinDigests.md5, serverKey);
  430. String keyAlgorithm = serverKey.getAlgorithm();
  431. askUser(provider, uri, null, //
  432. format(SshdText.get().knownHostsRevokedKeyMsg,
  433. remote.getHostString(), path),
  434. format(SshdText.get().knownHostsKeyFingerprints,
  435. keyAlgorithm),
  436. md5, sha256);
  437. }
  438. public boolean acceptUnknownKey(SocketAddress remoteAddress,
  439. PublicKey serverKey) {
  440. Check check = checkMode(remoteAddress, false);
  441. if (check != Check.ASK) {
  442. return check == Check.ALLOW;
  443. }
  444. InetSocketAddress remote = (InetSocketAddress) remoteAddress;
  445. // Ask the user
  446. String sha256 = KeyUtils.getFingerPrint(BuiltinDigests.sha256,
  447. serverKey);
  448. String md5 = KeyUtils.getFingerPrint(BuiltinDigests.md5, serverKey);
  449. String keyAlgorithm = serverKey.getAlgorithm();
  450. String remoteHost = remote.getHostString();
  451. URIish uri = JGitUserInteraction.toURI(config.getUsername(),
  452. remote);
  453. String prompt = SshdText.get().knownHostsUnknownKeyPrompt;
  454. return askUser(provider, uri, prompt, //
  455. format(SshdText.get().knownHostsUnknownKeyMsg,
  456. remoteHost),
  457. format(SshdText.get().knownHostsKeyFingerprints,
  458. keyAlgorithm),
  459. md5, sha256);
  460. }
  461. public ModifiedKeyHandling acceptModifiedServerKey(
  462. InetSocketAddress remoteAddress, PublicKey expected,
  463. PublicKey actual, Path path) {
  464. Check check = checkMode(remoteAddress, true);
  465. if (check == Check.ALLOW) {
  466. // Never auto-store on CHECK.ALLOW
  467. return ModifiedKeyHandling.ALLOW;
  468. }
  469. String keyAlgorithm = actual.getAlgorithm();
  470. String remoteHost = remoteAddress.getHostString();
  471. URIish uri = JGitUserInteraction.toURI(config.getUsername(),
  472. remoteAddress);
  473. List<String> messages = new ArrayList<>();
  474. String warning = format(
  475. SshdText.get().knownHostsModifiedKeyWarning,
  476. keyAlgorithm, expected.getAlgorithm(), remoteHost,
  477. KeyUtils.getFingerPrint(BuiltinDigests.md5, expected),
  478. KeyUtils.getFingerPrint(BuiltinDigests.sha256, expected),
  479. KeyUtils.getFingerPrint(BuiltinDigests.md5, actual),
  480. KeyUtils.getFingerPrint(BuiltinDigests.sha256, actual));
  481. messages.addAll(Arrays.asList(warning.split("\n"))); //$NON-NLS-1$
  482. if (check == Check.DENY) {
  483. if (provider != null) {
  484. messages.add(format(
  485. SshdText.get().knownHostsModifiedKeyDenyMsg, path));
  486. askUser(provider, uri, null,
  487. messages.toArray(new String[0]));
  488. }
  489. return ModifiedKeyHandling.DENY;
  490. }
  491. // ASK -- two questions: procceed? and store?
  492. List<CredentialItem> items = new ArrayList<>(messages.size() + 2);
  493. for (String message : messages) {
  494. items.add(new CredentialItem.InformationalMessage(message));
  495. }
  496. CredentialItem.YesNoType proceed = new CredentialItem.YesNoType(
  497. SshdText.get().knownHostsModifiedKeyAcceptPrompt);
  498. CredentialItem.YesNoType store = new CredentialItem.YesNoType(
  499. SshdText.get().knownHostsModifiedKeyStorePrompt);
  500. items.add(proceed);
  501. items.add(store);
  502. if (provider.get(uri, items) && proceed.getValue()) {
  503. return store.getValue() ? ModifiedKeyHandling.ALLOW_AND_STORE
  504. : ModifiedKeyHandling.ALLOW;
  505. }
  506. return ModifiedKeyHandling.DENY;
  507. }
  508. public boolean createNewFile(Path path) {
  509. if (provider == null) {
  510. // We can't ask, so don't create the file
  511. return false;
  512. }
  513. URIish uri = new URIish().setPath(path.toString());
  514. return askUser(provider, uri, //
  515. format(SshdText.get().knownHostsUserAskCreationPrompt,
  516. path), //
  517. format(SshdText.get().knownHostsUserAskCreationMsg, path));
  518. }
  519. }
  520. private static class HostKeyFile extends ModifiableFileWatcher
  521. implements Supplier<List<HostEntryPair>> {
  522. private List<HostEntryPair> entries = Collections.emptyList();
  523. public HostKeyFile(Path path) {
  524. super(path);
  525. }
  526. @Override
  527. public List<HostEntryPair> get() {
  528. Path path = getPath();
  529. synchronized (this) {
  530. try {
  531. if (checkReloadRequired()) {
  532. entries = reload(getPath());
  533. }
  534. } catch (IOException e) {
  535. LOG.warn(format(SshdText.get().knownHostsFileReadFailed,
  536. path));
  537. }
  538. return Collections.unmodifiableList(entries);
  539. }
  540. }
  541. private List<HostEntryPair> reload(Path path) throws IOException {
  542. try {
  543. List<KnownHostEntry> rawEntries = KnownHostEntryReader
  544. .readFromFile(path);
  545. updateReloadAttributes();
  546. if (rawEntries == null || rawEntries.isEmpty()) {
  547. return Collections.emptyList();
  548. }
  549. List<HostEntryPair> newEntries = new LinkedList<>();
  550. for (KnownHostEntry entry : rawEntries) {
  551. AuthorizedKeyEntry keyPart = entry.getKeyEntry();
  552. if (keyPart == null) {
  553. continue;
  554. }
  555. try {
  556. PublicKey serverKey = keyPart.resolvePublicKey(null,
  557. PublicKeyEntryResolver.IGNORING);
  558. if (serverKey == null) {
  559. LOG.warn(format(
  560. SshdText.get().knownHostsUnknownKeyType,
  561. path, entry.getConfigLine()));
  562. } else {
  563. newEntries.add(new HostEntryPair(entry, serverKey));
  564. }
  565. } catch (GeneralSecurityException e) {
  566. LOG.warn(format(SshdText.get().knownHostsInvalidLine,
  567. path, entry.getConfigLine()));
  568. }
  569. }
  570. return newEntries;
  571. } catch (FileNotFoundException | NoSuchFileException e) {
  572. resetReloadAttributes();
  573. return Collections.emptyList();
  574. }
  575. }
  576. }
  577. private int parsePort(String s) {
  578. try {
  579. return Integer.parseInt(s);
  580. } catch (NumberFormatException e) {
  581. return -1;
  582. }
  583. }
  584. private SshdSocketAddress toSshdSocketAddress(@NonNull String address) {
  585. String host = null;
  586. int port = 0;
  587. if (HostPatternsHolder.NON_STANDARD_PORT_PATTERN_ENCLOSURE_START_DELIM == address
  588. .charAt(0)) {
  589. int end = address.indexOf(
  590. HostPatternsHolder.NON_STANDARD_PORT_PATTERN_ENCLOSURE_END_DELIM);
  591. if (end <= 1) {
  592. return null; // Invalid
  593. }
  594. host = address.substring(1, end);
  595. if (end < address.length() - 1
  596. && HostPatternsHolder.PORT_VALUE_DELIMITER == address
  597. .charAt(end + 1)) {
  598. port = parsePort(address.substring(end + 2));
  599. }
  600. } else {
  601. int i = address
  602. .lastIndexOf(HostPatternsHolder.PORT_VALUE_DELIMITER);
  603. if (i > 0) {
  604. port = parsePort(address.substring(i + 1));
  605. host = address.substring(0, i);
  606. } else {
  607. host = address;
  608. }
  609. }
  610. if (port < 0 || port > 65535) {
  611. return null;
  612. }
  613. return new SshdSocketAddress(host, port);
  614. }
  615. private Collection<SshdSocketAddress> getCandidates(
  616. @NonNull String connectAddress,
  617. @NonNull InetSocketAddress remoteAddress) {
  618. Collection<SshdSocketAddress> candidates = new TreeSet<>(
  619. SshdSocketAddress.BY_HOST_AND_PORT);
  620. candidates.add(SshdSocketAddress.toSshdSocketAddress(remoteAddress));
  621. SshdSocketAddress address = toSshdSocketAddress(connectAddress);
  622. if (address != null) {
  623. candidates.add(address);
  624. }
  625. return candidates;
  626. }
  627. private String createHostKeyLine(Collection<SshdSocketAddress> patterns,
  628. PublicKey key, Configuration config) throws Exception {
  629. StringBuilder result = new StringBuilder();
  630. if (config.getHashKnownHosts()) {
  631. // SHA1 is the only algorithm for host name hashing known to OpenSSH
  632. // or to Apache MINA sshd.
  633. NamedFactory<Mac> digester = KnownHostDigest.SHA1;
  634. Mac mac = digester.create();
  635. SecureRandom prng = new SecureRandom();
  636. byte[] salt = new byte[mac.getDefaultBlockSize()];
  637. for (SshdSocketAddress address : patterns) {
  638. if (result.length() > 0) {
  639. result.append(',');
  640. }
  641. prng.nextBytes(salt);
  642. KnownHostHashValue.append(result, digester, salt,
  643. KnownHostHashValue.calculateHashValue(
  644. address.getHostName(), address.getPort(), mac,
  645. salt));
  646. }
  647. } else {
  648. for (SshdSocketAddress address : patterns) {
  649. if (result.length() > 0) {
  650. result.append(',');
  651. }
  652. KnownHostHashValue.appendHostPattern(result,
  653. address.getHostName(), address.getPort());
  654. }
  655. }
  656. result.append(' ');
  657. PublicKeyEntry.appendPublicKeyEntry(result, key);
  658. return result.toString();
  659. }
  660. private String updateHostKeyLine(String line, PublicKey newKey)
  661. throws IOException {
  662. // Replaces an existing public key by the new key
  663. int pos = line.indexOf(' ');
  664. if (pos > 0 && line.charAt(0) == KnownHostEntry.MARKER_INDICATOR) {
  665. // We're at the end of the marker. Skip ahead to the next blank.
  666. pos = line.indexOf(' ', pos + 1);
  667. }
  668. if (pos < 0) {
  669. // Don't update if bogus format
  670. return null;
  671. }
  672. StringBuilder result = new StringBuilder(line.substring(0, pos + 1));
  673. PublicKeyEntry.appendPublicKeyEntry(result, newKey);
  674. return result.toString();
  675. }
  676. }