Ejemplo n.º 1
0
def ologin():
    if request.method == 'GET':
        if 'otpusername' not in session and 'username'in session :
            if User.otpchk(str(session['username'])) == "0":
                print("hellop")
                import pyotp
                key = pyotp.random_base32()
                totp = pyotp.TOTP(key)
                optsct = totp.provisioning_uri(session['username'])
                User.optnew(str(session['username']),optsct,key)
                return render_template('admin/otpset.html',otpurl=str(User.otpchk(str(session['username']))))
            else:
                return render_template('admin/otplogin.html',name=str(session['username']))
        else:
            return redirect(url_for('admin.index'))

    else:
        if 'username' in session:
            import pyotp
            passd = request.form['otppass']
            otpkey = User.otpkeychk(str(session['username']))
            totp = pyotp.TOTP(otpkey)
            if totp.verify(passd) is True:
                session['otpusername'] = str(session['username'])+str(passd)
                return redirect(url_for('admin.index'))
            else:
                return redirect(url_for('login.ologin'))
Ejemplo n.º 2
0
def adduser(request):
    """ Method to insert new username, generate secret"""
    messages = None
    session = request.getSession()
    user = IUser(session)
    if not user.is_admin:
        request.setResponseCode(403)
        returnValue('Permission Denied')
    if request.method == 'POST':
        username = request.args.get("username", None)[0]
        if username is not None:
            # Generate Secret
            secret = pyotp.random_base32()
            # Insert user into db
            try:
                yield dbpool.runOperation('INSERT into users (username, secret) values (?, ?);', (username, secret))
                # generate QRCODE
                totp = pyotp.TOTP(secret)
                img = qrcode.make(totp.provisioning_uri("Unlab:{}".format(username)))
                page = webapp.templates.get_template('show_qrcode.html')
                returnValue(page.render(username=username, img=make_datauri(img)))
            except sqlite3.IntegrityError, e:
                messages = "User {} already exists".format(username)
        else:
            messages = "Failed to create user"
Ejemplo n.º 3
0
    def create(cls, email, key, password):
        u = cls(email=email, key=key, password=password)

        if u.key is None:
            u.key = pyotp.random_base32()

        return u
Ejemplo n.º 4
0
def test_activate():
    user_id = db_utils.create_user()
    tfa_secret = pyotp.random_base32()
    totp = pyotp.TOTP(tfa_secret)

    # Failed validation between tfa_secret/tfa_response
    assert not tfa.activate(user_id, tfa_secret, "000000")
    # Verify 2FA is not active
    assert not d.engine.scalar("""
        SELECT twofa_secret
        FROM login
        WHERE userid = %(userid)s
    """, userid=user_id)

    # Validation successful, and tfa_secret written into user's `login` record
    tfa_response = totp.now()
    assert tfa.activate(user_id, tfa_secret, tfa_response)
    # The stored twofa_secret must not be plaintext
    stored_secret = d.engine.scalar("""
        SELECT twofa_secret
        FROM login
        WHERE userid = %(userid)s
    """, userid=user_id)
    assert tfa_secret != stored_secret
    # The stored secret must be decryptable to the generated tfa_secret
    assert tfa_secret == tfa._decrypt_totp_secret(stored_secret)
Ejemplo n.º 5
0
def register(request):
	if request.method == 'POST':
		form = RegisterForm(request.POST)

		if form.is_valid():
			username = form.cleaned_data['username']
			password = form.cleaned_data['password']

			seed = pyotp.TOTP(pyotp.random_base32())
			# The parameter below is used as the label for the auth app interface.
			uri = seed.provisioning_uri(username)
			secret = urlparse.parse_qs(urlparse.urlparse(uri).query)['secret'][0]

			# This can fail if username is not unique. TODO: wrap in try
			newUser = User(username=username, password=password, tfaEnabled=True, tfaSecret=secret)
			newUser.save()

			request.session['username'] = username
			request.session['password'] = password
			request.session['tfaUri'] = uri

			return redirect(reverse('tfaSetup'))
		else:
			return render(request, 'tfa/register.html', {'form': RegisterForm()})
	else:
		return render(request, 'tfa/register.html', {'form': RegisterForm()})
