package org.openslx.imagemaster.serversession; import java.nio.ByteBuffer; import java.util.HashMap; import org.apache.log4j.Logger; import org.apache.thrift.TException; import org.openslx.imagemaster.thrift.iface.AuthenticationException; import org.openslx.imagemaster.thrift.iface.ServerAuthenticationError; import org.openslx.imagemaster.thrift.iface.ServerAuthenticationException; import org.openslx.imagemaster.util.AsymMessageVerifier; import org.openslx.imagemaster.util.RandomString; /** * Authenticating a server with message signing. */ public class ServerAuthenticator { private static Logger log = Logger.getLogger( ServerAuthenticator.class ); // map of currently authenticating servers private static HashMap authenticatingServers = new HashMap(); /** * Start the server authentification. * * @param organization * the organization of the server * @return encrypted random string */ public static String startServerAuthentication( String organization ) { String secret = RandomString.generate( 100, false ); synchronized ( authenticatingServers ) { authenticatingServers.put( organization, secret ); log.info( "Server of organinzation '" + organization + "' starts to authenticate. And got string: '" + secret + "'" ); } return secret; } /** * Authenticate with the challengeResponse. * * @param organization Is already verified. * @param address * @param challengeResponse * @return * @throws AuthenticationException * @throws TException */ public static ServerUser serverAuthenticate( String organization, String address, ByteBuffer challengeResponse ) throws AuthenticationException, TException { byte[] bytes = new byte[ 512 ]; challengeResponse.get( bytes ); boolean result = false; AsymMessageVerifier verifier = null; try { verifier = new AsymMessageVerifier( organization ); } catch ( Exception e ) { throw new ServerAuthenticationException( ServerAuthenticationError.INVALID_ORGANIZATION, "Organization not found." ); } try { result = verifier.verifyMessage( bytes, authenticatingServers.get( organization ).getBytes() ); } catch ( Exception e ) { log.error( "Error while verifying message", e ); throw new ServerAuthenticationException( ServerAuthenticationError.INVALID_KEY, "Could not verfiy key." ); } if ( !result ) { throw new ServerAuthenticationException( ServerAuthenticationError.INVALID_KEY, "Could not verfiy key." ); } log.info( "Server of organinzation '" + organization + " authenticated." ); authenticatingServers.remove( organization ); return new ServerUser( organization, address ); } }