HostKeyVerifierImpl.java 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package hudson.plugins.ec2.ssh;
  2. import java.util.logging.Logger;
  3. import com.trilead.ssh2.ServerHostKeyVerifier;
  4. import com.trilead.ssh2.crypto.digest.MD5;
  5. /**
  6. * {@link ServerHostKeyVerifier} that makes sure that the host key fingerprint
  7. * showed up in {@link ConsoleOutput#getOutput()}.
  8. *
  9. * @author Kohsuke Kawaguchi
  10. */
  11. public class HostKeyVerifierImpl implements ServerHostKeyVerifier {
  12. private final String console;
  13. public HostKeyVerifierImpl(String console) {
  14. this.console = console;
  15. }
  16. private String getFingerprint(byte[] serverHostKey) {
  17. MD5 md5 = new MD5();
  18. md5.update(serverHostKey);
  19. byte[] fingerprint = new byte[16];
  20. md5.digest(fingerprint);
  21. StringBuilder buf = new StringBuilder();
  22. for( byte b : fingerprint ) {
  23. if(buf.length()>0) buf.append(':');
  24. buf.append(String.format("%02x",b));
  25. }
  26. return buf.toString();
  27. }
  28. public boolean verifyServerHostKey(String hostname, int port, String serverHostKeyAlgorithm, byte[] serverHostKey) throws Exception {
  29. String fingerprint = getFingerprint(serverHostKey);
  30. LOGGER.fine("Host key fingerprint of "+hostname+" is "+fingerprint);
  31. boolean matches = console.contains(fingerprint);
  32. if(!matches)
  33. LOGGER.severe("No matching fingerprint found in the console output: "+console);
  34. return matches;
  35. }
  36. private static final Logger LOGGER = Logger.getLogger(HostKeyVerifierImpl.class.getName());
  37. }