     [file version.texi not included]

Java TOTP Server Library
************************

This manual is for the Java TOTP server library (version VERSION, UPDATED).

Copyright © 2013-2018 Enrico M. Crisostomo

     Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts.  A copy of the license is included in the section entitled `GNU Free Documentation License'.

Introduction
************

The Time-Based One-Time Password algorithm (TOTP) (RFC 6238) is a an extension of the HMAC-based One-Time Password algorithm (HOTP) (RFC 4226) which is the basis of many two-phase authentication solutions such as Google's, Microsoft's and others.

The Google Authenticator client application is probably the most widely used software-based TOTP token generator, and is available as a free application on all the mainstream mobile operating systems.  It is probably the de-facto standard TOTP password generator and it is used to manage not only Google's, but other accounts' passwords as well.  Google Authenticator is a flexible, easy to use, easy to configure, free application that can be leveraged by any system, provided it has a back-end that implements the functionality to validate a TOTP password.  This Java library provides the building blocks of such a back-end:

  * Credential generation.

  * Credential verification.

  * QR code generation (The QR code can be obtained using a generated URL, which relies on the goQR HTTP API to create a compliant QR code encoding the necessary information.)  for the easy configuration (Google Authenticator can use the built-in camera of a cellular phone to take a picture of a QR code and configure a new account using the information contained therein.) of an account in the Google Authenticator application.

Design Philosophy
=================

This library has been designed with simplicity in mind, trying to follow the KISS principle.  This basically means that the library does one thing, and it strives hard to do it well: TOTP authentication.  No more, no less.

There exist more complex and comprehensive solutions, and if you need something more than being able to perform TOTP authentication, chances are you should assess whether to use this library or some other product.

On the other hand, if what you are looking is performing TOTP authentication, then this library will provide an easy to use API and a very compact library: currently, the size of the library JAR archive is smaller than 20 kB.  Most importantly, this library has very few (This library's dependencies are compact as well and do not pull-in a chain of dependencies themselves.)  dependencies:

  * The Apache Commons Codec library.

  * The Apache HTTP components library.

The library contains Java SE code and the back-end components are implemented as POJOs (using current Java jargon).  Therefore, it can be included and used in any Java application and does not have dependencies with any framework or technology (Earlier versions of this library had a dependency with JAX-RS v. 2 that was removed in v. 0.4.5.)  other than a Java SE 7 runtime environment.

Overview
********

The TOTP algorithm (specified by RFC 6238) is an extension of the HOTP algorithm that uses a time-based moving factor instead of an event counter.  One of the purposes of that work is, in the words of the authors:

     The proposed algorithm can be used across a wide range of network applications, from remote Virtual Private Network (VPN) access and Wi-Fi network logon to transaction-oriented Web applications.  The authors believe that a common and shared algorithm will facilitate adoption of two-factor authentication on the Internet by enabling interoperability across commercial and open-source implementations.

In fact, as expected by the authors, both two-factor authentication and TOTP are being widely adopted.  Google enabled TOTP-based two-factor authentication for its users and developed a software TOTP token generator, Google Authenticator, running on all the mainstream smartphone operating systems, which is now the de-facto standard token generator (at least for non-corporate use).

TOTP-based two-factor authentication schemes usually require the user to send its TOTP password alongside its credentials.  The TOTP password is time-based, it is calculated with a cryptographic algorithm and its validity is very short: RFC 6238 recommends to used a time-step size of 30 seconds.  The very short expiration time of each password is a key security factor against attacks.

The security analysis (RFC 4226) of this algorithm concludes that the best attack against the HOTP function is the brute force attack.  The security of the algorithm can be approximate (RFC 4226) as

where s is the look-ahead synchronization window size (Referred to simply as window size in the rest of this manual.), v is the number of verification attempts and d is the number of digits in the TOTP password.  That is: if a brute force attack with v verification attempts is used, then its probability of success is

RFC 4226 recommends that d \geq 6, and this library validates 6-digit TOTP passwords, which is the password length currently used by Google Authenticator.  Passwords of up to 9 decimal digits could be used, which is the maximum that can be represented by the 31-bit string returned by the dynamic truncation function.

Evaluating the probability p of making a successful attack with s = 10 and d = 6 yields that is, v successes every 10.000 attempts.  By limiting the number of unsuccessful authentication attempts a user can perform, a superior bound on p can be established that satisfies the security requirements.

API Description
***************

The TOTP algorithm is used to determine whether the password provided by the prover (The user providing the password generated by his token.)  is proved as authentic by the verifier, given the prover's shared secret and current Unix time.

The two basic operations that this library implements are:

  * Credential creation.

  * Credential authentication.

Credential creation is the process in which the server generates the shared secret and shares it with the client.  The shared secret is generated using a cryptographically strong pseudorandom generator and has to be communicated to the client, so that he can store it and configure its token.  A common way to communicate this information is sending it to the client encoded into a QR code.  The user only needs to scan the QR code with the Google Authenticator application and then discard it immediately.  For the sake of security, TOTP token generators do not generally let users retrieve the shared secrets after an account has been configured.  This way, only individuals in physical possession of a token can use the shared secret to generate TOTP passwords.

Credential authentication is the process in which the server applies the TOTP algorithm to the shared secret and the token-generated password of the prover to determine its authenticity.

All the API members are published by the following interfaces and classes:

IGoogleAuthenticator
     This is the main API interface and it publishes the library entry points.

GoogleAuthenticatorKey
     This class is the credentials container, mainly used when returning newly-created credentials.

GoogleAuthenticatorQRGenerator
     This helper class provides QR code generation using the goQR HTTP API.

ICredentialRepository
     This interface can optionally be implemented by callers to provide callback functions to the library used to interact with a `credential repository', where newly-generated credentials are stored and keys are retrieved when a password must be validated.