Ejemplo n.º 6
0
def register_device(request):
    if request.method == 'POST':
        secret_key = request.POST['secret_key']
        otp = request.POST['otp']
        totp = pyotp.TOTP(secret_key)
        
        if totp.verify(otp) is False:
            logout(request)
            return HttpResponseRedirect('/login')
        
        otpuser = OtpUser.objects.get(user__username=request.user.username)
        otpuser.secret_key = secret_key
        otpuser.save()
        logout(request)
        return HttpResponseRedirect('/login')

    secret_key = pyotp.random_base32()
    username = request.user.username
    key_uri = 'otpauth://totp/appname:'+username+'?secret='+secret_key+'&issuer=appname'
    qr = pyqrcode.create(key_uri)
    qr_name = secret_key+'.svg'
    qr_file = os.path.join(BASE_DIR, 'static')+'/'+qr_name
    qr.svg(qr_file)

    return render_to_response('register_device.html', {'qr_file':qr_name, 'secret_key': secret_key}, context_instance=RequestContext(request))
    def generate_token(self, ip, duration):
        """
        takes an ip to generate an AccessToken for and a duration that the
        remote device will be granted control of the ip once the token is used
        """
        totp_dict = self._ip_to_totp_map.get(ip)
        if totp_dict is None:
            # Timeout changed to 60 seconds from the default 30 as it may take
            # more than 30 sec to get the code, go to other client and enter it
            totp = AtcdTOTP(
                interval=self.ACCESS_TOKEN_INTERVAL,
                s=pyotp.random_base32()
            )
            self._ip_to_totp_map[ip] = {
                'totp': totp,
                'duration': duration
            }
        else:
            totp = totp_dict.get('totp')
            if duration != totp_dict.get('duration'):
                totp_dict['duration'] = duration
                self._ip_to_totp_map[ip] = totp_dict

        timestamp = datetime.datetime.now()

        return AccessToken(
            token=totp.at(timestamp),
            interval=self.ACCESS_TOKEN_INTERVAL,
            # valid_until returns time as a datetime.datetime object
            # this converts it to a float time
            valid_until=time.mktime(totp.valid_until(timestamp).timetuple())
        )
Ejemplo n.º 8
0
def otp_validate():
    print request.json
    if request.json.get('mobile') is None or request.json.get('otp') is None :
        abort(400)
    else:
        user_id = request.json.get('mobile')
        otp = request.json.get('otp')
        try:
            act_rec = Account.query.filter_by(user_id=user_id).first()
            if act_rec and act_rec.otp == otp:
                time_difference = datetime.strptime(ctime(), "%a %b %d %H:%M:%S %Y") - act_rec.last_updated_on
                if time_difference.seconds > 600:
                    return make_response(jsonify({'result': 'otp expired'}), 502)
                access_token = pyotp.random_base32()
                act_rec.access_token = access_token
                act_rec.last_updated_on = ctime()
                session_commit()
                #map_products(user_id, request.json.get('products'))
                products = Product.query.all()
                res= {'products' : [product.as_dict() for product in products], 'access_token': access_token}
                return make_response(jsonify(res), 200)
            else:
                return make_response(jsonify({'result': 'invalid otp'}), 501)
        except Exception, e:
            logging.error(str(e))
            abort(404)
Ejemplo n.º 9
0
def new_google_authentication():
    new_token = pyotp.random_base32()
    g.settings.secret_key = new_token
    db.session.commit()
    totp = pyotp.TOTP(g.settings.secret_key)
    uri = totp.provisioning_uri("admin")
    return uri
Ejemplo n.º 10
0
def startup():

    # db initializations
    db.create_all()
    settings = Settings(secret_key=pyotp.random_base32())
    db.session.add(settings)
    db.session.commit()
Ejemplo n.º 11
0
    def test_2fa_invalid_totp(self):
        mary = User.query.filter(User.uid == "urn:mary").first()
        mary.second_factor_auth = pyotp.random_base32()
        db.session.merge(mary)
        db.session.commit()

        self.login("urn:mary")
        self.post("/api/mfa/verify2fa", {"totp": "123456"}, with_basic_auth=False, response_status_code=400)
def addotp(user):
    unverifiedkey = "unverified_{}".format(user.username)
    otphash = r.get(unverifiedkey)
    if not otphash:
        otphash = pyotp.random_base32()
        r.set(unverifiedkey, otphash)
    totp = pyotp.TOTP(otphash)
    return totp.provisioning_uri(user.username, COOKIE_DOMAIN)
