Take the 2-minute tour ×
Information Security Stack Exchange is a question and answer site for Information security professionals. It's 100% free, no registration required.

Google Authenticator is an alternative to SMS for 2Step verification, installing an app on Android where the codes will be sent.

It works without any connectivity; it even works on plane mode. This is what I don't get. How is it possible that it works without connectivity? How do the mobile phone and the server sync to know which code is valid at that very moment?

share|improve this question
4  
The codes are not "sent". They are made via a seed and counter. –  Steel City Hacker May 1 '13 at 19:28

3 Answers 3

up vote 58 down vote accepted

Google Authenticator supports both the HOTP and TOTP algorithms for generating one-time passwords.

With HOTP, the server and client share a secret value and a counter, which are used to compute a one time password independently on both sides. Whenever a password is generated and used, the counter is incremented on both sides, allowing the server and client to remain in sync.

TOTP essentially uses the same algorithm as HOTP with one major difference. The counter used in TOTP is replaced by the current time. The client and server remain in sync as long as the system times remain the same. This can be done by using the Network Time protocol.

The secret key (as well as the counter in the case of HOTP) has to be communicated to both the server and the client at some point in time. In the case of Google Authenticator, this is done in the form of a QRCode encoded URI. See: KeyUriFormat for more information.

share|improve this answer
3  
In the case of HOTP, how does Google Authenticator know that I have "used" the password without syncing with the server? What Google Authenticator does is that it continues to flash different keys and I can just use any one them without giving feedback to my mobile. –  Mario Awad May 7 '13 at 8:21
    
@MarioAwad The answer to that can be found on the HOTP RFC, section 7.4. ietf.org/rfc/rfc4226.txt –  Terry Chia May 7 '13 at 8:24
1  
Thank you for the well defined answer and followup. Quick summary of section 7.4: Resynchronization of the Counter every now and then and a look-ahead window for the counter is what makes things work without requiring instant-sync. –  Mario Awad May 7 '13 at 11:03

It'll work on a seed based on time so it's similar to the way the RSA key fobs work. i.e. they also don't require any connectivity.

I've just had a look around and this is answered here: http://stackoverflow.com/questions/8340495/how-rsa-tokens-works

share|improve this answer

HOTP & TOTP algorithms have now become open standards in IT. That means, you can use Google Authenticator not only for Google, but also Facebook, Yahoo, Microsoft websites, or even your own website.

All you have to do is to just use the following code in the server's main base:

import os

import bcrypt
from twilio.rest import TwilioRestClient
from flask.ext.login import LoginManager
from flask import Flask
from flask import request
from flask import redirect
from flask import url_for
from flask import render_template
from flask.ext.login import login_user
from flask.ext.login import logout_user
from flask.ext.login import current_user
from flask.ext.login import login_required
from pymongo import Connection

from konfig import Konfig

app = Flask(__name__)
konf = Konfig()
app.secret_key = konf.secret_key

connection = Connection(konf.mongo_url)

login_manager = LoginManager()
login_manager.setup_app(app)

twilio = TwilioRestClient()

@login_manager.user_loader
def load_user(user_id):
    return User(user_id)

class User:
    def __init__(self, user_id):
        self.id = user_id.lower()
        self.db = connection.tfa.users
        self.account = self.db.find_one({'uid': self.id})

    def create(self):
        self.db.insert({'uid': self.id})
        self.account = self.db.find_one({'uid': self.id})

    def save(self):
        self.db.save(self.account)

    def password_valid(self, pwd):
        pwd_hash = self.account['password_hash']
        return bcrypt.hashpw(pwd, pwd_hash) == pwd_hash

    # The methods below are required by flask-login
    def is_authenticated(self):
        """Always return true - we don't do any account verification"""
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return self.id

@app.route("/", methods=['GET', 'POST'])
def main_page():
    opts = {}
    if request.method == 'GET':
        return render_template('main_page.html', opts=opts)
    user = User(request.form['username'])
    if not user.account or not user.password_valid(request.form['password']):
        opts['invalid_username_or_password'] = True
        return render_template('main_page.html', opts=opts)
    login_user(user)
    return redirect(url_for('user'))

@app.route("/sign-up", methods=['GET', 'POST'])
def sign_up():
    opts = {}
    if request.method == 'GET':
        return render_template('sign_up.html', opts=opts)
    user = User(request.form['username'])
    if user.account:
        opts['username_exists'] = True
        return render_template('sign_up.html', opts=opts)
    if request.form['password1'] != request.form['password2']:
        opts['passwords_do_not_match'] = True
        return render_template('sign_up.html', opts=opts)
    user.create()
    pwd_hash = bcrypt.hashpw(request.form['password1'], bcrypt.gensalt())
    user.account['password_hash'] = pwd_hash
    user.save()
    login_user(user)
    return redirect(url_for('user'))

@app.route("/user")
@login_required
def user():
    opts = {'user': current_user,
            'logged_in': True}
    return render_template('user.html', opts=opts)

@app.route("/logout")
def logout():
    logout_user()
    return redirect(url_for('main_page'))

if __name__ == "__main__":
    # Bind to PORT if defined, otherwise default to 5000.
    port = int(os.environ.get('PORT', 5000))
    if port == 5000:
        app.debug = True
    app.run(host='0.0.0.0', port=port)

Courtesy: Kyle Kelly-Yahner

share|improve this answer
    
I think the question was more generic about how the Authenticator works, not how to implement in code. –  Andrew Lott Jul 24 '13 at 8:43
2  
Hello Andrew :) With respect to your comment on the relevancy: The generic question has already been answered above by Terry Chia. My comment is for developers. (Because hardly any expert knows that you can use Google Authenticator for third party API/Apps/Web Apps/Website as well) –  Gaurav Jha Jul 24 '13 at 17:46
2  
How is the code relevant? I can't see any logic beyond simple single-factor password authentication. –  pluma Oct 9 '13 at 21:31

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.