Showing posts with label Authentication. Show all posts
Showing posts with label Authentication. Show all posts

Monday, December 4, 2023

How TOPT Works: Generating OTPs Without Internet Connection

Introduction

Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an internet connection? This fascinating technology is made possible through Time-Based One-Time Passwords (TOTP). In this article, we will explore the mechanics of TOTP, its security features, and why it doesn't rely on the internet at the client-side for generating OTPs.

Understanding TOPT

1. TOPT in a Nutshell

TOPT, or Time-Based One-Time Password, is a security feature designed to enhance the authentication process. It generates OTPs that are only valid for a short period, typically 30 seconds. TOPT uses a secret key, often shared between the server and the user's device, to generate these OTPs. The central idea is to provide a second factor of authentication, beyond just a static password, to strengthen security.

2. The RSA Authenticator App

One popular example of a TOPT implementation is the RSA Authenticator app. This app is commonly used for two-factor authentication and generates OTPs even when the device is offline. So, how does it work?

The Inner Workings of TOPT

1. Secret Key and Initialization

When setting up TOPT on a device, the user and the authentication server share a secret key. This key is securely stored on both sides and is crucial for generating the OTPs. The server also maintains a counter that increments every 30 seconds.

2. Time-Step and Hashing

To generate an OTP, the device combines the secret key with a time-step value. This time-step value is derived from the current time, typically using Unix time (the number of seconds since January 1, 1970). The resulting value is then hashed, often using the HMAC-SHA1 algorithm.

3. Presentation of OTP

The resulting hash is typically a 160-bit value, which is then truncated to obtain a 6 to 8 digit OTP. The truncation involves taking a subset of bits from the hash. The number of digits and the specific bits selected are implementation-dependent.

4. Rolling Code

The server, which is aware of the current time and the shared secret key, can perform the same process to generate an OTP. If the generated OTP matches the one presented by the user, access is granted.

Advantages of TOPT

1. Offline OTP Generation

One of the major advantages of TOPT is that it does not require an internet connection to generate OTPs. The algorithm is based on a predefined time-step, allowing the device and the server to independently generate OTPs at the same time. This is particularly useful when an internet connection is unavailable, ensuring users can still access their accounts securely.

2. Enhanced Security

TOPT significantly enhances security because the OTPs are time-bound and change frequently. Even if an attacker intercepts an OTP, it will be invalid within seconds, reducing the risk of unauthorized access.

TOTP: A Special Case of TOPT

1. What is TOTP?

TOTP, or Time-Based One-Time Password, is a specific implementation of TOPT. It uses the current time as the input for generating OTPs. TOTP ensures that OTPs are synchronized between the device and the server, allowing for secure authentication even when offline.

2. TOTP in Action

In TOTP, the user and the server share a secret key. The device and the server independently generate OTPs based on the current time. The time-step is typically set to 30 seconds, ensuring that OTPs remain valid for a short period.

Conclusion

TOPT, and specifically TOTP, play a crucial role in modern authentication systems. They provide an additional layer of security by generating time-bound OTPs, without requiring an internet connection at the client-side. This capability ensures that even when internet access is unavailable, users can still access their accounts securely. The use of secret keys and time-based calculations makes TOPT a robust and widely adopted security feature, strengthening the overall security of online services.

Friday, December 16, 2016

What is JSON Web Token?

1. Overview

JSON Web Token or JWT (jot) for short is an open standard (RFC 7519) that defines a compact, URL-safe means of representing claims to be transferred between two parties.  The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or encrypted.

2. Structure

The compacted representation of a signed JWT is a string that has three parts, each separated by a dots (.) :

Eg: 
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
.
eyJzdWIiOiJBYmR1bCIsImlhdCI6MTIzNDU2Nzg5MCwiZXhwIjoxMjM0NTY3ODkwLCJuYmYiOjEyMzQ1Njc4OTAsImlzcyI6Imh0dHA6Ly93YWhlZWR0ZWNoYmxvZy5pbiIsInNjb3BlIjpbInJlYWQiLCJ3cml0ZSJdLCJhZG1pbiI6dHJ1ZX0
.
Ats92uWxgSjQ8vFgQieK9tpBi66csIFHxkTke70FGlI

Each section is Base64Encoded and the first section is called header, the second section is payload and the third section is Signature.

2.1 Header

It consists of two parts: Hashing algorithm (HMAC SHA256 or RSA) and type of the token and to form the first part of the JWT, you need to do Base64Url encoded.

Eg:
{
  "alg": "HS256",
  "typ": "JWT"
}


2.2 Payload