Ejemplo n.º 13
0
 def init_2fa_totp(self):
     if self._data.get('mfa_enabled'):
         return None
     self._data['_2fa_totp'] = pyotp.random_base32()
     self._set_modified(True)
     self.save()
     totp = pyotp.TOTP(self._data['_2fa_totp'])
     return totp.provisioning_uri(self.email, 'EPManage')
Ejemplo n.º 14
0
    def revoke(self):
        """
        Revoke secret MFA for this user.

        This method generate a new secret_key for this user.
        """
        self.secret_key = pyotp.random_base32()
        self.save()
Ejemplo n.º 15
0
    def _add_ota_secret(self, user_id: str, secret: Optional[str] = None) -> str:
        """Create a ota_secret for user."""
        import pyotp

        ota_secret: str = secret or pyotp.random_base32()

        self._users[user_id] = ota_secret  # type: ignore
        return ota_secret
Ejemplo n.º 16
0
 def reset_mfa(self, length=16):
     """
     Sets the user's `mfa_secret` value to a random value and marks the user
     as not having setup two-factor authentication.
     :return: None
     """
     self.mfa_secret = pyotp.random_base32(length)
     self.mfa_enabled = False
Ejemplo n.º 17
0
    def _add_ota_secret(self, user_id: str, secret: str | None = None) -> str:
        """Create a ota_secret for user."""
        import pyotp  # pylint: disable=import-outside-toplevel

        ota_secret: str = secret or pyotp.random_base32()

        self._users[user_id] = ota_secret  # type: ignore
        return ota_secret
Ejemplo n.º 18
0
    def generate_otp(self):
        if self.otp_enabled:
            raise ValueError('otp already set')

        self.otp_seed = pyotp.random_base32()
        db.session.commit()
        return pyotp.totp.TOTP(self.otp_seed).provisioning_uri(
            self.username, issuer_name="SARNA")
Ejemplo n.º 19
0
def new_password(algo):
    "Generate a password."
    if algo == ALGO_TOTP:
        # Generate a proper/compatible password for most TOTP apps
        return pyotp.random_base32().encode()
    # Stick to printable characters.
    return ''.join(chr(random.randint(33, 126))
                   for _ in range(PASSWORD_LEN)).encode()
Ejemplo n.º 20
0
def generate_key():
    global totp
    otp = pyotp.random_base32()
    totp = pyotp.TOTP(otp, interval=300)
    password = totp.now()

    if is_unique(otp):
        return password
Ejemplo n.º 21
0
def addotp(username):
    if username in unverifiedotp:
        otphash = unverifiedotp[username]
    else:
        otphash = pyotp.random_base32()
        unverifiedotp[username] = otphash
    totp = pyotp.TOTP(otphash)
    return totp.provisioning_uri(username, COOKIE_DOMAIN)
Ejemplo n.º 22
0
def generate(id):
    #128 bit is 8 HEX and 4 base32
    with open("users.txt", "a") as f:
        f.write(str("\n" + id))
    key = pyotp.random_base32(length=8)
    print("GENERATED KEY", key, "FOR USER", id)
    with open(id, "w") as f:
        f.write(key)
Ejemplo n.º 23
0
def generateOTP():
    global totp
    secret = pyotp.random_base32()
    totp = pyotp.TOTP(
        secret, interval=300
    )  #set interval(time of the otp expiration) according to your need in seconds.
    one_time = totp.now()
    return one_time
Ejemplo n.º 24
0
 def get(self, request, *args, **kwargs):
     profile = self.profile
     if profile.is_contest_account:
         raise Http404()
     if not profile.totp_key:
         profile.totp_key = pyotp.random_base32(length=32)
         profile.save()
     return self.render_to_response(self.get_context_data())
Ejemplo n.º 25
0
    def get(self, request):
        meth = "GET"
        auth_key = pyotp.random_base32()
        QR = f'https://chart.googleapis.com/chart?chs=200x200&chld=M|0&cht=qr&chl= \
            {pyotp.totp.TOTP(auth_key).provisioning_uri(self.request.user.username, issuer_name="CyberRage")}'

        context = {"meth": meth, "KEY": auth_key, "QR": QR}
        return render(request, "accounts/mfa.html", context)
Ejemplo n.º 26
0
 def get(self, request, *args, **kwargs):
     profile = self.profile
     if not profile.totp_key:
         profile.totp_key = pyotp.random_base32(length=32)
         profile.save(update_fields=['totp_key'])
     if not profile.scratch_codes:
         profile.generate_scratch_codes()
     return self.render_to_response(self.get_context_data())
