summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/openslx/imagemaster/serversession/ServerAuthenticator.java
blob: 4ec5acf6852ca489604eb1026bb3d9194a982d1a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package org.openslx.imagemaster.serversession;

import java.nio.ByteBuffer;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;
import org.apache.thrift.TException;
import org.openslx.encryption.AsymEncryptionHandler;
import org.openslx.imagemaster.db.DbSatellite;
import org.openslx.imagemaster.thrift.iface.ServerAuthenticationError;
import org.openslx.imagemaster.thrift.iface.ServerAuthenticationException;
import org.openslx.imagemaster.util.RandomString;

/**
 * Authenticating a server with message signing.
 */
public class ServerAuthenticator
{

	private static Logger log = Logger.getLogger( ServerAuthenticator.class );

	/**
	 * Servers currently doing authentication. Maps from organization to the challenge we sent.
	 */
	private static Map<String, byte[]> authenticatingServers = new ConcurrentHashMap<>();

	/**
	 * Start the server authentification.
	 * 
	 * @param organization
	 *           the organization of the server
	 * @return encrypted random string
	 */
	public static ByteBuffer startServerAuthentication( String organization )
	{
		byte[] secret = RandomString.generateBinary( 100 );
		authenticatingServers.put( organization, secret );
		log.info( "Server of organinzation '" + organization
				+ "' starts to authenticate. And got string: '" + secret.length
				+ "'" );
		return ByteBuffer.wrap( secret );
	}

	/**
	 * Authenticate with the challengeResponse.
	 * 
	 * @param organizationId Is already verified.
	 * @param address
	 * @param challengeResponse
	 * @return
	 * @throws ServerAuthenticationException
	 * @throws TException
	 */
	public static ServerUser serverAuthenticate( DbSatellite satellite, ByteBuffer challengeResponse )
			throws ServerAuthenticationException
	{
		byte[] encryptedBytes = new byte[ challengeResponse.remaining() ];
		challengeResponse.get( encryptedBytes );

		AsymEncryptionHandler verifier = new AsymEncryptionHandler( satellite.getPubkey() );

		if ( !verifier.verifyMessage( encryptedBytes, authenticatingServers.get( satellite.getOrganizationId() ) ) )
			throw new ServerAuthenticationException( ServerAuthenticationError.CHALLENGE_FAILED, "You failed the encryption challenge. private and public key don't seem to match." );

		log.info( "Server of organinzation " + satellite.getName() + " (" + satellite.getOrganizationId() + ") authenticated." );

		authenticatingServers.remove( satellite.getOrganizationId() );

		return new ServerUser( satellite.getOrganizationId(), satellite.getAddress() );
	}
}