Giter Site home page Giter Site logo

twofactor's Introduction

Current test status

Build Status GoDoc

totp

This package implements the RFC 6238 OATH-TOTP algorithm;

Installation

go get github.com/sec51/twofactor

Features

  • Built-in support for secure crypto keys generation

  • Built in encryption of the secret keys when converted to bytes, so that they can be safely transmitted over the network, or stored in a DB

  • Built-in back-off time when a user fails to authenticate more than 3 times

  • Bult-in serialization and deserialization to store the one time token struct in a persistence layer

  • Automatic re-synchronization with the client device

  • Built-in generation of a PNG QR Code for adding easily the secret key on the user device

  • Supports 6, 7, 8 digits tokens

  • Supports HMAC-SHA1, HMAC-SHA256, HMAC-SHA512

Storing Keys

The key is created using Golang crypto random function. It's a secret key and therefore it needs to be protected against unauthorized access. The key cannot be leaked, otherwise the security is completely compromised. The key is presented to the user in a form of QR Code. Once scanned the key should never be revealed again. In addition when the QR code is shared with the client for scanning, the connection used must be secured (HTTPS).

The totp struct can be easily serialized using the ToBytes() function. The bytes can then be stored on a persistent layer (database for example). The bytes are encrypted using cryptoengine library (NaCl) You can then retrieve the object back with the function: TOTPFromBytes

You can transfer the bytes securely via a network connection (Ex. if the database is in a different server) because they are encrypted and authenticated.

The struct needs to be stored in a persistent layer becase its values, like last token verification time, max user authentication failures, etc.. need to be preserved. The secret key needs to be preserved too, between the user accound and the user device. The secret key is in fact used to derive tokens.

Upcoming features

  • Generation of recovery tokens.

  • Integration with Twilio for sending the token via SMS, in case the user loses its entry in the Google authenticator app.

Example Usages

Case 1: Google Authenticator

  • How to use the library

1- Import the library

import github.com/sec51/twofactor

2- Instanciate the totp object via:

	otp, err := twofactor.NewTOTP("[email protected]", "Sec51", crypto.SHA1, 8)	
	if err != nil {
		return err
	}

3- Display the PNG QR code to the user and an input text field, so that he can insert the token generated from his device

	qrBytes, err := otp.QR()
	if err != nil {
		return err
	}

4- Verify the user provided token, coming from the google authenticator app

	err := otp.Validate(USER_PROVIDED_TOKEN)
	if err != nil {
		return err
	}
	// if there is an error, then the authentication failed
	// if it succeeded, then store this information and do not display the QR code ever again.

5- All following authentications should display only a input field with no QR code.

References

Author

totp was written by Sec51 [email protected].

License

Copyright (c) 2015 Sec51.com <[email protected]>

Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above 
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 

twofactor's People

Contributors

cswank avatar silenteh avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

twofactor's Issues

Purpose of the public OTP() function?

Hi
Thanks for a great package.
Please could you explain the purpose of the (*Totp) OTP() function?
I'm struggling to understand what it is for and how it would fit into a 2FA workflow.

Many thanks.

After some time twofactor.TOTPFromBytes is not working

I am using your library. Everything works fine but all of sudden after few days. I am getting this error,

Could not verify the message. Message has been tempered with!

It does work fine for few days but don't know what happens and after few days twofactor.TOTPFromBytes is giving me the error. Can you please help me in identify the issue or how to resolve it?

Thank You!

Keep getting "Tokens mismatch" error

So, yeah. Validate returns Tokens mismatch. I can't seem to understand why ://

package main

import (
	//	"crypto"
	b64 "encoding/base64"
	"fmt"
	"github.com/sec51/twofactor"
)

func main() {
	// otpauth://totp/Cryptoapl:[email protected]?secret=JEAM3MSPDPI5TLWDM4DEE4OCYDRVPSXY&issuer=Cryptoapl:karlis
	issuer := "somesite"
	//	otp, err := twofactor.NewTOTP("[email protected]", issuer, crypto.SHA1, 8)
	//	if err != nil {
	//		fmt.Println(err)
	//		return
	//	}
	//
	//	bytes, err := otp.ToBytes()
	//	if err != nil {
	//		fmt.Println(err)
	//		return
	//	}

	//	bytesToString := string(bytes)
	//	base64EncodedBytes := b64.StdEncoding.EncodeToString([]byte(bytesToString))
	//	fmt.Println(base64EncodedBytes)

	stringOfBytes, _ := b64.StdEncoding.DecodeString("oQAAAAAAAACcALyxTRxmg1YFxKYPcgR4s/e+K/mqlC6M92BekB51Wor/tdD1Q3/pj2RxUmpNzU79P65u2Oefj+lPgHBixKvWEWwLgH22nM/zo9SCf5umOn2txUrsfJPPzQSmG1SO3HFoSFkKvMMR7brDuHn53bDTS1l5+VeoR/QGrugglt8w8jcOOaDHGxahaZM9LmhBBlubT+P7cP5ndUA=")
	stringToBytes := []byte(stringOfBytes)

	otpTwo, err := twofactor.TOTPFromBytes(stringToBytes, issuer)
	if err != nil {
		fmt.Println(err)
		return
	}

	//	fmt.Println(otp.Secret())
	fmt.Println(otpTwo.Secret())

	authCode := "911849"
	err = otpTwo.Validate(authCode)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println("Successful Authorisation!")
	return

}