Ejemplo n.º 27
0
    def create(self, country_code: str, phone_number: int):
        secret = self._create_secret(secret=pyotp.random_base32(length=32))
        counter = self._create_counter()

        hotp = pyotp.HOTP(secret, digits=self._digits)
        self._send_sms(sms_code=hotp.at(counter),
                       country_code=country_code,
                       phone_number=phone_number)
Ejemplo n.º 28
0
 def get(self):
     key = pyotp.random_base32()
     return ApiResponse({
         "key":
         key,
         "url":
         pyotp.TOTP(key).provisioning_uri(request.host, Config.OTP_NAME)
     })
Ejemplo n.º 29
0
    def create_key(self):
        """Enter the key generated into your 2fa authenticator app,
        to start generating keys"""

        key = pyotp.random_base32()
        with open("2fa.txt", "w+") as f:
            f.write(key)
        print("Key created!")
Ejemplo n.º 30
0
def run():
    config = configparser.ConfigParser()
    config.read('/data/config.ini')
    if not config.has_option('totp', 'code'):
        eprint("No TOTP code found. Generating one.")
        if not config.has_section('totp'):
            config.add_section('totp')
        config['totp']['code'] = pyotp.random_base32()
        write_config(config)
    if not config.has_section('reverse_proxy'):
        config.add_section('reverse_proxy')
        config['reverse_proxy']['domain_name'] = ""
        config['reverse_proxy']['backend'] = ""
        config['reverse_proxy']['allowed_ips'] = "127.0.0.1"
        write_config(config)
        eprint("Configuration missing! Please edit /data/config.ini.")
        exit(2)
    if len(sys.argv) > 1 and sys.argv[1] == "provisioning-uri":
        totp = pyotp.TOTP(config['totp']['code'])
        print(totp.provisioning_uri("Main", issuer_name="TOTP ACL"))
        exit(0)
    elif len(sys.argv) > 1 and sys.argv[1] == "config-setup":
        create_config(config['reverse_proxy'], restart=False)
        exit(0)
    elif len(sys.argv) > 1 and sys.argv[1] == "get-code":
        totp = pyotp.TOTP(config['totp']['code'])
        print("TOTP code:", totp.now())
        exit(0)
    elif len(sys.argv) > 1:
        print("Supported commands:")
        print("provisioning-uri, config-setup, get-code")
        exit(1)
    if os.environ['REQUEST_METHOD'] == 'POST':
        print("Content-Type: text/html\n")
        post_data = sys.stdin.read()
        totp = pyotp.TOTP(config['totp']['code'])
        if check_code(totp, post_data):
            # Break string up in IPs and add current IP.
            new_ips = config['reverse_proxy']['allowed_ips'].split(',')
            ip = os.environ['REMOTE_ADDR']
            new_ips.append(ip)
            config['reverse_proxy']['allowed_ips'] = ','.join(new_ips)
            write_config(config)
            print("""<!DOCTYTPE html>
            <html><head><!--<meta HTTP-EQUIV="refresh" CONTENT="10;url=/">--!></head>
            <body>Your IP {} has been allowed.
            <script>setTimeout(function(){{window.open("/","_self");}}, 5000);</script>
            </body></html>""".format(ip))
            eprint("IP address added as allowed:", ip)
            create_config(config['reverse_proxy'])
        else:
            show_login()
    elif os.environ['REQUEST_METHOD'] == 'GET':
        print("Content-Type: text/html\n")
        show_login()
    else:
        eprint("Invalid request method")
        exit(1)