Random Number Generator Algorithm and Provider
==============================================

The creation of a shared secret is an important process because the ability of taking over or guessing somebody else's secret could result in account hijacking.  For this reason, and since it is not always practicable or desirable to devise such a creation strategy, this library offers the possibility of creating shared secrets using data coming from a cryptographically strong pseudorandom generator (PRNG).  The default provider (SUN) and the default algorithm (SHA1PRNG) used by this library are available on Oracle Java runtime environments and they were not tested on other implementations where they are likely to be missing.

Users can configure the library to use an alternate provider and algorithm by providing their names as values of the following system properties or they can specify this in the GoogleAuthenticator constructor:

com.warrenstrange.googleauth.rng.algorithm
     If a property with this name is set, the specified random number generator algorithm is used.

com.warrenstrange.googleauth.rng.algorithmProvider
     If a property with this name is set, the specified random number generator algorithm provider is used.  The provider can be overridden if and only if the algorithm is overridden as well.

While explicitly specifying a provider and an algorithm may impair interoperability, on the other hand it guarantees the expected level of randomness and a predictable behaviour.  The performance problems often reported when using a blocking entropy gathering device (see NativePRNG) are an example of why the authors chose the current defaults.

NativePRNG
----------

On some environments the NativePRNG algorithm may be used by default. This algorithm uses the /dev/random device to get random data and this device is blocking on certain platforms (such as Linux).  If the blocking behaviour is undesirable and /dev/urandom can be used as a valid alternative entropy gathering device, then the NativePRNG algorithm can be configured to get random data from /dev/urandom by setting the system property java.security.egd to /dev/urandom, for example passing the following argument to the Java virtual machine:

     -Djava.security.egd=file:/dev/urandom

ICredentialRepository-Related Methods
=====================================

The IGoogleAuthenticator interface originally provided the following methods:

createCredentials()
     Create new credentials.

authorize(String secret, int verificationCode)
     Validate the specified verificationCode with the specified secret using the TOTP algorithm.

When support for the ICredentialRepository callbacks was designed, a new set of methods were added to allow the user to specify a USERNAME to be used to save or retrieve his key.  Such methods are the following:

createCredentials(String userName)
     Create new credentials.

authorizeUser(String userName, int verificationCode)
     Validate the specified verificationCode with the secret of the user with the specified userName using the TOTP algorithm.

Their functionality is identical to that of the aforementioned methods, but in this case no SECRET is returned or passed as a parameter, but is saved or retrieved from the configured ICredentialRepository instance instead.

In the following sections the first generation methods will be used for tutorial purposes, but any of those API calls could be substituted by the corresponding ICredentialRepository-enabled call.

Credential Creation
===================

A new set of credentials can be created using the createCredentials method:

     GoogleAuthenticatorKey createCredentials();

This method computes a new random shared secret wrapped into a GoogleAuthenticatorKey instance.

Credentials
-----------