giles with keys – how to push to prod?!

hello, guys!
I'd like to use your lib for production, but I can't push files with the keys to repositories due to security reasons. Also keys are regenerated every single time once docker is restarted so otps won't match (as mentioned in previous issue).
So for those reasons I can't use your lib in production.
Could you please explain why using this encryption with the keys? Is there any reason I'm missing?
Any plans to modify it? e.g., it's possible to get keys from Vault and keep them in memory.

Token from bytes, why no account?

TOTPFromBytes(encryptedMessage []byte, issuer string)

Why there is no Account (username | email)?

If I store bytes in a database and then I want to retrieve them do I need to store username manually?
Why issuer is only used here?

Supported Authenticators

Looks like Google Authenticator (GA) only support SHA1 URIs even though it says it support 256/512.
I have tested it with a few other authenticators on iPhone:

Not working:

  • Microsoft Authenticator (SHA512)
  • DUO (SHA512)
  • Authy (SHA512)

Working:

  • Lastpass Authenticator (SHA1/256/512+8 Digits)
  • Authenticator (512+8 Digits)
  • Google Authenticator (SHA1)
  • 1Password TOTP (SHA512 & 8 Digits, tested @nugget)

Is there any problem with the Base32 padding or URI encoding that could be preventing other apps from working properly?

I saw this article that GA has a potential problem and recommends using their authenticator for their Sophos firewall. Let me know what you think.

EDIT: Funny how Google helped with the SHA1 Collision Attack and Google Authenticator still only supports SHA1. Is there any problem to that?

OTP Expiration time

Hi, great job with the library, is there any option to increse the expiration time of generated OTP?

Panic and Unit Tests fail on Go 1.11

I use the twofactor package in a daemon, which suddenly started to panic when I rebuilt and ran it using Go version 1.11 - this does not happen with Go 1.10

Running go test on the twofactor package produces the error.
If you run go test --race then the error does not happen.

--- FAIL: TestVerificationFailures (0.00s)
panic: runtime error: slice bounds out of range [recovered]
	panic: runtime error: slice bounds out of range

goroutine 6 [running]:
testing.tRunner.func1(0xc0000b4200)
	/usr/local/go/src/testing/testing.go:792 +0x387
panic(0x550240, 0x682870)
	/usr/local/go/src/runtime/panic.go:513 +0x1b9
github.com/twofactor.TOTPFromBytes(0xc0000ca000, 0x93, 0xf3, 0x5798fd, 0x5, 0x0, 0xc0000b2100, 0x0)
	/home/msonghurst/go/src/github.com/twofactor/totp.go:560 +0xc9f
github.com/twofactor.TestVerificationFailures(0xc0000b4200)
	/home/msonghurst/go/src/github.com/twofactor/totp_test.go:171 +0x45c
testing.tRunner(0xc0000b4200, 0x5835a8)
	/usr/local/go/src/testing/testing.go:827 +0xbf
created by testing.(*T).Run
	/usr/local/go/src/testing/testing.go:878 +0x353
exit status 2
FAIL	github.com/twofactor	0.005s
[msonghurst@deimos twofactor]$ go version
go version go1.11 linux/amd64

Sometimes encountered an issue "Could not verify the message.

On local dev. Everything seems fine but on deployment sometimes I encounter an error in this part of the code.

otp, err := twofactor.TOTPFromBytes(qrBytesDecoded, "Test")
if err != nil {
	fmt.Println(err)
	return u.Message(false, err.Error())
}

Sometimes it pass through or doesn't at all. Any tips on how to locate or fix this kind of issue?

Some questions about the CryptoEngine generated files

Thanks for a great library.

Some internal behaviour of twofactor has caught me out in my distributed infrastructure.
I noticed through a log message that the cryptoengine package used by twofactor writes a bunch of files to disk in a keys subdirectory:

example.com_nonce.key
example.com_salt.key
example.com_private.key
example.com_secret.key
example.com_public.key

After looking at the code I can see environment variable SEC51_KEYPATH can be used to declare the path for these files.
However, I'm using twofactor in a highly scaled daemon, of which I run multiple instances (1 per CPU) on the same host and also run on other separate hosts. Each instance of my daemon needs to successfully encrypt or decrypt the totp struct which is stored centrally in a database.

Please can you confirm which of the cryptoengine files must be identical on all my hosts for totp encryption/decryption to work correctly across my infrastructure?
I plan to pre-generate these files and install them to each of my hosts before my daemon is run. However from reading the cryptoengine source code, I think that some of the files are refreshed over time - please could you confirm which files these are (I think the salt, nonce and secret?), and would it matter if these refreshed files were different for every instance of my daemon?