Ejemplo n.º 31
0
def confirm(action=None):
    if flask.ext.security.current_user.has_role('admin'):
        return flask.redirect(flask.url_for('admin.index'))
    if not flask.ext.security.current_user.is_anonymous():
        return flask.redirect(flask.url_for('manage.actions'))
    if not (flask.session.get('email') or flask.session.get('phone')):
        return flask.redirect(flask.url_for('.step_one'))
    if not flask.session.get('actions'):
        return flask.redirect(flask.url_for('.step_two'))
    phone = utils.format_phone(flask.session)
    if action == 'submit':
        user = None
        query = models.User.query
        email = flask.session.get('email', '')
        if phone:
            user = query.filter_by(phone=phone)
            user = user.first()
        if email and not user:
            user = query.filter_by(email=email).first()
        if not user:
            user = models.User()
        user.phone = phone
        user.email = email
        for action_id in flask.session['actions']:
            action = models.Action.query.get(action_id)
            user.actions.append(action)
        name = flask.session.get('method_name')
        if name:
            method = models.Method.query.filter_by(name=name).first()
            user.method = method
        utils.add_schedule(user, flask.session)
        user.secret = pyotp.random_base32()
        models.db.session.add(user)
        models.db.session.commit()
        redirect = 'index'
        if user.email and user.email_confirmed_at is None:
            confirmable = flask.ext.security.confirmable
            token = confirmable.generate_confirmation_token(user)
            link = flask.url_for('.confirm_signup', token=token,
                                 _external=True)
            msg = flask.ext.security.utils.get_message('CONFIRM_REGISTRATION',
                                                       email=user.email)
            flask.flash(*msg)
            subject = 'Thank You for Signing Up for Love Touches!'
            flask.ext.security.utils.send_mail(subject, user.email,
                                               'signup', user=user,
                                               confirmation_link=link)
            redirect = 'index'
        if user.phone and user.phone_confirmed_at is None:
            utils.send_code(user)
            flask.session['_user_id'] = user.id
            redirect = 'confirm_mobile'
        for key in (x for x in flask.session.keys() if not x.startswith('_')):
            del flask.session[key]
        return flask.redirect(flask.url_for(redirect))
    actions = [models.Action.query.get(x) for x in flask.session['actions']]
    return flask.render_template('confirm.html', actions=actions, phone=phone,
                                 days_label=_days_label())
Ejemplo n.º 32
0
def confirm(action=None):
    if flask_security.current_user.has_role("admin"):
        return flask.redirect(flask.url_for("admin.index"))
    if not flask_security.current_user.is_anonymous:
        return flask.redirect(flask.url_for("manage.actions"))
    if not (flask.session.get("email") or flask.session.get("phone")):
        return flask.redirect(flask.url_for(".step_one"))
    if not flask.session.get("actions"):
        return flask.redirect(flask.url_for(".step_two"))
    phone = utils.format_phone(flask.session)
    if action == "submit":
        user = None
        query = models.User.query
        email = flask.session.get("email", "")
        if phone:
            user = query.filter_by(phone=phone)
            user = user.first()
        if email and not user:
            user = query.filter_by(email=email).first()
        if not user:
            user = models.User()
        user.phone = phone
        user.email = email
        for action_id in flask.session["actions"]:
            action = models.Action.query.get(action_id)
            user.actions.append(action)
        name = flask.session.get("method_name")
        if name:
            method = models.Method.query.filter_by(name=name).first()
            user.method = method
        utils.add_schedule(user, flask.session)
        user.secret = pyotp.random_base32()
        models.db.session.add(user)
        models.db.session.commit()
        redirect = "index"
        if user.email and user.email_confirmed_at is None:
            token = flask_security.confirmable.generate_confirmation_token(user)
            link = flask.url_for(".confirm_signup", token=token, _external=True)
            msg = flask_security.utils.get_message(
                "CONFIRM_REGISTRATION", email=user.email
            )
            flask.flash(*msg)
            subject = "Thank You for Signing Up for Love Touches!"
            flask_security.utils.send_mail(
                subject, user.email, "signup", user=user, confirmation_link=link
            )
            redirect = "index"
        if user.phone and user.phone_confirmed_at is None:
            utils.send_code(user)
            flask.session["_user_id"] = user.id
            redirect = "confirm_mobile"
        for key in (x for x in list(flask.session.keys()) if not x.startswith("_")):
            del flask.session[key]
        return flask.redirect(flask.url_for(redirect))
    actions = [models.Action.query.get(x) for x in flask.session["actions"]]
    return flask.render_template(
        "confirm.html", actions=actions, phone=phone, days_label=_days_label()
    )
Ejemplo n.º 33
0
    def get_initial(self):
        initial = super().get_initial()

        initial['secret'] = pyotp.random_base32(length=32)
        initial['link'] = pyotp.TOTP(initial['secret']).provisioning_uri(
            self.request.user.email, settings.MFA_APPLICATION_NAME,
        )

        return initial
Ejemplo n.º 34
0
 def get(self, request):
     base_32 = pyotp.random_base32()
     otp_path = pyotp.totp.TOTP(base_32).provisioning_uri(
         request.user.email, issuer_name="El bot es mio")
     return Response({
         'qr_code': otp_path,
         'base_32': base_32
     },
                     status=status.HTTP_200_OK)