Payload contains the Claims. JWT Claims Set represents a JSON object whose members are the claims conveyed by the JWT i.e. Data to be shared between the applications.
Eg:
{
  "sub": "Abdul",
  "iat": 1234567890,
  "exp": 1234567890,
  "nbf": 1234567890,
  "iss": "http://waheedtechblog.in",
  "scope": ["read","write"],
  "admin": true
}

There are three types of claims: reserved, public, and private claims.

2.2.1 Reserved Claims

These are standard predefined claims defined in the specification which can be used to provide a set of useful claims. Some of them are : 
a. "iss" (Issuer) Claim
b. "sub" (Subject) Claim 
c. "aud" (Audience) Claim
d. "exp" (Expiration Time) Claim
e. "nbf" (Not Before) Claim
f. "iat" (Issued At) Claim
g. "jti" (JWT ID) Claim  


2.2.2 Public Claims

These can be defined at will by those using JWTs. But to avoid collisions they should be defined in the IANA JSON Web Token Registry or be defined as a URI that contains a collision resistant namespace.


2.2.3 Private Claims

  All the custom claims come under private claims and it is created to share information between parties that agree on using them.
{
"scope": ["read","write"],
 "admin": true
}

2.3 Signature

To create the signature part, you have to take the encoded header, the encoded payload, and a SECRET_KEY, the algorithm specified in the header, and sign that.
Eg:
if you want to use the HMAC SHA256 algorithm, the signature will be created in the following way:
HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret)
The signature is used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn't changed along the way.

You will get the below JWT token if you combine above header and payload and will use secret as SECRET_KEY.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJBYmR1bCIsImlhdCI6MTIzNDU2Nzg5MCwiZXhwIjoxMjM0NTY3ODkwLCJuYmYiOjEyMzQ1Njc4OTAsImlzcyI6Imh0dHA6Ly93YWhlZWR0ZWNoYmxvZy5pbiIsInNjb3BlIjpbInJlYWQiLCJ3cml0ZSJdLCJhZG1pbiI6dHJ1ZX0.Ats92uWxgSjQ8vFgQieK9tpBi66csIFHxkTke70FGlI


3. How do JSON Web Tokens work?


1. Browser will log in to Authorization Server via username/password

2. Authorization Server will authenticate the user and will create the JWT token signed by its key and will return in the response.
3. Now, Browser will access the Application Server by JWT token as Authorization bearer <token> in the header.
4. Application Server will verify JWT using secret key (In such scenario, Key must be shared between Authorization Server and Application Server), Decode the String, verify the claims and will return the response.


4. Open Source libraries:

There are already open source libraries available in the market using which you can create and verify the access token. 
Source code for implementation of above library can be downloaded from GITHUB

5. Conclusion:

We went over what JWT are, how they are created and validated, and how they can be used to ensure trust between an application and its users. This is a starting point for understanding the fundamentals of JWT and why they are useful. 

6. References:



Wednesday, May 11, 2011

ClientLogin for Installed Applications for C2DM - Tutorial

Before you can write client applications that use the C2DM feature, you must have an HTTPS application server that meets the following criteria:Able to communicate with your client.
  • Able to fire off HTTP requests to the C2DM server.
  • Able to handle requests and queue data as needed. For example, it should be able to perform exponential back off.
  •  Able to store the ClientLogin Auth token and client registration IDs. The ClientLogin Auth token is included in the header of POST requests that send messages. For more discussion of this topic, see ClientLogin for Installed Applications. The server should store the token and have a policy to refresh it periodically.

The ClientLogin authorization process:
Authorization with ClientLogin involves a sequence of interactions between three entities: the installed application, Google services, and the user. This diagram illustrates the sequence:













  1. When the third-party application needs to access a user's Google service, it retrieves the user's login name and password.
  2. The third-party application then makes a ClientLogin call to Google's Authorization service.
  3. If the Google Authorization service decides additional vetting is necessary, it returns failure response with a CAPTCHA token and challenge, in the form of a URL for a CAPTCHA image. 
  4. If a CAPTCHA challenge is received, the third-party application displays the CAPTCHA image for the user and solicits an answer from the user. 
  5. If requested, the user submits an answer to the CAPTCHA challenge. 
  6. The third-party application makes a new ClientLogin call, this time including the CAPTCHA answer and token (received with the failure response). 
  7. On a successful login attempt (with or without CAPTCHA challenge), the Google Authorization service returns a token to the application. 
  8. The application contacts the Google service with a request for data access, referencing the token received from the Google Authorization service. 
  9. If the Google service recognizes the token, it supplies the requested data access.


How the Application Server Sends Messages