The GoogleAuthenticatorKey class represents newly generated credentials, as returned by createCredentials.  Instances of this class contains the following data members:

  * The shared secret key.

  * The verification code (The verification code is the TOTP password calculated at t = u, where u is the Unix Epoch.) verificationCode.  The verification code is an optional feature which is not used by some clients such as Google Authenticator.

  * A list of scratch codes scratchCodes.  Scratch codes are randomly generated data (Generated together with the shared secret using the same, cryptographically strong pseudorandom generator.)  that are optionally used as `recovery passwords' in case the token generator is not available.  If this feature is implemented, scratch codes should be usable only once. This library provides scratch codes as an ancillary feature, to offer the client randomly generated data with the same guarantees the shared secret offers.  How scratch codes are used, however, is a responsibility of the prover and this library offers no facility to store them or validate them.

Generating a QR Code
====================

 The Google Authenticator application can be quickly configured using a QR code: the application requests the user to take a photograph of the code and the application uses the data encoded therein to configure a new account.

This approach has several advantages: human errors are reduced to a minimum, or eliminated altogether, the setup process is easy and quick, but most importantly, the shared secret is never shown in plain text.  Unless a malicious user succeeds in stealing a usable picture of the QR code to configure another Google Authenticator instance with the stolen credentials, the shared secret cannot be read, not even by the legitimate owner himself. Therefore, QR code greatly reduce the risk of credentials being intercepted during the delicate phase of the initial interchange.

This library supports this use case providing a ready-to-use goQR HTTP API call to display a QR code encoding all the data of the newly generated credentials:

  * The issuer.

  * The account name.

  * The label.

  * The shared secret.

The QR code encoding the aforementioned data can be created invoking the GoogleAuthenticatorQRGenerator.getOtpAuthURL() method:

     public static String getOtpAuthURL(
       String issuer,
       String accountName,
       GoogleAuthenticatorKey credentials);

as in the following example, where Test Org. is the issuer and test@test.org is the account name (Account names often are email addresses, but they need not be.):

     final GoogleAuthenticatorKey key =
       googleAuthenticator.createCredentials();
     final String otpAuthURL =
       GoogleAuthenticatorQRGenerator.getOtpAuthURL(
         "Test Org.",
         "test@test.org",
         key);

The GoogleAuthenticatorQRGenerator.getOtpAuthURL method will return a goQR API URL which can then be used to generate the QR code image.

The otpauth Scheme
------------------

Google Authenticator expects an URI conforming to the otpauth scheme to configure a new account.

     otpauth://TYPE/LABEL?PARAMETERS

This URI is generated by the library using the information passed to the API methods.  The most important pieces of information are:

  * The TYPE, which is always totp.

  * The LABEL, conforming to the following ABNF grammar:

          label = accountname / issuer (":" / "%3A") *"%20" accountname

  * The PARAMETERS.  The library automatically adds the two required parameters issuer and secret.  The secret is the shared secret, encoded in Base32 (RFC 5348).

The Issuer
..........

The issuer identifies the service provider associated with the account being created, and it must be URL-encoded.  The issuer information is optional and is present in both the label and the query parameters of an optauth URI.  Although optional, it is strongly recommended to include it.

The QR Code
-----------

The goQR API currently generates the QR code as an image in PNG format (see qr).

Figure: A QR code generated by goQR.

Since one of the reasons why QR codes are used in the first place is making it more difficult to a man in the middle to steal a newly-generated identity, and since it encodes the shared secret, implementors should make sure the QR code is treated as securely as any other kind of credential.

Generating a Password
=====================

A TOTP password can be created using one of the getTotpPassword* methods, specifying:

  * The secret or the username.

  * The time for which the password should be generated.

Validating a Password
=====================

A TOTP password is validated using one of the different authorize* methods provided by the library.  To validate a password, the TOTP algorithm requires:

  * The password to validate.

  * The shared secret (The library API treats one-time passwords as integers.).

  * The time-based moving factor.

The client and the server should agree on how to calculate the time-based moving factor.  RFC 6238 recommends using a default time-step size of 30 seconds and this library adheres to that recommendation.  The library API allows callers to specify the number of time-step windows that should be checked during the validation process, but does not currently allows the time-step size to be overridden.

When the number x of time-step windows to use is specified, the implementation will check all the integral time-step in an interval I (roughly) centered in the current instant of time: I = [\lfloor -(x-1)/2 \rfloor, \lfloor x/2 \rfloor].

API
***

The API is currently published by the following classes and interfaces:

GoogleAuthenticator
     The IGoogleAuthenticator implementation.

GoogleAuthenticatorConfig
     The configuration parameters used during the TOTP password validation, including time step size, window size, number of digits and key representations.

GoogleAuthenticatorConfig.GoogleAuthenticatorConfigBuilder
     The factory for GoogleAuthenticatorConfig instances.

GoogleAuthenticatorException
     The root exception used by the library.

GoogleAuthenticatorKey
     This class is the credentials container, mainly used when returning newly-created credentials.

GoogleAuthenticatorQRGenerator
     Helper class providing QR code generation using the goQR HTTP API.

ICredentialRepository
     This interface can optionally be implemented by callers to provide callback functions to the library used to interact with a `credential repository', where newly-generated credentials are stored and keys are retrieved when a password must be validated.

