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

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