Many thanks.

Get secret key

I need to communicate with another service so I need to store the secret key on a database. the raw Base32 alphabet one without encryption

I know this is not the best aproach but still.

Is there a way to get the secret key without the encryption layers?

Thanks

Cannot make library write the keys files.

I've been using this library for several years now and with the recent builds I'm seeing a strange change in behavior where it is not writing out any contents to the keys directory under normal operation.

If I have a populated keys directory the saved keypair, secret, and salt are loaded as I'd expect.

If I launch my application with no saved keys, the keys directory is created, but no files are placed inside.

What behavior triggers the key files to be written? I thought it was supposed to happen when I called NewTOTP() but that doesn't seem to be the case. I could swear that's how it used to behave, though.

Is this a bug or am I doing something wrong?

No License In Project

Hi Sec51 team,

Would it be possible to add a license to this project? We are currently going through some due diligence and this project has been flagged as not having a license associated with it.

Many Thanks,

Ant

Directory traversal using "/" in issuer of NewTOTP()

Hallo,

if the issuer argument of the NewTOTP() function contains a "/", the keys will be moved to a different directory and it will fail to create the subdirectories. I think this is not, what we want.

Mebus

Do I need to scan a QR every time?

Excuse my dumb question, I've managed to implement a very basic authentication program in which I generate a QR code, which I scan with Google Authenticator and verify the code correctly. My question is, once I've scanned the QR code once and I have added my new go application to my 2FA app, do I need to regenerate, scan the QR code and re-add it to my 2FA app? How can I just ask the user to enter the new code generated by his/her 2FA app and check it?

Thanks for your help!

Keep getting "Tokens mismatch" error

Hi There,

I am trying to figure it out how to use this library. I have used ToBytes() function to serialize the totp struct and stored it in Redis database (and restore it by calling the twofactor.TOTPFromBytes() function). However, I keep getting the "Tokens mismatch" error when trying to verify the user provided token. I have verified the values of the byte array are exactly the same before storing into Redis and after retrieving from Redis.

Can someone help to review my code and let me know what I was doing wrong?

package main

import (
        "crypto"
        "fmt"
        "github.com/sec51/twofactor"
        "gopkg.in/redis.v3"
        "log"
        "net/http"
        "strconv"
)

var redisClient = redis.NewClient(&redis.Options{
        Addr:     "localhost:6379",
        Password: "", // no password set
        DB:       0,  // use default DB
})

func handler(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Home: %s!", r.URL.Path[1:])
}

func writeImage(w http.ResponseWriter, r *http.Request) {
        otp, err := twofactor.NewTOTP("[email protected]", "Sec51", crypto.SHA1, 6)

        if err != nil {
                log.Println("call NewTOTP error.")
        }

        qrBytes, err := otp.QR()

        if err != nil {
                log.Println("call QR error.")
        }

        if b, err := otp.ToBytes(); err != nil {
                log.Println("call ToBytes error.")
        } else {
                log.Printf("Before: %v\n", b) // show the byte array before storing in Redis

                if err := redisClient.Set("[email protected]", b, 0).Err(); err != nil {
                        log.Printf("H: %v\n\n", err)
                }
        }

        w.Header().Set("Content-Type", "image/png")
        w.Header().Set("Content-Length", strconv.Itoa(len(qrBytes)))

        if _, err := w.Write(qrBytes); err != nil {
                log.Println("unable to write image.")
        }
}

func verifyIt(w http.ResponseWriter, r *http.Request) {
        val, err := redisClient.Get("[email protected]").Bytes()

        log.Printf("Afterr: %v\n", val) // show the byte array after getting it from Redis

        otp, err := twofactor.TOTPFromBytes(val, "Sec51")

        if err != nil {
                log.Println("call TOTPFromBytes error.")
        }

        if err := otp.Validate(r.URL.Path[3:]); err != nil {
                fmt.Fprintf(w, "Wrong code: %s. Err: %v\n", r.URL.Path[3:], err)
        } else {
                fmt.Fprintf(w, "Good Job: %s.\n", r.URL.Path[3:])
        }
}

func main() {

        http.HandleFunc("/v/", verifyIt)
        http.HandleFunc("/qr/", writeImage)
        http.HandleFunc("/", handler)

        http.ListenAndServe(":80", nil)
}

undefined: crypto

while instantiating the TOTP object via:
otp, err := twofactor.NewTOTP("[email protected]", "Sec51", crypto.SHA1, 8)
if err != nil {
fmt.Println(err)
}

i got this error:
.\main.go:8:60: undefined: crypto

this is my go file:

package main

import "fmt"
import "github.com/sec51/twofactor"

func main(){
fmt.Println("ds")
otp, err := twofactor.NewTOTP("[email protected]", "Sec51", crypto.SHA1, 8)
if err != nil {
fmt.Println(err)
}

qrBytes, err := otp.QR()
if err != nil {
fmt.Println(err)
}

}

I am newbee to golang and authentication process so may be i am missing any dependency here.
Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.