IGoogleAuthenticator
     This is the main API interface and it publishes the library entry points.

KeyRepresentation
     An enumeration of all the available secret key representations, currently:

       * BASE32

       * BASE64

ReseedingSecureRandom
     A wrapper class around SecureRandom that takes care of reseeding the wrapper instance every certain number of operations.  Currently, this parameter is not overridable.

GoogleAuthenticator
===================

The GoogleAuthenticator class is the provided implementation of the IGoogleAuthenticator interface.  This class adds no public methods to those defined in its primary interface.

This implementation conforms to the recommendations and the default parameter values specified in RFC 6238.  Specifically, this class uses:

  * The HMAC-SHA-1 algorithm is used, as specified by RFC 4226. RFC 6238 specifies that implementors may also use HMAC-SHA-256 and HMAC-SHA-512 and can be used by specifying them in the constructor of GoogleAuthenticator.

  * A time-step size of 30 seconds is used, as recommended in by RFC 6238.

The parameters used during the TOTP password validation are:

  * Time step size.

  * Windows size.

  * Number of digits (key modulus).

Furthermore, the secret key can be provided in one of the supported representations:

  * BASE32.

  * BASE64.

Base32 is the representation used by default by Google Authenticator, and Base64 is offered since it is the default representation used by RFC 6030, Portable Symmetric Key Container (PSKC), since it is commonly used by software platforms and hardware TOTP token providers.

All these parameters can be configured by passing an instance of the GoogleAuthenticatorConfig class to the constructor of the GoogleAuthenticator class.

GoogleAuthenticatorConfigBuilder
--------------------------------

GoogleAuthenticatorConfig instances can only be built using GoogleAuthenticatorConfigBuilder instances. The following fragment, for example, builds a GoogleAuthenticator instance with the following characteristics:

  * It uses a time step size of one minute.

  * It validate TOTP password checking an interval of 5 time steps centered at the current time.

  * It validates and creates TOTP passwords of 8 digits.

  * It requests 10 scratch codes.

     GoogleAuthenticatorConfigBuilder gacb =
       new GoogleAuthenticatorConfigBuilder()
         .setTimeStepSizeInMillis(TimeUnit.SECONDS.toMillis(60))
         .setWindowSize(5)
         .setCodeDigits(8)
         .setNumberOfScratchCodes(10);
     GoogleAuthenticator ga =
       new GoogleAuthenticator(gacb.build());

GoogleAuthenticatorException
============================

This class is the root exception used by library methods.  The exception is a subtype of RuntimeException so that library method callers need neither catch nor declare this exception in their calling methods.

GoogleAuthenticatorKey
======================

This inmutable class is a JavaBean used by the GoogleAuthenticator library to represent a newly-created set of credentials.  Currently, this class publishes the following read-only properties:

GoogleAuthenticatorCofig config
     The TOTP configuration of this key.

String key
     The shared secret.

List<Integer> scratchCodes
     A list of scratch codes.  By default, 5 scratch codes are provided. There currently is no way to generate scratch codes without creating a new credential.

int verificationCode
     The verification code, that is, the TOTP password when at time-step 0 (the Unix Epoch).

GoogleAuthenticatorKey.Builder
------------------------------

Instances of GoogleAuthenticatorKey can only be built using GoogleAuthenticatorKey.Builder instances.  The builder publishes all the properties of the GoogleAuthenticatorKey class.  The following fragment, for example, builds an instance with the following characteristics:

  * It has a default GoogleAuthenticatorConfig.

  * It has the following secret key: secretKey.

  * It has the following verification code: 123456.

  * It has an empty list of scratch codes.

     GoogleAuthenticatorConfig config =
       new GoogleAuthenticatorConfig
         .GoogleAuthenticatorConfigBuilder()
         .build();

     GoogleAuthenticatorKey credentials =
       new GoogleAuthenticatorKey
         .Builder("secretKey")
         .setConfig(config)
         .setVerificationCode(123456)
         .setScratchCodes(new ArrayList<Integer>())
         .build();

Manually building instances of this class is generally useful to re-create QR codes for an existing key.