This section describes how the third-party application server sends messages to a 3rd party client application running on a mobile device.
Before the third-party application server can send a message to an application, it must have received a registration ID from it.
To send a message, the application server issues a POST request to https://android.apis.google.com/c2dm/send that includes the following:
FieldDescription
registration_idThe registration ID retrieved from the Android application on the phone. Required.
collapse_keyAn arbitrary string that is used to collapse a group of like messages when the device is offline, so that only the last message gets sent to the client. This is intended to avoid sending too many messages to the phone when it comes back online. Note that since there is no guarantee of the order in which messages get sent, the "last" message may not actually be the last message sent by the application server. Required.
data.<key>
Payload data, expressed as key-value pairs. If present, it will be included in the Intent as application data, with the <key>. There is no limit on the number of key/value pairs, though there is a limit on the total size of the message. Optional.
delay_while_idleIf included, indicates that the message should not be sent immediately if the device is idle. The server will wait for the device to become active, and then only the last message for each collapse_key value will be sent. Optional.
Authorization: GoogleLogin auth=[AUTH_TOKEN]Header with a ClientLogin Auth token. The cookie must be associated with the ac2dm service. Required.


This table lists the possible response codes:
ResponseDescription
200
Includes body containing:
  • id=[ID of sent message]
  • Error=[error code]
    • QuotaExceeded — Too many messages sent by the sender. Retry after a while.
    • DeviceQuotaExceeded — Too many messages sent by the sender to a specific device. Retry after a while.
    • InvalidRegistration — Missing or bad registration_id. Sender should stop sending messages to this device.
    • NotRegistered — The registration_id is no longer valid, for example user has uninstalled the application or turned off notifications. Sender should stop sending messages to this device.
    • MessageTooBig — The payload of the message is too big, see the limitations. Reduce the size of the message.
    • MissingCollapseKey — Collapse key is required. Include collapse key in the request.
503Indicates that the server is temporarily unavailable (i.e., because of timeouts, etc ). Sender must retry later, honoring any Retry-After header included in the response. Application servers must implement exponential back off. Senders that create problems risk being blacklisted.
401Indicates that the ClientLogin AUTH_TOKEN used to validate the sender is invalid


Code:


// Create a new HttpClient and Post Header 
HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost("https://www.google.com/accounts/ClientLogin"); 
// this is for proxy settings 

HttpParams params = httpclient.getParams(); 
params.setParameter("content-type", "application/x-www-form-urlencoded"); 
try { 
           // Add your data 
           List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
           nameValuePairs.add(new BasicNameValuePair("accountType","HOSTED_OR_GOOGLE")); 
           nameValuePairs.add(new BasicNameValuePair("Email","ar*****.pushapp@gmail.com")); 
           nameValuePairs.add(new BasicNameValuePair("Passwd","W******21")); 
           nameValuePairs.add(new BasicNameValuePair("service", "ac2dm")); 
           nameValuePairs.add(new BasicNameValuePair("source",   "arxxus.push.1.1")); 
           httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
    
           // Execute HTTP Post Requestu 
           HttpResponse response = httpclient.execute(httppost); 
          System.out.println(response.getEntity().toString()); 
          BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
          StringBuffer sb = new StringBuffer(""); 
          String line = ""; 
          while ((line = in.readLine()) != null) 
          { 
                    sb.append(line); 
          } 
          in.close(); 
         String result = sb.toString(); 
         String authToken=result.substring(result.indexOf("Auth=")+5); 
         System.out.println("Token="+authToken); 
         System.out.println("REGID"+RegistrationId);
         System.out.println(authToken.trim());

}//try

This code work properly on Apache Tomcat Server but while deploying this code on the Google App Engine you will get the Restricted class issues..So if you are thinking of deploying on Google App Engine Try this...


HttpURLConnection urlConnection;
URL url = new URL("https://www.google.com/accounts/ClientLogin");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
 
StringBuilder content = new StringBuilder();
content.append("Email=").append("ar*******pp@gmail.com");
content.append("&Passwd=").append("W******");
content.append("&service=").append("ac2dm");
content.append("&source=").append( "arxxus.push.1.1");
content.append("&accountType").append("HOSTED_OR_GOOGLE");
   
OutputStream outputStream = urlConnection.getOutputStream();
outputStream.write(content.toString().getBytes("UTF-8"));
outputStream.close();
int responseCode = urlConnection.getResponseCode();
System.out.println(responseCode+"\tSuccess");
StringBuffer resp = new StringBuffer(); 
if (responseCode == HttpURLConnection.HTTP_OK) 
{
   InputStream inputStream = urlConnection.getInputStream();
     BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
     String line; 
     while ((line = rd.readLine()) != null) 
    
     if(line.startsWith("Auth="))
     {
     resp.append(line.substring(5)); 
     }
    
     rd.close(); 
}
String authToken=resp.toString();
System.out.println("AuthTOken"+authToken);


If you like this post..Please do comments..

How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...