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.

OpenSshServerKeyVerifier.java 24KB

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