Ejemplo n.º 35
0
def create_secret():
    """
    Creates new random secret.

    :returns: Random secret
    :rtype: str
    """

    return pyotp.random_base32(length=api_settings.SECRET_KEY_LENGTH)
Ejemplo n.º 36
0
 def __init__(self, username, password=None, name=None, totp_key=None, groups=()):
     if name is None:
         name = username
     if password is None:
         password = passgen.passgen()
     if totp_key is None:
         totp_key = pyotp.random_base32()
     super(User, self).__init__(username=username, password=password,
             name=name, totp_key=totp_key, groups=groups)
Ejemplo n.º 37
0
Archivo: otp.py Proyecto: node13h/droll
def generate_secret():
    """
    Generate random OTP secret

    :rtype: str
    :returns: 16-character string
    """

    return pyotp.random_base32()
Ejemplo n.º 38
0
    def _add_ota_secret(self, user_id: str,
                        secret: Optional[str] = None) -> str:
        """Create a ota_secret for user."""
        import pyotp

        ota_secret = secret or pyotp.random_base32()  # type: str

        self._users[user_id] = ota_secret   # type: ignore
        return ota_secret
Ejemplo n.º 39
0
def create_secret():
    """
    Creates new random secret.

    :returns: Random secret
    :rtype: str
    """

    return pyotp.random_base32(length=20)
Ejemplo n.º 40
0
def _generate_secret_and_qr_code(username: str) -> Tuple[str, str, str]:
    """Generate a secret, url, and QR code."""
    import pyotp

    ota_secret = pyotp.random_base32()
    url = pyotp.totp.TOTP(ota_secret).provisioning_uri(
        username, issuer_name="Home Assistant")
    image = _generate_qr_code(url)
    return ota_secret, url, image
def gerarBase32():
    print('[AUTHENTICATOR]Gerando base32 aléatoria...')
    try:
        base32 = pyotp.random_base32()
        print('[AUTHENTICATOR]Base32 gerada com sucesso!')
        return base32
    except Exception as e:
        print('[AUTHENTICATOR]Não foi possivel gerar a base32...')
        print('[AUTHENTICATOR]:',e)
Ejemplo n.º 42
0
def generate(id):
    psecret = pyotp.random_base32()
    file_path = open('totpauth/' + str(id) + '.txt', 'a')
    file_path.write(psecret)
    #os.system('echo ' + psecret + '>totpauth/' + str(id) + '.txt')
    print('Scan the QR or input this code manually: ' + psecret)
    qrcode_terminal.draw(
        pyotp.totp.TOTP(psecret).provisioning_uri(str(id) + "@example",
                                                  issuer_name="Lock"))
Ejemplo n.º 43
0
def _generate_secret_and_qr_code(username: str) -> Tuple[str, str, str]:
    """Generate a secret, url, and QR code."""
    import pyotp

    ota_secret = pyotp.random_base32()
    url = pyotp.totp.TOTP(ota_secret).provisioning_uri(
        username, issuer_name="Home Assistant")
    image = _generate_qr_code(url)
    return ota_secret, url, image
Ejemplo n.º 44
0
 def generate(user):
     BackupCode.objects.filter(user=user).delete()
     codes = [
         BackupCode(user=user, code=pyotp.random_base32(8))
         for i in range(10)
     ]
     BackupCode.objects.bulk_create(codes)
     return BackupCode.objects.filter(user=user).values_list('code',
                                                             flat=True)
Ejemplo n.º 45
0
def _generate_secret_and_qr_code(username: str) -> tuple[str, str, str]:
    """Generate a secret, url, and QR code."""
    import pyotp  # pylint: disable=import-outside-toplevel

    ota_secret = pyotp.random_base32()
    url = pyotp.totp.TOTP(ota_secret).provisioning_uri(
        username, issuer_name="AI-Speaker")
    image = _generate_qr_code(url)
    return ota_secret, url, image
Ejemplo n.º 46
0
Archivo: main.py Proyecto: peuter/gosa
    def __enable_otp(self, user):
        if user.uuid not in self.__settings:
            self.__settings[user.uuid] = {}

        user_settings = self.__settings[user.uuid]
        secret = random_base32()
        totp = TOTP(secret)
        user_settings['otp_secret'] = secret
        self.__save_settings()
        return totp.provisioning_uri("%s@%s.gosa" % (user.uid, self.env.domain))
