OpenSshServerKeyDatabase.java

  1. /*
  2.  * Copyright (C) 2018, 2021 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.Random;
  36. import java.util.TreeSet;
  37. import java.util.concurrent.ConcurrentHashMap;
  38. import java.util.function.Supplier;

  39. import org.apache.sshd.client.config.hosts.HostPatternsHolder;
  40. import org.apache.sshd.client.config.hosts.KnownHostDigest;
  41. import org.apache.sshd.client.config.hosts.KnownHostEntry;
  42. import org.apache.sshd.client.config.hosts.KnownHostHashValue;
  43. import org.apache.sshd.client.keyverifier.KnownHostsServerKeyVerifier.HostEntryPair;
  44. import org.apache.sshd.client.session.ClientSession;
  45. import org.apache.sshd.common.NamedFactory;
  46. import org.apache.sshd.common.config.keys.AuthorizedKeyEntry;
  47. import org.apache.sshd.common.config.keys.KeyUtils;
  48. import org.apache.sshd.common.config.keys.PublicKeyEntry;
  49. import org.apache.sshd.common.config.keys.PublicKeyEntryResolver;
  50. import org.apache.sshd.common.digest.BuiltinDigests;
  51. import org.apache.sshd.common.mac.Mac;
  52. import org.apache.sshd.common.util.io.ModifiableFileWatcher;
  53. import org.apache.sshd.common.util.net.SshdSocketAddress;
  54. import org.eclipse.jgit.annotations.NonNull;
  55. import org.eclipse.jgit.internal.storage.file.LockFile;
  56. import org.eclipse.jgit.transport.CredentialItem;
  57. import org.eclipse.jgit.transport.CredentialsProvider;
  58. import org.eclipse.jgit.transport.URIish;
  59. import org.eclipse.jgit.transport.sshd.ServerKeyDatabase;
  60. import org.slf4j.Logger;
  61. import org.slf4j.LoggerFactory;

  62. /**
  63.  * A sever host key verifier that honors the {@code StrictHostKeyChecking} and
  64.  * {@code UserKnownHostsFile} values from the ssh configuration.
  65.  * <p>
  66.  * The verifier can be given default known_hosts files in the constructor, which
  67.  * will be used if the ssh config does not specify a {@code UserKnownHostsFile}.
  68.  * If the ssh config <em>does</em> set {@code UserKnownHostsFile}, the verifier
  69.  * uses the given files in the order given. Non-existing or unreadable files are
  70.  * ignored.
  71.  * <p>
  72.  * {@code StrictHostKeyChecking} accepts the following values:
  73.  * </p>
  74.  * <dl>
  75.  * <dt>ask</dt>
  76.  * <dd>Ask the user whether new or changed keys shall be accepted and be added
  77.  * to the known_hosts file.</dd>
  78.  * <dt>yes/true</dt>
  79.  * <dd>Accept only keys listed in the known_hosts file.</dd>
  80.  * <dt>no/false</dt>
  81.  * <dd>Silently accept all new or changed keys, add new keys to the known_hosts
  82.  * file.</dd>
  83.  * <dt>accept-new</dt>
  84.  * <dd>Silently accept keys for new hosts and add them to the known_hosts
  85.  * file.</dd>
  86.  * </dl>
  87.  * <p>
  88.  * If {@code StrictHostKeyChecking} is not set, or set to any other value, the
  89.  * default value <b>ask</b> is active.
  90.  * </p>
  91.  * <p>
  92.  * This implementation relies on the {@link ClientSession} being a
  93.  * {@link JGitClientSession}. By default Apache MINA sshd does not forward the
  94.  * config file host entry to the session, so it would be unknown here which
  95.  * entry it was and what setting of {@code StrictHostKeyChecking} should be
  96.  * used. If used with some other session type, the implementation assumes
  97.  * "<b>ask</b>".
  98.  * <p>
  99.  * <p>
  100.  * Asking the user is done via a {@link CredentialsProvider} obtained from the
  101.  * session. If none is set, the implementation falls back to strict host key
  102.  * checking ("<b>yes</b>").
  103.  * </p>
  104.  * <p>
  105.  * Note that adding a key to the known hosts file may create the file. You can
  106.  * specify in the constructor whether the user shall be asked about that, too.
  107.  * If the user declines updating the file, but the key was otherwise
  108.  * accepted (user confirmed for "<b>ask</b>", or "no" or "accept-new" are
  109.  * active), the key is accepted for this session only.
  110.  * </p>
  111.  * <p>
  112.  * If several known hosts files are specified, a new key is always added to the
  113.  * first file (even if it doesn't exist yet; see the note about file creation
  114.  * above).
  115.  * </p>
  116.  *
  117.  * @see <a href="http://man.openbsd.org/OpenBSD-current/man5/ssh_config.5">man
  118.  *      ssh-config</a>
  119.  */
  120. public class OpenSshServerKeyDatabase
  121.         implements ServerKeyDatabase {

  122.     // TODO: GlobalKnownHostsFile? May need some kind of LRU caching; these
  123.     // files may be large!

  124.     private static final Logger LOG = LoggerFactory
  125.             .getLogger(OpenSshServerKeyDatabase.class);

  126.     /** Can be used to mark revoked known host lines. */
  127.     private static final String MARKER_REVOKED = "revoked"; //$NON-NLS-1$

  128.     private final boolean askAboutNewFile;

  129.     private final Map<Path, HostKeyFile> knownHostsFiles = new ConcurrentHashMap<>();

  130.     private final List<HostKeyFile> defaultFiles = new ArrayList<>();

  131.     private Random prng;

  132.     /**
  133.      * Creates a new {@link OpenSshServerKeyDatabase}.
  134.      *
  135.      * @param askAboutNewFile
  136.      *            whether to ask the user, if possible, about creating a new
  137.      *            non-existing known_hosts file
  138.      * @param defaultFiles
  139.      *            typically ~/.ssh/known_hosts and ~/.ssh/known_hosts2. May be
  140.      *            empty or {@code null}, in which case no default files are
  141.      *            installed. The files need not exist.
  142.      */
  143.     public OpenSshServerKeyDatabase(boolean askAboutNewFile,
  144.             List<Path> defaultFiles) {
  145.         if (defaultFiles != null) {
  146.             for (Path file : defaultFiles) {
  147.                 HostKeyFile newFile = new HostKeyFile(file);
  148.                 knownHostsFiles.put(file, newFile);
  149.                 this.defaultFiles.add(newFile);
  150.             }
  151.         }
  152.         this.askAboutNewFile = askAboutNewFile;
  153.     }

  154.     private List<HostKeyFile> getFilesToUse(@NonNull Configuration config) {
  155.         List<HostKeyFile> filesToUse = defaultFiles;
  156.         List<HostKeyFile> userFiles = addUserHostKeyFiles(
  157.                 config.getUserKnownHostsFiles());
  158.         if (!userFiles.isEmpty()) {
  159.             filesToUse = userFiles;
  160.         }
  161.         return filesToUse;
  162.     }

  163.     @Override
  164.     public List<PublicKey> lookup(@NonNull String connectAddress,
  165.             @NonNull InetSocketAddress remoteAddress,
  166.             @NonNull Configuration config) {
  167.         List<HostKeyFile> filesToUse = getFilesToUse(config);
  168.         List<PublicKey> result = new ArrayList<>();
  169.         Collection<SshdSocketAddress> candidates = getCandidates(
  170.                 connectAddress, remoteAddress);
  171.         for (HostKeyFile file : filesToUse) {
  172.             for (HostEntryPair current : file.get()) {
  173.                 KnownHostEntry entry = current.getHostEntry();
  174.                 if (!isRevoked(entry)) {
  175.                     for (SshdSocketAddress host : candidates) {
  176.                         if (entry.isHostMatch(host.getHostName(),
  177.                                 host.getPort())) {
  178.                             result.add(current.getServerKey());
  179.                             break;
  180.                         }
  181.                     }
  182.                 }
  183.             }
  184.         }
  185.         return result;
  186.     }

  187.     @Override
  188.     public boolean accept(@NonNull String connectAddress,
  189.             @NonNull InetSocketAddress remoteAddress,
  190.             @NonNull PublicKey serverKey,
  191.             @NonNull Configuration config, CredentialsProvider provider) {
  192.         List<HostKeyFile> filesToUse = getFilesToUse(config);
  193.         AskUser ask = new AskUser(config, provider);
  194.         HostEntryPair[] modified = { null };
  195.         Path path = null;
  196.         Collection<SshdSocketAddress> candidates = getCandidates(connectAddress,
  197.                 remoteAddress);
  198.         for (HostKeyFile file : filesToUse) {
  199.             try {
  200.                 if (find(candidates, serverKey, file.get(), modified)) {
  201.                     return true;
  202.                 }
  203.             } catch (RevokedKeyException e) {
  204.                 ask.revokedKey(remoteAddress, serverKey, file.getPath());
  205.                 return false;
  206.             }
  207.             if (path == null && modified[0] != null) {
  208.                 // Remember the file in which we might need to update the
  209.                 // entry
  210.                 path = file.getPath();
  211.             }
  212.         }
  213.         if (modified[0] != null) {
  214.             // We found an entry, but with a different key
  215.             AskUser.ModifiedKeyHandling toDo = ask.acceptModifiedServerKey(
  216.                     remoteAddress, modified[0].getServerKey(),
  217.                     serverKey, path);
  218.             if (toDo == AskUser.ModifiedKeyHandling.ALLOW_AND_STORE) {
  219.                 try {
  220.                     updateModifiedServerKey(serverKey, modified[0], path);
  221.                     knownHostsFiles.get(path).resetReloadAttributes();
  222.                 } catch (IOException e) {
  223.                     LOG.warn(format(SshdText.get().knownHostsCouldNotUpdate,
  224.                             path));
  225.                 }
  226.             }
  227.             if (toDo == AskUser.ModifiedKeyHandling.DENY) {
  228.                 return false;
  229.             }
  230.             // TODO: OpenSsh disables password and keyboard-interactive
  231.             // authentication in this case. Also agent and local port forwarding
  232.             // are switched off. (Plus a few other things such as X11 forwarding
  233.             // that are of no interest to a git client.)
  234.             return true;
  235.         } else if (ask.acceptUnknownKey(remoteAddress, serverKey)) {
  236.             if (!filesToUse.isEmpty()) {
  237.                 HostKeyFile toUpdate = filesToUse.get(0);
  238.                 path = toUpdate.getPath();
  239.                 try {
  240.                     if (Files.exists(path) || !askAboutNewFile
  241.                             || ask.createNewFile(path)) {
  242.                         updateKnownHostsFile(candidates, serverKey, path,
  243.                                 config);
  244.                         toUpdate.resetReloadAttributes();
  245.                     }
  246.                 } catch (Exception e) {
  247.                     LOG.warn(format(SshdText.get().knownHostsCouldNotUpdate,
  248.                             path), e);
  249.                 }
  250.             }
  251.             return true;
  252.         }
  253.         return false;
  254.     }

  255.     private static class RevokedKeyException extends Exception {
  256.         private static final long serialVersionUID = 1L;
  257.     }

  258.     private boolean isRevoked(KnownHostEntry entry) {
  259.         return MARKER_REVOKED.equals(entry.getMarker());
  260.     }

  261.     private boolean find(Collection<SshdSocketAddress> candidates,
  262.             PublicKey serverKey, List<HostEntryPair> entries,
  263.             HostEntryPair[] modified) throws RevokedKeyException {
  264.         for (HostEntryPair current : entries) {
  265.             KnownHostEntry entry = current.getHostEntry();
  266.             for (SshdSocketAddress host : candidates) {
  267.                 if (entry.isHostMatch(host.getHostName(), host.getPort())) {
  268.                     boolean revoked = isRevoked(entry);
  269.                     if (KeyUtils.compareKeys(serverKey,
  270.                             current.getServerKey())) {
  271.                         // Exact match
  272.                         if (revoked) {
  273.                             throw new RevokedKeyException();
  274.                         }
  275.                         modified[0] = null;
  276.                         return true;
  277.                     } else if (!revoked) {
  278.                         // Server sent a different key
  279.                         modified[0] = current;
  280.                         // Keep going -- maybe there's another entry for this
  281.                         // host
  282.                     }
  283.                     break;
  284.                 }
  285.             }
  286.         }
  287.         return false;
  288.     }

  289.     private List<HostKeyFile> addUserHostKeyFiles(List<String> fileNames) {
  290.         if (fileNames == null || fileNames.isEmpty()) {
  291.             return Collections.emptyList();
  292.         }
  293.         List<HostKeyFile> userFiles = new ArrayList<>();
  294.         for (String name : fileNames) {
  295.             try {
  296.                 Path path = Paths.get(name);
  297.                 HostKeyFile file = knownHostsFiles.computeIfAbsent(path,
  298.                         p -> new HostKeyFile(path));
  299.                 userFiles.add(file);
  300.             } catch (InvalidPathException e) {
  301.                 LOG.warn(format(SshdText.get().knownHostsInvalidPath,
  302.                         name));
  303.             }
  304.         }
  305.         return userFiles;
  306.     }

  307.     private void updateKnownHostsFile(Collection<SshdSocketAddress> candidates,
  308.             PublicKey serverKey, Path path, Configuration config)
  309.             throws Exception {
  310.         String newEntry = createHostKeyLine(candidates, serverKey, config);
  311.         if (newEntry == null) {
  312.             return;
  313.         }
  314.         LockFile lock = new LockFile(path.toFile());
  315.         if (lock.lockForAppend()) {
  316.             try {
  317.                 try (BufferedWriter writer = new BufferedWriter(
  318.                         new OutputStreamWriter(lock.getOutputStream(),
  319.                                 UTF_8))) {
  320.                     writer.newLine();
  321.                     writer.write(newEntry);
  322.                     writer.newLine();
  323.                 }
  324.                 lock.commit();
  325.             } catch (IOException e) {
  326.                 lock.unlock();
  327.                 throw e;
  328.             }
  329.         } else {
  330.             LOG.warn(format(SshdText.get().knownHostsFileLockedUpdate,
  331.                     path));
  332.         }
  333.     }

  334.     private void updateModifiedServerKey(PublicKey serverKey,
  335.             HostEntryPair entry, Path path)
  336.             throws IOException {
  337.         KnownHostEntry hostEntry = entry.getHostEntry();
  338.         String oldLine = hostEntry.getConfigLine();
  339.         if (oldLine == null) {
  340.             return;
  341.         }
  342.         String newLine = updateHostKeyLine(oldLine, serverKey);
  343.         if (newLine == null || newLine.isEmpty()) {
  344.             return;
  345.         }
  346.         if (oldLine.isEmpty() || newLine.equals(oldLine)) {
  347.             // Shouldn't happen.
  348.             return;
  349.         }
  350.         LockFile lock = new LockFile(path.toFile());
  351.         if (lock.lock()) {
  352.             try {
  353.                 try (BufferedWriter writer = new BufferedWriter(
  354.                         new OutputStreamWriter(lock.getOutputStream(), UTF_8));
  355.                         BufferedReader reader = Files.newBufferedReader(path,
  356.                                 UTF_8)) {
  357.                     boolean done = false;
  358.                     String line;
  359.                     while ((line = reader.readLine()) != null) {
  360.                         String toWrite = line;
  361.                         if (!done) {
  362.                             int pos = line.indexOf('#');
  363.                             String toTest = pos < 0 ? line
  364.                                     : line.substring(0, pos);
  365.                             if (toTest.trim().equals(oldLine)) {
  366.                                 toWrite = newLine;
  367.                                 done = true;
  368.                             }
  369.                         }
  370.                         writer.write(toWrite);
  371.                         writer.newLine();
  372.                     }
  373.                 }
  374.                 lock.commit();
  375.             } catch (IOException e) {
  376.                 lock.unlock();
  377.                 throw e;
  378.             }
  379.         } else {
  380.             LOG.warn(format(SshdText.get().knownHostsFileLockedUpdate,
  381.                     path));
  382.         }
  383.     }

  384.     private static class AskUser {

  385.         public enum ModifiedKeyHandling {
  386.             DENY, ALLOW, ALLOW_AND_STORE
  387.         }

  388.         private enum Check {
  389.             ASK, DENY, ALLOW;
  390.         }

  391.         private final @NonNull Configuration config;

  392.         private final CredentialsProvider provider;

  393.         public AskUser(@NonNull Configuration config,
  394.                 CredentialsProvider provider) {
  395.             this.config = config;
  396.             this.provider = provider;
  397.         }

  398.         private static boolean askUser(CredentialsProvider provider, URIish uri,
  399.                 String prompt, String... messages) {
  400.             List<CredentialItem> items = new ArrayList<>(messages.length + 1);
  401.             for (String message : messages) {
  402.                 items.add(new CredentialItem.InformationalMessage(message));
  403.             }
  404.             if (prompt != null) {
  405.                 CredentialItem.YesNoType answer = new CredentialItem.YesNoType(
  406.                         prompt);
  407.                 items.add(answer);
  408.                 return provider.get(uri, items) && answer.getValue();
  409.             }
  410.             return provider.get(uri, items);
  411.         }

  412.         private Check checkMode(SocketAddress remoteAddress, boolean changed) {
  413.             if (!(remoteAddress instanceof InetSocketAddress)) {
  414.                 return Check.DENY;
  415.             }
  416.             switch (config.getStrictHostKeyChecking()) {
  417.             case REQUIRE_MATCH:
  418.                 return Check.DENY;
  419.             case ACCEPT_ANY:
  420.                 return Check.ALLOW;
  421.             case ACCEPT_NEW:
  422.                 return changed ? Check.DENY : Check.ALLOW;
  423.             default:
  424.                 return provider == null ? Check.DENY : Check.ASK;
  425.             }
  426.         }

  427.         public void revokedKey(SocketAddress remoteAddress, PublicKey serverKey,
  428.                 Path path) {
  429.             if (provider == null) {
  430.                 return;
  431.             }
  432.             InetSocketAddress remote = (InetSocketAddress) remoteAddress;
  433.             URIish uri = JGitUserInteraction.toURI(config.getUsername(),
  434.                     remote);
  435.             String sha256 = KeyUtils.getFingerPrint(BuiltinDigests.sha256,
  436.                     serverKey);
  437.             String md5 = KeyUtils.getFingerPrint(BuiltinDigests.md5, serverKey);
  438.             String keyAlgorithm = serverKey.getAlgorithm();
  439.             askUser(provider, uri, null, //
  440.                     format(SshdText.get().knownHostsRevokedKeyMsg,
  441.                             remote.getHostString(), path),
  442.                     format(SshdText.get().knownHostsKeyFingerprints,
  443.                             keyAlgorithm),
  444.                     md5, sha256);
  445.         }

  446.         public boolean acceptUnknownKey(SocketAddress remoteAddress,
  447.                 PublicKey serverKey) {
  448.             Check check = checkMode(remoteAddress, false);
  449.             if (check != Check.ASK) {
  450.                 return check == Check.ALLOW;
  451.             }
  452.             InetSocketAddress remote = (InetSocketAddress) remoteAddress;
  453.             // Ask the user
  454.             String sha256 = KeyUtils.getFingerPrint(BuiltinDigests.sha256,
  455.                     serverKey);
  456.             String md5 = KeyUtils.getFingerPrint(BuiltinDigests.md5, serverKey);
  457.             String keyAlgorithm = serverKey.getAlgorithm();
  458.             String remoteHost = remote.getHostString();
  459.             URIish uri = JGitUserInteraction.toURI(config.getUsername(),
  460.                     remote);
  461.             String prompt = SshdText.get().knownHostsUnknownKeyPrompt;
  462.             return askUser(provider, uri, prompt, //
  463.                     format(SshdText.get().knownHostsUnknownKeyMsg,
  464.                             remoteHost),
  465.                     format(SshdText.get().knownHostsKeyFingerprints,
  466.                             keyAlgorithm),
  467.                     md5, sha256);
  468.         }

  469.         public ModifiedKeyHandling acceptModifiedServerKey(
  470.                 InetSocketAddress remoteAddress, PublicKey expected,
  471.                 PublicKey actual, Path path) {
  472.             Check check = checkMode(remoteAddress, true);
  473.             if (check == Check.ALLOW) {
  474.                 // Never auto-store on CHECK.ALLOW
  475.                 return ModifiedKeyHandling.ALLOW;
  476.             }
  477.             String keyAlgorithm = actual.getAlgorithm();
  478.             String remoteHost = remoteAddress.getHostString();
  479.             URIish uri = JGitUserInteraction.toURI(config.getUsername(),
  480.                     remoteAddress);
  481.             List<String> messages = new ArrayList<>();
  482.             String warning = format(
  483.                     SshdText.get().knownHostsModifiedKeyWarning,
  484.                     keyAlgorithm, expected.getAlgorithm(), remoteHost,
  485.                     KeyUtils.getFingerPrint(BuiltinDigests.md5, expected),
  486.                     KeyUtils.getFingerPrint(BuiltinDigests.sha256, expected),
  487.                     KeyUtils.getFingerPrint(BuiltinDigests.md5, actual),
  488.                     KeyUtils.getFingerPrint(BuiltinDigests.sha256, actual));
  489.             messages.addAll(Arrays.asList(warning.split("\n"))); //$NON-NLS-1$

  490.             if (check == Check.DENY) {
  491.                 if (provider != null) {
  492.                     messages.add(format(
  493.                             SshdText.get().knownHostsModifiedKeyDenyMsg, path));
  494.                     askUser(provider, uri, null,
  495.                             messages.toArray(new String[0]));
  496.                 }
  497.                 return ModifiedKeyHandling.DENY;
  498.             }
  499.             // ASK -- two questions: procceed? and store?
  500.             List<CredentialItem> items = new ArrayList<>(messages.size() + 2);
  501.             for (String message : messages) {
  502.                 items.add(new CredentialItem.InformationalMessage(message));
  503.             }
  504.             CredentialItem.YesNoType proceed = new CredentialItem.YesNoType(
  505.                     SshdText.get().knownHostsModifiedKeyAcceptPrompt);
  506.             CredentialItem.YesNoType store = new CredentialItem.YesNoType(
  507.                     SshdText.get().knownHostsModifiedKeyStorePrompt);
  508.             items.add(proceed);
  509.             items.add(store);
  510.             if (provider.get(uri, items) && proceed.getValue()) {
  511.                 return store.getValue() ? ModifiedKeyHandling.ALLOW_AND_STORE
  512.                         : ModifiedKeyHandling.ALLOW;
  513.             }
  514.             return ModifiedKeyHandling.DENY;
  515.         }

  516.         public boolean createNewFile(Path path) {
  517.             if (provider == null) {
  518.                 // We can't ask, so don't create the file
  519.                 return false;
  520.             }
  521.             URIish uri = new URIish().setPath(path.toString());
  522.             return askUser(provider, uri, //
  523.                     format(SshdText.get().knownHostsUserAskCreationPrompt,
  524.                             path), //
  525.                     format(SshdText.get().knownHostsUserAskCreationMsg, path));
  526.         }
  527.     }

  528.     private static class HostKeyFile extends ModifiableFileWatcher
  529.             implements Supplier<List<HostEntryPair>> {

  530.         private List<HostEntryPair> entries = Collections.emptyList();

  531.         public HostKeyFile(Path path) {
  532.             super(path);
  533.         }

  534.         @Override
  535.         public List<HostEntryPair> get() {
  536.             Path path = getPath();
  537.             synchronized (this) {
  538.                 try {
  539.                     if (checkReloadRequired()) {
  540.                         entries = reload(getPath());
  541.                     }
  542.                 } catch (IOException e) {
  543.                     LOG.warn(format(SshdText.get().knownHostsFileReadFailed,
  544.                             path));
  545.                 }
  546.                 return Collections.unmodifiableList(entries);
  547.             }
  548.         }

  549.         private List<HostEntryPair> reload(Path path) throws IOException {
  550.             try {
  551.                 List<KnownHostEntry> rawEntries = KnownHostEntryReader
  552.                         .readFromFile(path);
  553.                 updateReloadAttributes();
  554.                 if (rawEntries == null || rawEntries.isEmpty()) {
  555.                     return Collections.emptyList();
  556.                 }
  557.                 List<HostEntryPair> newEntries = new LinkedList<>();
  558.                 for (KnownHostEntry entry : rawEntries) {
  559.                     AuthorizedKeyEntry keyPart = entry.getKeyEntry();
  560.                     if (keyPart == null) {
  561.                         continue;
  562.                     }
  563.                     try {
  564.                         PublicKey serverKey = keyPart.resolvePublicKey(null,
  565.                                 PublicKeyEntryResolver.IGNORING);
  566.                         if (serverKey == null) {
  567.                             LOG.warn(format(
  568.                                     SshdText.get().knownHostsUnknownKeyType,
  569.                                     path, entry.getConfigLine()));
  570.                         } else {
  571.                             newEntries.add(new HostEntryPair(entry, serverKey));
  572.                         }
  573.                     } catch (GeneralSecurityException e) {
  574.                         LOG.warn(format(SshdText.get().knownHostsInvalidLine,
  575.                                 path, entry.getConfigLine()));
  576.                     }
  577.                 }
  578.                 return newEntries;
  579.             } catch (FileNotFoundException | NoSuchFileException e) {
  580.                 resetReloadAttributes();
  581.                 return Collections.emptyList();
  582.             }
  583.         }
  584.     }

  585.     private int parsePort(String s) {
  586.         try {
  587.             return Integer.parseInt(s);
  588.         } catch (NumberFormatException e) {
  589.             return -1;
  590.         }
  591.     }

  592.     private SshdSocketAddress toSshdSocketAddress(@NonNull String address) {
  593.         String host = null;
  594.         int port = 0;
  595.         if (HostPatternsHolder.NON_STANDARD_PORT_PATTERN_ENCLOSURE_START_DELIM == address
  596.                 .charAt(0)) {
  597.             int end = address.indexOf(
  598.                     HostPatternsHolder.NON_STANDARD_PORT_PATTERN_ENCLOSURE_END_DELIM);
  599.             if (end <= 1) {
  600.                 return null; // Invalid
  601.             }
  602.             host = address.substring(1, end);
  603.             if (end < address.length() - 1
  604.                     && HostPatternsHolder.PORT_VALUE_DELIMITER == address
  605.                             .charAt(end + 1)) {
  606.                 port = parsePort(address.substring(end + 2));
  607.             }
  608.         } else {
  609.             int i = address
  610.                     .lastIndexOf(HostPatternsHolder.PORT_VALUE_DELIMITER);
  611.             if (i > 0) {
  612.                 port = parsePort(address.substring(i + 1));
  613.                 host = address.substring(0, i);
  614.             } else {
  615.                 host = address;
  616.             }
  617.         }
  618.         if (port < 0 || port > 65535) {
  619.             return null;
  620.         }
  621.         return new SshdSocketAddress(host, port);
  622.     }

  623.     private Collection<SshdSocketAddress> getCandidates(
  624.             @NonNull String connectAddress,
  625.             @NonNull InetSocketAddress remoteAddress) {
  626.         Collection<SshdSocketAddress> candidates = new TreeSet<>(
  627.                 SshdSocketAddress.BY_HOST_AND_PORT);
  628.         candidates.add(SshdSocketAddress.toSshdSocketAddress(remoteAddress));
  629.         SshdSocketAddress address = toSshdSocketAddress(connectAddress);
  630.         if (address != null) {
  631.             candidates.add(address);
  632.         }
  633.         return candidates;
  634.     }

  635.     private String createHostKeyLine(Collection<SshdSocketAddress> patterns,
  636.             PublicKey key, Configuration config) throws Exception {
  637.         StringBuilder result = new StringBuilder();
  638.         if (config.getHashKnownHosts()) {
  639.             // SHA1 is the only algorithm for host name hashing known to OpenSSH
  640.             // or to Apache MINA sshd.
  641.             NamedFactory<Mac> digester = KnownHostDigest.SHA1;
  642.             Mac mac = digester.create();
  643.             if (prng == null) {
  644.                 prng = new SecureRandom();
  645.             }
  646.             byte[] salt = new byte[mac.getDefaultBlockSize()];
  647.             for (SshdSocketAddress address : patterns) {
  648.                 if (result.length() > 0) {
  649.                     result.append(',');
  650.                 }
  651.                 prng.nextBytes(salt);
  652.                 KnownHostHashValue.append(result, digester, salt,
  653.                         KnownHostHashValue.calculateHashValue(
  654.                                 address.getHostName(), address.getPort(), mac,
  655.                                 salt));
  656.             }
  657.         } else {
  658.             for (SshdSocketAddress address : patterns) {
  659.                 if (result.length() > 0) {
  660.                     result.append(',');
  661.                 }
  662.                 KnownHostHashValue.appendHostPattern(result,
  663.                         address.getHostName(), address.getPort());
  664.             }
  665.         }
  666.         result.append(' ');
  667.         PublicKeyEntry.appendPublicKeyEntry(result, key);
  668.         return result.toString();
  669.     }

  670.     private String updateHostKeyLine(String line, PublicKey newKey)
  671.             throws IOException {
  672.         // Replaces an existing public key by the new key
  673.         int pos = line.indexOf(' ');
  674.         if (pos > 0 && line.charAt(0) == KnownHostEntry.MARKER_INDICATOR) {
  675.             // We're at the end of the marker. Skip ahead to the next blank.
  676.             pos = line.indexOf(' ', pos + 1);
  677.         }
  678.         if (pos < 0) {
  679.             // Don't update if bogus format
  680.             return null;
  681.         }
  682.         StringBuilder result = new StringBuilder(line.substring(0, pos + 1));
  683.         PublicKeyEntry.appendPublicKeyEntry(result, newKey);
  684.         return result.toString();
  685.     }

  686. }