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 25KB

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