Ejemplo n.º 47
0
def main():
	parser = argparse.ArgumentParser(description='King Phisher TOTP Enrollment Utility', conflict_handler='resolve')
	utilities.argp_add_args(parser)
	config_group = parser.add_mutually_exclusive_group(required=True)
	config_group.add_argument('-c', '--config', dest='server_config', type=argparse.FileType('r'), help='the server configuration file')
	config_group.add_argument('-u', '--url', dest='database_url', help='the database connection url')
	parser.add_argument('--otp', dest='otp_secret', help='a specific otp secret')
	parser.add_argument('user', help='the user to mange')
	parser.add_argument('action', choices=('remove', 'set', 'show'), help='the action to preform')
	parser.epilog = PARSER_EPILOG
	arguments = parser.parse_args()

	utilities.configure_stream_logger(arguments.loglvl, arguments.logger)

	if arguments.database_url:
		database_connection_url = arguments.database_url
	elif arguments.server_config:
		server_config = yaml.load(arguments.server_config)
		database_connection_url = server_config['server']['database']
	else:
		raise RuntimeError('no database connection was specified')

	manager.init_database(database_connection_url)
	session = manager.Session()
	user = session.query(models.User).filter_by(id=arguments.user).first()
	if not user:
		color.print_error("invalid user id: {0}".format(arguments.user))
		return

	for case in utilities.switch(arguments.action):
		if case('remove'):
			user.otp_secret = None
			break
		if case('set'):
			if user.otp_secret:
				color.print_error("the specified user already has an otp secret set")
				return
			if arguments.otp_secret:
				new_otp = arguments.otp_secret
			else:
				new_otp = pyotp.random_base32()
			if len(new_otp) != 16:
				color.print_error("invalid otp secret length, must be 16")
				return
			user.otp_secret = new_otp
			break

	if user.otp_secret:
		color.print_status("user: {0} otp: {1}".format(user.id, user.otp_secret))
		totp = pyotp.TOTP(user.otp_secret)
		uri = totp.provisioning_uri(user.id + '@king-phisher') + '&issuer=King%20Phisher'
		color.print_status("provisioning uri: {0}".format(uri))
	else:
		color.print_status("user: {0} otp: N/A".format(user.id))
	session.commit()
Ejemplo n.º 48
0
 def create(plugin, user_metadata):
     """Creates a new user given the user_metadata dictionary, assigns a new random secret"""
     user = User.get(plugin, user_metadata)
     if not user:
         token = pyotp.random_base32()
         permissions = set()
         if user_metadata['nick'] in getattr(settings, 'ADMIN_USERS', '').split(','):
             permissions = set(['administer_twofactor', 'grant_permissions', 'revoke_permissions', 'view_permissions'])
         return User(plugin, user_metadata, token, permissions)
     else:
         return None
Ejemplo n.º 49
0
    def otp_secret(self, msg, args):
        """Send a new secret to somebody"""
        new_secret = pyotp.random_base32()
        with self.lock:
            with self.stored('secrets') as secrets:
                secrets[args] = (new_secret, 0, BEGINNING_OF_TIMES)
        totp = pyotp.TOTP(new_secret)
        url = totp.provisioning_uri(args)
        self.send(self.build_identifier(args), makeQRCodeMessage(url, self._bot.mode), None, 'chat')

        return "New secret set for %s and message sent." % args
Ejemplo n.º 50
0
 def signup(self, request):
   username = request.username
   result = USER.query(USER.username==username).fetch(1)
   if len(result) > 0 :
     return SignUpResponse(success=False,message='username ' + username + ' already exists')
   else :
     ssecret = pyotp.random_base32()
     hotp = pyotp.HOTP(ssecret)
     url = 'https://chart.googleapis.com/chart?chs=200x200&chld=M%7C0&cht=qr&chl=' + urllib.quote(hotp.provisioning_uri(username), safe='') 
     USER(username=username,secret=ssecret,lastcounter=-1).put()
     return SignUpResponse(success=True, message=url)
Ejemplo n.º 51
0
 def gen_authenticator(self):
     """ Generates and stores new secret for authenticator. """
     timestamp = timezone.now()
     self.strong_authenticator_secret = pyotp.random_base32()
     current_authenticator_id = self.strong_authenticator_num
     self.strong_authenticator_id = settings.AUTHENTICATOR_NAME % (self.username, current_authenticator_id)
     self.strong_authenticator_num += 1
     self.strong_authenticator_generated_at = timestamp
     self.save()
     AuthenticatorCode.objects.create(user=self, generated_at=timestamp, authenticator_secret=self.strong_authenticator_secret, authenticator_id=self.strong_authenticator_id)
     return self.strong_authenticator_secret
