wstrange / GoogleAuth

Google Authenticator Server side code

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

GoogleAuthenticator class is thread-safe?

s-papa opened this issue · comments

Is it safe to generate keys or verify passwords in a multi-threaded environment using singleton instance for the GoogleAuthenticator class

commented

Had the same question. I have checked source code and found no global properties usage except configuration, CredentialRepository, and SecureRandom.
Configuration itself is private final, but mutable. Any way even if it is mutable, there is no public getter (actually no getter at all), so no one can change it from outside, and from inside class only reads values. SecureRandom implements Random which is thread safe.
At last, we have CredentialRepository. When we check the following code:

    public ICredentialRepository getCredentialRepository() {
        if (this.credentialRepositorySearched) {
            return this.credentialRepository;
        } else {
            this.credentialRepositorySearched = true;
            ServiceLoader<ICredentialRepository> loader = ServiceLoader.load(ICredentialRepository.class);
            Iterator var2 = loader.iterator();
            if (var2.hasNext()) {
                ICredentialRepository repository = (ICredentialRepository)var2.next();
                this.credentialRepository = repository;
            }

            return this.credentialRepository;
        }
    }

we see that here GoogleAuthenticator tries to load Service and cache it. And unfortunately, at least this method is not thread safe. Problem could happened if several threads will use GoogleAuthenticator straight after class was instantiated. One more issue here is a public setter for CredentialRepository: setCredentialRepository which is also not synchronized with other methods.

So out of the box this class is not a thread safe. So my suggestion is to extend this class and implement custom synchronization for methods. Any way on many *nix systems securerandom will block as it uses /dev/random stream to generate random numbers, so won't be a big penalty for synchronizing business methods. Another question - how faster will be class in genera as we will safe SecureRandom instantiation for every call, which is in this class most expensive. Only profiling on target server could answer this question on 100% :)

wbr,
Mike