GoogleAuthenticatorQRGenerator
==============================

This class is a helper class which provides a way to generate QR codes using the goQR API.  Please note that the usage of this method is subject to the license and usage restrictions of the goQR API.

This class publishes the following method:

static String getOtpAuthURL(String issuer, String accountName, GoogleAuthenticatorKey credentials)
     Returns the URL of a goQR API call to generate a QR barcode to be loaded into the Google Authenticator application.  The user scans this bar code with the application on their smart phones or enters the secret manually.

static String getOtpAuthTotpURL(String issuer, String accountName, GoogleAuthenticatorKey credentials)
     Returns the key URI, that is a otpauth:// URL as specified by the key URI format, to be loaded in compliant applications.

Generating a QR Code, provides a detailed description of this method's functionality.

ICredentialRepository
=====================

The ICredentialRepository is a service interface which can be implemented by a library user to provide a callback that establishes a relation between a user name and its shared secret.  The methods of the API that accept a user name instead of the shared secret will use this callback to retrieve that user's shared key.  This interface is optional and needs not be implemented, unless you want the library code to perform basic user management tasks.  Methods accepting user names are used when no ICredentialRepository service is available will fail.

This interface defines the following methods:

String getSecretKey(String userName);
     This method returns the shared secret of the specified user.  If the specified user does not exist, the method shall fail throwing a GoogleAuthenticatorException.

void saveUserCredentials(String userName, String secretKey, int validationCode, List<Integer> scratchCodes);
     This method saves the credentials of the specified user.

The service lookup mechanism used by the library is the ServiceLoader facility provided by Java SE.  Implementors needs creating a file named after the service interface, that is

     com.warrenstrange.googleauth.ICredentialRepository

and one line with the name of each implementing class.  The library will use the ServiceLoader class to discover the available implementations and will use the first available.

Setting a credential repository on a per-instance basis
-------------------------------------------------------

Since 1.0.0, the ServiceLoader API is not the only way to set the credential repository: the setCredentialRepository(ICredentialRepository) method can be used to explicitly set the credential repository used by an IGoogleAuthenticator instance, effectively disabling the autmatic service discovery described in the previous section.

Disabling the credential repository feature
-------------------------------------------

Sometimes it may be desirable to disable this feature on specific instances.  This can be achieved by passing null to the setCredentialRepository method.

IGoogleAuthenticator
====================

This interfaces publishes the main library API:

GoogleAuthenticatorKey createCredentials();
     This method generates a new set of credentials including:

       * Secret key.

       * Validation code.

       * A list of scratch codes.

     The user must register this secret on their device.

GoogleAuthenticatorKey createCredentials(String userName);
     This method generates a new set of credentials invoking the createCredentials method with no arguments.  The generated credentials are then saved using the configured ICredentialRepository service.

     The user must register this secret on their device.

boolean authorize(String secret, int verificationCode);
     Checks a verification code against a secret key using the current time.  The algorithm also checks in a time window whose size determined by the windowSize property of this class.  The default value of 30 seconds recommended by RFC 6238 is used for the interval size.

boolean authorize(String secret, int verificationCode, long time);
     Checks a verification code against a secret key the specified time. The algorithm also checks in a time window whose size determined by the windowSize property of this class.  The default value of 30 seconds recommended by RFC 6238 is used for the interval size.

boolean authorizeUser(String userName, int verificationCode);
     This method validates a verification code of the specified user whose private key is retrieved from the configured credential repository. This method delegates the validation to the authorize(String, int) method.

boolean authorizeUser(String userName, int verificationCode, long time);
     This method validates a verification code of the specified user whose private key is retrieved from the configured credential repository. This method delegates the validation to the authorize(String, int, long) method.

ICredentialRepository getCredentialRepository();
     This method returns the credential repository used by this instance, or null if none is set or none can be found using the ServiceLoader API.

void setCredentialRepository(ICredentialRepository repository);
     This method sets the credential repository used by this instance.  If null is passed to this method, no credential repository will be used, nor discovered using the ServiceLoader API.

getTotpPassword(String secret);
     This method generates the current TOTP password using the specified secret.

getTotpPassword(String secret, long time);
     This method generates the TOTP password at the specified time using the specified secret.

getTotpPasswordOfUser(String userName);
     This method generates the current TOTP password using key of the specified user.

getTotpPasswordOfUser(String userName, long time);
     This method generates the TOTP password at the specified time using key of the specified user.

GNU Free Documentation License
******************************

     [file fdl.texi not included]