Ejemplo n.º 52
0
def test_is_2fa_enabled():
    user_id = db_utils.create_user()
    tfa_secret = pyotp.random_base32()
    tfa_secret_encrypted = tfa._encrypt_totp_secret(tfa_secret)

    # 2FA is not enabled
    assert not tfa.is_2fa_enabled(user_id)

    # 2FA is enabled
    _insert_2fa_secret(user_id, tfa_secret_encrypted)
    assert tfa.is_2fa_enabled(user_id)
Ejemplo n.º 53
0
    def generate(self, **kwargs):
        """
        Generate Secret Key.

        Parameters:
            **kwargs: Optional. Any keyword arguments to be passed to
            `pyotp.random_base32`.

        Return Value: 16 chars random string that is able to be a secret key.

        """
        return random_base32(**kwargs)
Ejemplo n.º 54
0
def create_confirmed_user():
    main.models.db.create_all()
    print "creating [email protected]"
    password = flask.ext.security.utils.encrypt_password(getpass.getpass())
    main.user_datastore.create_user(
        email="*****@*****.**",
        password=password,
        active=True,
        confirmed_at=datetime.datetime.utcnow(),
        secret=pyotp.random_base32(),
        method_id=1,
    )
    main.models.db.session.commit()
Ejemplo n.º 55
0
def mfa_qr_code():
    user = g.user

    if not user.mfa_secret:
        user.mfa_secret = pyotp.random_base32()
        user.save(commit=True)

    totp = pyotp.TOTP(user.mfa_secret)
    uri = totp.provisioning_uri(user.get_username(), 'Standard Survival')
    image = qrcode.make(uri)

    stream = StringIO.StringIO()
    image.save(stream)
    image = stream.getvalue()

    return Response(image, mimetype='image/png')
Ejemplo n.º 56
0
def test_force_deactivate():
    user_id = db_utils.create_user()
    tfa_secret = pyotp.random_base32()
    tfa_secret_encrypted = tfa._encrypt_totp_secret(tfa_secret)

    _insert_2fa_secret(user_id, tfa_secret_encrypted)
    _insert_recovery_code(user_id)

    # Verify that force_deactivate() functions as expected.
    assert tfa.is_2fa_enabled(user_id)
    assert tfa.get_number_of_recovery_codes(user_id) == 1

    tfa.force_deactivate(user_id)

    assert not tfa.is_2fa_enabled(user_id)
    assert tfa.get_number_of_recovery_codes(user_id) == 0
Ejemplo n.º 57
0
    def setUp(self):
        """Setup."""
        self.secret = random_base32()

        class TestForm(Form):
            """Test Form."""

            totp = StringField(validators=[
                OTPCheck(
                    self.secret, method="TOTP", interval=30,
                    call_args={"valid_window": 0}
                )
            ])

        self.key = TOTP(self.secret).now()
        self.form = TestForm(data={"totp": self.key})
Ejemplo n.º 58
0
    def setUp(self):
        """Setup."""
        self.secret = random_base32()

        class TestForm(Form):
            """Test Form."""

            # Note that `window` parameter is just for testing.
            hotp = StringField(validators=[
                OTPCheck(
                    self.secret, method="HOTP", window=3,
                    call_args={"counter": 0}
                )
            ])

        self.key = HOTP(self.secret).at(0)
        self.form = TestForm(data={"hotp": self.key})
Ejemplo n.º 59
0
    def create_two_factor_key(self, user_id, two_factor_auth):
        """Enables two factor auth for a certain user."""

        user = self.identity_api.get_user(user_id) # check if user exists

        # create dictionary if requesting a new key
        if not two_factor_auth and self.driver.is_two_factor_enabled(user_id):
            two_factor_auth = {}

        two_factor_auth['key'] = pyotp.random_base32()
        key_object = self.driver.create_two_factor_key(user_id, two_factor_auth)

        totp = pyotp.TOTP(two_factor_auth['key'])
        # TODO(@federicofdez) Save issuer_name in settings
        key_object['uri'] = totp.provisioning_uri(user['name'], issuer_name=ISSUER_NAME)
        
        return key_object