in sshd-core/src/main/java/org/apache/sshd/client/keyverifier/KnownHostsServerKeyVerifier.java [349:428]
protected void updateModifiedServerKey(
ClientSession clientSession, SocketAddress remoteAddress, HostEntryPair match, PublicKey actual,
Path file, Collection<HostEntryPair> knownHosts)
throws Exception {
KnownHostEntry entry = match.getHostEntry();
String matchLine = ValidateUtils.checkNotNullAndNotEmpty(entry.getConfigLine(), "No entry config line");
String newLine = prepareModifiedServerKeyLine(
clientSession, remoteAddress, entry, matchLine, match.getServerKey(), actual);
if (GenericUtils.isEmpty(newLine)) {
if (log.isDebugEnabled()) {
log.debug("updateModifiedServerKey({})[{}] no replacement generated for {}",
clientSession, remoteAddress, matchLine);
}
return;
}
if (matchLine.equals(newLine)) {
if (log.isDebugEnabled()) {
log.debug("updateModifiedServerKey({})[{}] unmodified updated line for {}",
clientSession, remoteAddress, matchLine);
}
return;
}
List<String> lines = new ArrayList<>();
synchronized (updateLock) {
int matchingIndex = -1; // read all lines but replace the updated one
try (BufferedReader rdr = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
for (String line = rdr.readLine(); line != null; line = rdr.readLine()) {
// skip if already replaced the original line
if (matchingIndex >= 0) {
lines.add(line);
continue;
}
line = GenericUtils.trimToEmpty(line);
if (GenericUtils.isEmpty(line)) {
lines.add(line);
continue;
}
int pos = line.indexOf(ConfigFileReaderSupport.COMMENT_CHAR);
if (pos == 0) {
lines.add(line);
continue;
}
if (pos > 0) {
line = line.substring(0, pos);
line = line.trim();
}
if (!matchLine.equals(line)) {
lines.add(line);
continue;
}
lines.add(newLine);
matchingIndex = lines.size();
}
}
ValidateUtils.checkTrue(matchingIndex >= 0, "No match found for line=%s", matchLine);
try (Writer w = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
for (String l : lines) {
w.append(l).append(IoUtils.EOL);
}
}
synchronized (match) {
match.setServerKey(actual);
entry.setConfigLine(newLine);
}
}
if (log.isDebugEnabled()) {
log.debug("updateModifiedServerKey({}) replaced '{}' with '{}'", file, matchLine, newLine);
}
resetReloadAttributes(); // force reload on next verification
}