def validate_machine_token(self, token): s = Signer(self.secret) try: s.unsign(token) return True except BadSignature: return False
def confirm_user(data=None): if not get_config('verify_emails'): return redirect(url_for('challenges.challenges_view')) if data and request.method == "GET": # User is confirming email account try: s = Signer(app.config['SECRET_KEY']) email = s.unsign(urllib.unquote_plus(data.decode('base64'))) except BadSignature: return render_template( 'confirm.html', errors=['Your confirmation link seems wrong']) except: return render_template( 'confirm.html', errors=['Your link appears broken, please try again.']) team = Teams.query.filter_by(email=email).first_or_404() team.verified = True db.session.commit() db.session.close() logger = logging.getLogger('regs') logger.warn("[{0}] {1} confirmed {2}".format( time.strftime("%m/%d/%Y %X"), team.name.encode('utf-8'), team.email.encode('utf-8'))) if authed(): return redirect(url_for('challenges.challenges_view')) return redirect(url_for('auth.login')) if not data and request.method == "GET": # User has been directed to the confirm page because his account is not verified if not authed(): return redirect(url_for('auth.login')) team = Teams.query.filter_by(id=session['id']).first_or_404() if team.verified: return redirect(url_for('views.profile')) else: verify_email(team.email) return render_template('confirm.html', team=team)
def save_session(self, app, session, response): domain = self.get_cookie_domain(app) path = self.get_cookie_path(app) if not session: if session.modified: self.redis.delete(self.session_prefix + session.session_id) response.delete_cookie(app.session_cookie_name, domain=domain, path=path) return httponly = self.get_cookie_httponly(app) secure = self.get_cookie_secure(app) expire = self.get_expiration_time(app, session) serialize_session = self.serialization_method.dumps(dict(session)) pipe = self.redis.pipeline() pipe.set(self.session_prefix + session.session_id, serialize_session) pipe.expire(self.session_prefix + session.session_id, total_seconds(self.expire_time)) pipe.execute() if self.use_sign: session_id = Signer(app.secret_key, salt='flask-redis-session', key_derivation='hmac').sign(session.session_id.encode('utf-8')) session_id = session_id.decode('utf-8') else: session_id = session.session_id print('session_id:', session_id) response.set_cookie(key=app.session_cookie_name, value=session_id, max_age=self.expire_time, expires=expire, path=path, domain=domain, secure=secure, httponly=httponly)
def signup(): data = request.get_json() app_root = os.getcwd() s = Signer('superpowerfullkey') token = s.sign(data['email'].encode()).decode() token = token[::-1].split('.')[0][::-1] if 'type' not in data: data['type'] = False image_path = None else: import base64 byte_image = base64.b64decode(data['image']) if not os.path.isdir(os.path.join(app_root, "images/")): os.mkdir(os.path.join(app_root, "images/")) image_path = os.path.join( os.path.join(app_root, "images/"), data['first_name'] + ' ' + data['last_name'] + '.jpg') with open(image_path, 'wb') as f: f.write(byte_image) newuser = User(data['first_name'], data['last_name'], data['email'], data['password'], token, data['type'], filepath_=image_path if image_path is not None else None) db.session.add(newuser) db.session.commit() return jsonify(status='success', token=token)
def captcha(publicID): publicID = publicID.lower() session_info = session_db.find_one({"publicID": publicID}, {"_id": 0}) hancock = Signer(str(secret_key), salt=str(session_info["privateID"])) if (publicID + "-guest") in request.cookies and hancock.validate( request.cookies.get(publicID + "-guest")): return redirect("https://www.crowdsourcejukebox.com/vote/" + publicID + "/") if request.method == "POST": captcha_response = request.form["g-recaptcha-response"] if is_human(captcha_response): resp = make_response( redirect("https://www.crowdsourcejukebox.com/vote/" + publicID + "/")) guestID = bytes(str(uuid.uuid4()), "utf-8") session_db.update_one({"publicID": publicID}, {"$inc": { "guests": 1 }}) resp.set_cookie( publicID + "-guest", value=hancock.sign(guestID), expires=datetime.datetime.now() + datetime.timedelta(hours=1), ) return resp else: return redirect("http://www.crowdsourcejukebox.com/") else: return render_template("captcha.html", sitekey=os.environ["RC_SITE_KEY"])
def validate_fingerprints(fp_secret_key, fp_salt, client_ip_fingerprint, browser_fingerprint, client_ip, user_agent, accept_language): is_valid = True signer = Signer(fp_secret_key, fp_salt) logging.debug('client_ip_fingerprint: %s', client_ip_fingerprint) calculated_client_ip_fingerprint = signer.get_signature(client_ip) logging.debug('calculated_client_ip_fingerprint: %s', calculated_client_ip_fingerprint) if calculated_client_ip_fingerprint != client_ip_fingerprint: logging.warn('Client IP does not match fingerprint in signature') is_valid = False # TODO: # Uncomment return line below until atmobeta sends the right fingerprint signature. # Just ignore fingerprint for now. return is_valid browser_fingerprint_input = ''.join([user_agent, accept_language]) logging.debug('browser_fingerprint_input: %s', browser_fingerprint_input) logging.debug('browser_fingerprint: %s', browser_fingerprint) calculated_browser_fingerprint = signer.get_signature( browser_fingerprint_input) logging.debug('calculated_browser_fingerprint: %s', calculated_browser_fingerprint) if calculated_browser_fingerprint != browser_fingerprint: logging.warn( 'Browser fingerprint does not match calculated fingerprint') is_valid = False return is_valid
def reset_password(): form = ResetPasswordForm(request.form) if request.method == "POST" and form.validate(): token = form.token.data s = Signer(app.config['SECRET_KEY']) try: email = s.unsign(token) except BadSignature: return render_template("reset_invalid_token.html") user = User.query.filter_by(email=email).first() if user: user.set_password(form.password.data) print user.password login_user(user) return redirect("/") else: return render_template("reset_invalid_token.html") token = request.args.get('token', None) if not token: return render_template("reset_invalid_token.html") return render_template("reset_password.html", form=form, token=token)
def cookie_serialize(secure_key, session_id, expire): """Serialize the cookie. Set the expire_time timestamp into the cookie""" signer = Signer(secure_key) session_data = session_id.encode('utf-8') + '&' + str(expire) session_data = signer.sign(session_data).decode('utf-8') return session_data
def auth_payload(user, device) -> dict: ret = { "name": user.name or "", "email": user.email, "mfa_enabled": user.enable_otp } # do not give api_key, user can only obtain api_key after OTP verification if user.enable_otp: s = Signer(FLASK_SECRET) ret["mfa_key"] = s.sign(str(user.id)) ret["api_key"] = None else: api_key = ApiKey.get_by(user_id=user.id, name=device) if not api_key: LOG.d("create new api key for %s and %s", user, device) api_key = ApiKey.create(user.id, device) db.session.commit() ret["mfa_key"] = None ret["api_key"] = api_key.code # so user is automatically logged in on the web login_user(user) return ret
def verify_cookie(cookey): """ verify that the signature contained in the cookie corresponds to the informations sent by the app (see generate_cookie_info) """ is_correct = False debug("verify_cookie for origin: " + base64_decode(cookey)) cookie_value = request.cookies.get(cookey) if cookie_value: debug("cookie exists for this origin") s = Signer(app.secret_key) expected_cookie_content = \ generate_cookie_info(base64_decode(cookey)) expected_cookie_content = s.get_signature(expected_cookie_content) debug("verify_cookie: " + cookie_value + ", " + expected_cookie_content) if expected_cookie_content == cookie_value: debug('correct cookie') is_correct = True else: debug('incorrect cookie') return is_correct
def action(): if not 'action' in request.json: abort(400) s = Signer(signkey) try: action = s.unsign(request.json['action']) except: abort(403) action = action.split('.', 1) if action[0] == 'LIST': return getList() if action[0] == 'GET': if len(action) != 2: abort(400) obj = action[1].split('.', 1) if len(obj) != 2: abort(400) key = obj[1] return getObject(key) if action[0] == 'STORE': if len(action) != 2: abort(400) return store(action[1]) if action[0] == 'DELETE': if len(action) != 2: abort(400) return delete(action[1]) abort(400)
def make_admin(self, req): data = JSONParser().parse(req) signer = Signer(settings.HASH_SECRET_KEY) poll_id = data['poll_id'] uid = data['user_id'] secret_token = data['secret_token'] try: unsigned_data = signer.unsign(secret_token).decode('ascii') if unsigned_data == poll_id: poll_user_object = PollUser.objects.get(pk=uid) poll_user_object.is_admin = True poll_user_object.status = 'AP' poll_user_object.save() return Response( {'msg': 'User is now superadmin for given poll'}, status=status.HTTP_201_CREATED) else: return Response({'msg': 'Invalid poll user combo'}, status=status.HTTP_400_BAD_REQUEST) except BadSignature: return Response({'msg': 'Corrupted secret token'}, status=status.HTTP_400_BAD_REQUEST) except PollUser.DoesNotExist: return Response({'msg': 'User with given ID does not exist'}, status=status.HTTP_400_BAD_REQUEST)
def auth_mfa(): """ Validate the OTP Token Input: mfa_token: OTP token that user enters mfa_key: MFA key obtained in previous auth request, e.g. /api/auth/login device: the device name, used to create an ApiKey associated with this device Output: 200 and user info containing: { name: "John Wick", api_key: "a long string", email: "user email" } """ data = request.get_json() if not data: return jsonify(error="request body cannot be empty"), 400 mfa_token = data.get("mfa_token") mfa_key = data.get("mfa_key") device = data.get("device") s = Signer(FLASK_SECRET) try: user_id = int(s.unsign(mfa_key)) except Exception: return jsonify(error="Invalid mfa_key"), 400 user = User.get(user_id) if not user: return jsonify(error="Invalid mfa_key"), 400 elif not user.enable_otp: return ( jsonify( error= "This endpoint should only be used by user who enables MFA"), 400, ) totp = pyotp.TOTP(user.otp_secret) if not totp.verify(mfa_token): return jsonify(error="Wrong TOTP Token"), 400 ret = {"name": user.name or "", "email": user.email} api_key = ApiKey.get_by(user_id=user.id, name=device) if not api_key: LOG.d("create new api key for %s and %s", user, device) api_key = ApiKey.create(user.id, device) db.session.commit() ret["api_key"] = api_key.code # so user is logged in automatically on the web login_user(user) return jsonify(**ret), 200
def login(): print "\033[32mWelcome to the \033[33mHack The Vote 2016 \033[32mSession system\033[0m" print "You are requesting a session for 'ballot return'" print print "Please enter your team password to continue (found in the challenge description):" print ">>", pw = raw_input() try: teamid = Signer(SECRET_KEY).unsign(pw) except Exception as e: print "\033[31mInvalid password!" exit() username = teamid.replace('/', '') # Create user if not exist try: pwd.getpwnam(username) print "\033[32mUser already exists", except KeyError: if not makeuser(username, pw): print "Error creating user. ping @clarkb7" exit() print "\033[32mYou may now", print "\033[33m`ssh ballot{}@ballotreturn.pwn.democrat` \033[32mwith your secret to cast your vote\033[0m".format( username)
def get_username_from_confirmation_token(app, confirmation_token): signer = Signer(app.config['SECRET_KEY'], salt='confirmation') try: username = signer.unsign(confirmation_token) except BadSignature: return None return username
def on_confirm_email(token): """Email confirmation endpoint. We try to confirm the specified signup and redirect to a webpage. """ try: s = Signer(get_token_secret()) signup_id = ObjectId(s.unsign(token).decode('utf-8')) except BadSignature: return "Unknown token" patch_internal('eventsignups', {'confirmed': True}, skip_validation=True, concurrency_check=False, **{current_app.config['ID_FIELD']: signup_id}) # Now the user may be able to get accepted, so update the events waiting # list lookup = {current_app.config['ID_FIELD']: signup_id} signup = current_app.data.find_one('eventsignups', None, **lookup) update_waiting_list(signup['event']) redirect_url = current_app.config.get('EMAIL_CONFIRMED_REDIRECT') if redirect_url: return redirect(redirect_url) else: return current_app.config['CONFIRM_TEXT']
def test_auth_mfa_success(flask_client): user = User.create( email="[email protected]", password="******", name="Test User", activated=True, enable_otp=True, otp_secret="base32secret3232", ) db.session.commit() totp = pyotp.TOTP(user.otp_secret) s = Signer(FLASK_SECRET) mfa_key = s.sign(str(user.id)) r = flask_client.post( url_for("api.auth_mfa"), json={ "mfa_token": totp.now(), "mfa_key": mfa_key, "device": "Test Device" }, ) assert r.status_code == 200 assert r.json["api_key"] assert r.json["name"] == "Test User"
def gen_signed_code(self, identifier=None): """Generates a signed code in the format discount_code_base.randint.signature""" if not identifier: identifier = buid() signer = Signer(self.secret) key = "{base}.{identifier}".format(base=self.discount_code_base, identifier=identifier) return signer.sign(key)
def virtual_machines_view(): # Check if authed if not utils.authed() or not 'id' in session: return redirect(url_for('auth.login', next='vm')) # Look for all vms that the team has access too (has solved the chal) vmso = VMs.query.join(Solves, Solves.teamid == int( session['id'])).filter(Solves.chalid == VMs.chalid).all() vms = [] # Set up the json data for v in vmso: signer = Signer(utils.get_config('VM_KEY'), salt=v.name, digest_method=sha256) vms.append({ 'name': v.name, 'desc': v.desc, 'key': signer.sign(json.dumps({ 'team': session['id'], 'vm': v.name })).encode('base64').replace('\n', '') }) # Run the template return render_template(PLUGIN_NAME + '/vms.html', vms=vms)
def sign(): s = Signer( bytes(input("Enter a secret(!!) key: "), encoding="UTF-8")) print(s.sign( bytes(input("Enter data\n"), encoding="UTF-8")).decode('UTF-8'))
def createreportdict(lat, lng, accuracy, form): dct = {} dct["latitude"] = lat dct["longitude"] = lng dct["latitude_rand"] = lat + 0.01 * random.random() dct["longitude_rand"] = lng + 0.01 * random.random() dct["accuracy"] = accuracy dct["test"] = form.test.data dct["datetest"] = None if form.datetest.data is None else form.datetest.data.strftime("%d.%m.%Y") dct["notherstest"] = form.notherstest.data dct["symptoms"] = ', '.join(form.symptoms.data) dct["dayssymptoms"] = form.dayssymptoms.data dct["notherssymptoms"] = form.notherssymptoms.data dct["age"] = form.age.data dct["sex"] = form.sex.data dct["email_addr"] = form.email_addr.data s = Signer(form.password.data) dct["signature"] = str(s.sign(form.email_addr.data)) dct["timestamp"] = firestore.SERVER_TIMESTAMP dct["email_confirmed"] = False dct["overwritten"] = False dct["source"] = "report" dct["token"] = str(generate_confirmation_token(dct["signature"])) return dct
def mailbox_confirm_change_route(): s = Signer(MAILBOX_SECRET) mailbox_id = request.args.get("mailbox_id") try: r_id = int(s.unsign(mailbox_id)) except Exception: flash("Invalid link", "error") return redirect(url_for("dashboard.index")) else: mailbox = Mailbox.get(r_id) # new_email can be None if user cancels change in the meantime if mailbox and mailbox.new_email: mailbox.email = mailbox.new_email mailbox.new_email = None # mark mailbox as verified if the change request is sent from an unverified mailbox mailbox.verified = True db.session.commit() LOG.d("Mailbox change %s is verified", mailbox) flash(f"The {mailbox.email} is updated", "success") return redirect( url_for("dashboard.mailbox_detail_route", mailbox_id=mailbox.id) ) else: flash("Invalid link", "error") return redirect(url_for("dashboard.index"))
def verify_mailbox_change(user, mailbox, new_email): s = Signer(MAILBOX_SECRET) mailbox_id_signed = s.sign(str(mailbox.id)).decode() verification_url = ( URL + "/dashboard/mailbox/confirm_change" + f"?mailbox_id={mailbox_id_signed}" ) send_email( new_email, f"Confirm mailbox change on SimpleLogin", render( "transactional/verify-mailbox-change.txt", user=user, link=verification_url, mailbox_email=mailbox.email, mailbox_new_email=new_email, ), render( "transactional/verify-mailbox-change.html", user=user, link=verification_url, mailbox_email=mailbox.email, mailbox_new_email=new_email, ), )
def build_url(self, local_path, **kwargs): local_path = local_path.strip('/') for key in 'background mode width height quality format padding'.split(): if key in kwargs: kwargs[key[0]] = kwargs.pop(key) # Remote URLs are encoded into the query. parsed = urlparse(local_path) if parsed.netloc: kwargs['u'] = local_path local_path = 'remote' # Local ones are not. else: abs_path = self.find_img(local_path) if abs_path: kwargs['v'] = encode_int(int(os.path.getmtime(abs_path))) # Sign the query. public_kwargs = ((k, v) for k, v in kwargs.iteritems() if not k.startswith('_')) query = urlencode(sorted(public_kwargs), True) signer = Signer(current_app.secret_key) sig = signer.get_signature('%s?%s' % (local_path, query)) return '%s/%s?%s&s=%s' % ( current_app.config['IMAGES_URL'], local_path, query, sig, )
def validate_fingerprints(fp_secret_key, fp_salt, client_ip_fingerprint, browser_fingerprint, client_ip, user_agent, accept_language): is_valid = True signer = Signer(fp_secret_key, fp_salt) logging.debug('client_ip_fingerprint: %s', client_ip_fingerprint) calculated_client_ip_fingerprint = signer.get_signature(client_ip) logging.debug('calculated_client_ip_fingerprint: %s', calculated_client_ip_fingerprint) if calculated_client_ip_fingerprint != client_ip_fingerprint: logging.warn('Client IP does not match fingerprint in signature') is_valid = False # TODO: # Uncomment return line below until atmobeta sends the right fingerprint signature. # Just ignore fingerprint for now. return is_valid browser_fingerprint_input = ''.join([ user_agent, accept_language]) logging.debug('browser_fingerprint_input: %s', browser_fingerprint_input) logging.debug('browser_fingerprint: %s', browser_fingerprint) calculated_browser_fingerprint = signer.get_signature(browser_fingerprint_input) logging.debug('calculated_browser_fingerprint: %s', calculated_browser_fingerprint) if calculated_browser_fingerprint != browser_fingerprint: logging.warn('Browser fingerprint does not match calculated fingerprint') is_valid = False return is_valid
def sign(): # if request.method == 'GET': # # return render_template('user_signup.html') # elif request.method == 'POST': # name = request.form.get('name') # email=request.form.get('email') # password=request.form.get('password') # phone = request.form.get('phone') # address = request.form.get('address') # newUser = p.PeopleProfile(name,email,password, phone, address) # db.session.add(newUser) # db.session.commit() # flash('Record were added successfully') # return render_template('user_signup.html' ) if request.method == 'POST': email = request.form.get("email") print email userS = p.PeopleProfile.query.filter_by(email=email).first() if userS: if userS.email == email: session['email'] = userS.email flash('email already registered') return render_template('user_signup.html') else: name = request.form.get('name') email = request.form.get('email') password = request.form.get('password') # hashpw = hash_password(password) phone = request.form.get('phone') address = request.form.get('address') bloodCategoryId = request.form.get('bloodCategory') # newUser = p.PeopleProfile(email = email) newUser = p.PeopleProfile(name, email, password, phone, address, bloodCategoryId) newUser.hash_password(password) db.session.add(newUser) db.session.commit() signer = Signer(app.secret_key) token = signer.sign(email) url = url_for('confirmation', token=token, _external=True) msg = Message( "E-mail confirmation for Sahayog - A Blood Donation Portal", sender="*****@*****.**", recipients=[email]) msg.body = url # flash(msg.body) mail.send(msg) flash('Record were added successfully') return render_template('user_signup.html') elif request.method == 'GET': bloodCategoryL = b.BloodCategory.query.all() return render_template('user_signup.html', bloodCategoryList=bloodCategoryL)
def test_malformed_timestamp(self, signer): other = Signer("secret-key") signed = other.sign(b"value.____________") with pytest.raises(BadTimeSignature) as exc_info: signer.unsign(signed) assert "Malformed" in str(exc_info.value)
def check_token(token): signer = Signer(flask.current_app.config["SECRET_KEY"]) try: id = int(signer.unsign(token).decode("ascii")) except Exception as e: return None user = Subscriber.query.filter_by(id=id).first() return user
def open_session(self, app, request): signedSessionId = request.cookie.get(app.session_cookie_name) if not signedSessionId: sessionId = str(uuid.uuid4()) return self.session_class(sessionId=sessionId) signer = Signer(app.secret_key, salt=self.salt, key_derivation='hmac') sessionId = signer.unsign(signedSessionId).decode() return self.session_class(sessionId=sessionId)
def test_timestamp_missing(self, signer): other = Signer("secret-key") signed = other.sign("value") with pytest.raises(BadTimeSignature) as exc_info: signer.unsign(signed) assert "missing" in str(exc_info.value)
def token(self) -> str: signer = Signer(current_app.config['JWT_TOKEN_SECRET']) jwt = JSONWebToken(secret_key=current_app.config['JWT_TOKEN_SECRET'], expires_in=15 * 60) string = ''.join((self.factor, self.code)) signature = signer.sign( string.encode('utf-8')).decode('utf-8').split('.')[1] return jwt.dumps({'signature': signature}).decode('utf-8')
def sign_user(user_data, fields=None): """Sign user data.""" signer = Signer(current_app.config['SECRET_KEY'], salt='newdle-users') return dict( user_data, signature=signer.get_signature( _get_signature_source_bytes(user_data, fields)).decode('ascii'), )
def verify_email(addr): s = Signer(app.config['SECRET_KEY']) token = s.sign(addr) text = """Please click the following link to confirm your email address for {}: {}""".format( get_config('ctf_name'), url_for('auth.confirm_user', _external=True) + '/' + token.encode('base64') ) sendmail(addr, text)
def test_frame_positive(self): signer = Signer(globals.SECRET_KEY) file = signer.sign(FILE_URL_POSITIVE) result = self.app.get(FRAME_PATH, query_string=dict(file_url=file), follow_redirects=True) self.assertEqual(result.status_code, 200) assert 'Frame Integration' in result.data
def verify_email(addr): s = Signer(app.config['SECRET_KEY']) token = s.sign(addr) text = """Please click the following link to confirm your email address for {}: {}""".format( get_config('ctf_name'), url_for('auth.confirm_user', _external=True) + '/' + urllib.quote_plus(token.encode('base64')) ) sendmail(addr, text)
def createreportdict(form): dct = {} dct["plz"] = form.plz.data crd = json.loads(form.geolocation.data) dct["latitude"] = crd["latitude"] dct["longitude"] = crd["longitude"] dct["accuracy"] = crd["accuracy"] if dct["latitude"] == 0: dct["longitude"], dct["latitude"] = plz2longlat(dct["plz"]) dct["latitude_rand"] = dct["latitude"] + 0.01 * random.random() dct["longitude_rand"] = dct["longitude"] + 0.01 * random.random() dct["username"] = form.username.data s = Signer(form.password.data) dct["signature"] = str(s.sign(form.username.data)) dct["age"] = form.age.data dct["sex"] = form.sex.data dct["plz"] = form.plz.data dct["headache"] = form.headache.data dct["cough"] = form.cough.data dct["shortnessbreath"] = form.shortnessbreath.data dct["musclepain"] = form.musclepain.data dct["sorethroat"] = form.sorethroat.data dct["nausea"] = form.nausea.data dct["diarrhea"] = form.diarrhea.data dct["rhinorrhea"] = form.rhinorrhea.data dct["travelhistory"] = form.travelhistory.data dct["contacthistory"] = form.contacthistory.data dct["notherstest"] = form.notherstest.data dct["dayssymptoms"] = form.dayssymptoms.data dct["arzt"] = form.arzt.data dct["test"] = form.test.data dct["datetest"] = None if form.datetest.data is None else form.datetest.data.strftime("%d.%m.%Y") dct["quarantine"] = form.quarantine.data dct["datequarantine"] = None if form.datetest.data is None else form.datequarantine.data.strftime("%d.%m.%Y") #dct["notherssymptoms"] = form.notherssymptoms.data try: dct["kreis"] = plz2kreis[dct["plz"]] except: dct["kreis"] = "" print(f"error converting PLZ {dct['plz']} to Kreisebene") dct["timestamp"] = firestore.SERVER_TIMESTAMP dct["email_confirmed"] = False dct["overwritten"] = False dct["source"] = "report" dct["token"] = str(generate_confirmation_token(dct["signature"])) return dct
def generate_csrf_token(user): """产生token""" secret_key = current_app.config.get("WTF_CSRF_SECRET_KEY", current_app.secret_key) nonce = os.urandom(24) user_id = user.id signer = Signer(secret_key) csrf_token = signer.sign(str(user_id)) print csrf_token return csrf_token
def create_url(text): """ Method that create signed link that should be send it to Slack. :param text: Url of the file that should be opened. :return: Signed link for opening file within embedded Frame terminal. """ signer = Signer(globals.SECRET_KEY) url = BASE_PATH + FRAME_PATH + '?file_url=' + signer.sign(text) return url
def attachment(self, att_id): s = Signer(current_app.config.get('SECRET_KEY'), sep='$') try: att_id = int(s.unsign(att_id)) attach_obj = self.model.client.model('ir.attachment') content = attach_obj.read(att_id, ['datas'])['datas'] image_fp = StringIO(base64.b64decode(content)) return send_file(image_fp) except BadSignature: abort(404)
def split_cookie(self, rv): signer = Signer(self.app.secret_key) cookie_data = rv.headers['Set-Cookie'].split(';', 1)[0] for cookie in cookie_data.split('&'): name, value = cookie_data.split('=') if name == self.app.session_cookie_name: unsigned_value = signer.unsign(value) return unsigned_value.split('_')
def forgot(): form = ForgotPasswordForm(request.form) if request.method == "POST" and form.validate(): s = Signer(app.config['SECRET_KEY']) token = s.sign(request.form['email']) send_password_reset(form.get_user(), token) return redirect('/forgot_confirmation') return render_template("forgot.html", form=form)
def cookie_unserialize(session_data, secure_key): """Unserialize the cookie: separate the session_id and expire_time timestamp.""" signer = Signer(secret_key=secure_key) try: session_data = signer.unsign(session_data).decode('utf-8') except BadSignature: session_data = None if not session_data: return None, None session_id, session_expire = session_data.split('&') return session_id, session_expire
def split_cookie(app, rv): signer = Signer(app.secret_key) cookie_data = rv.headers['Set-Cookie'].split(';', 1)[0] for cookie in cookie_data.split('&'): name, value = cookie_data.split('=') if name == app.session_cookie_name: unsigned_value = signer.unsign(value) sid, created = unsigned_value.split(b('_')) return sid.decode('ascii'), int(created, 16)
def verify(): s = Signer( bytes(input("Enter a secret(!!) key: "), encoding="UTF-8")) try: unsigned = s.unsign(bytes( input("Enter data\n"), encoding="UTF-8")).decode('UTF-8') except BadSignature: print("!!!!! FAILED !!!!!") return 0 print("---") print(unsigned)
def get_new_uid(user): s = Signer(SECRET_SIGN_KEY) with get_db() as cur: cur.execute("insert into mfc.schedules (username, festival) values (%s, %s) returning id", [user['email'] if user else None, festival]) uid = cur.fetchall()[0]['id'] # cookie is uid hashed with our private key cookie = cherrypy.response.cookie cookie_name = 'mfc_sch'+str(uid) cookie[cookie_name] = s.sign(str(uid)) cookie[cookie_name]['path'] = '/' cookie[cookie_name]['max-age'] = 3600 cookie[cookie_name]['version'] = 1 return uid
def validate_csrf_token(csrf_token): secret_key = current_app.config.get("WTF_CSRF_SECRET_KEY", current_app.secret_key) signer = Signer(secret_key) # if current_user.is_anonymous(): # return False try: signer.unsign(csrf_token) except BadSignature: return False # if str(current_user.get_id()) == id: # return True return True
def get_from_signed_code(cls, code): """Returns a discount policy given a valid signed code, returns None otherwise""" if not cls.is_signed_code_format(code): return None discount_code_base = code.split('.')[0] policy = cls.query.filter_by(discount_code_base=discount_code_base).one_or_none() if not policy: return None signer = Signer(policy.secret) try: signer.unsign(code) return policy except BadSignature: return None
def _get_user_id(): if current_app.config.get('DEBUG'): return request.values.get('user_id') if 'mws-track-id' not in request.cookies: raise MWSServerError(400, "Invalid request (missing cookie)") key = current_app.config.get('EDX_SHARED_KEY') s = Signer(key) try: user_id = s.unsign(request.cookies['mws-track-id']) except (BadSignature, TypeError) as e: _logger.exception(e) raise MWSServerError(403, "Invalid request (invalid cookie)") return user_id
def task_run(): signer = Signer(current_app.secret_key) _data = request.form['_'] data = json.loads(signer.unsign(_data)) callname = data.get('call') a, kw = data['args'], data['kwargs'] modname, symname = callname.rsplit('.', 1) mod = __import__(modname, fromlist=[symname]) call = getattr(mod, symname) call.direct(*a, **kw) return 'ok'
def get_public_deploy_key(instance_dns_name, secret, salt): ''' Wait for and retrieve instance public key. ''' signer = Signer(secret, salt) path = '/.well-known/deploy-key.txt' while True: print(' Waiting for', path) sleep(5) resp = requests.get('http://{}{}'.format(instance_dns_name, path)) if resp.status_code == 200: break return signer.unsign(resp.content)
def uid_is_valid(user, uid, festival): s = Signer(SECRET_SIGN_KEY) # cookie is uid hashed with our private key, check that the cookie was sent cookie = cherrypy.request.cookie.get('mfc_sch'+str(uid)) if cookie: # and if it's correct return str(uid) == s.unsign(str(cookie.value)) elif user: #check if this user is the user that's allowed for this uid. with get_db() as cur: cur.execute("select id from mfc.schedules where username = %s and festival = %s", [user['email'], festival]) r = cur.fetchall() if r: return str(uid) == str(r[0]['id']) # else not valid else: return False
def confirm_user(data=None): if not utils.get_config('verify_emails'): # If the CTF doesn't care about confirming email addresses then redierct to challenges return redirect(url_for('challenges.challenges_view')) # User is confirming email account if data and request.method == "GET": try: s = Signer(app.config['SECRET_KEY']) email = s.unsign(urllib.unquote_plus(data.decode('base64'))) except BadSignature: return render_template('confirm.html', errors=['Your confirmation link seems wrong']) except: return render_template('confirm.html', errors=['Your link appears broken, please try again.']) team = Teams.query.filter_by(email=email).first_or_404() team.verified = True db.session.commit() logger = logging.getLogger('regs') logger.warn("[{0}] {1} confirmed {2}".format(time.strftime("%m/%d/%Y %X"), team.name.encode('utf-8'), team.email.encode('utf-8'))) db.session.close() if utils.authed(): return redirect(url_for('challenges.challenges_view')) return redirect(url_for('auth.login')) # User is trying to start or restart the confirmation flow if not utils.authed(): return redirect(url_for('auth.login')) team = Teams.query.filter_by(id=session['id']).first_or_404() if data is None: if request.method == "POST": # User wants to resend their confirmation email if team.verified: return redirect(url_for('views.profile')) else: utils.verify_email(team.email) return render_template('confirm.html', team=team, infos=['Your confirmation email has been resent!']) elif request.method == "GET": # User has been directed to the confirm page team = Teams.query.filter_by(id=session['id']).first_or_404() if team.verified: # If user is already verified, redirect to their profile return redirect(url_for('views.profile')) return render_template('confirm.html', team=team)
def render(self, template, **kwargs): attach_obj = self.model.client.model('ir.attachment') model = kwargs.get('model') if model: search_params = [ ('res_id', '=', model.id), ('res_model', '=', self.model._name) ] attach_ids = attach_obj.search(search_params) fields_to_read = ['datas_fname', 'name'] if attach_ids: attachments = attach_obj.read(attach_ids, fields_to_read) else: attachments = [] s = Signer(current_app.config.get('SECRET_KEY'), sep='$') for att in attachments: att['id'] = s.sign(str(att['id'])) kwargs['attachments'] = attachments return super(OpenERPModelView, self).render(template, **kwargs)
def build_url(self, local_path, **kwargs): # Make the path relative. local_path = local_path.strip('/') # We complain when we see non-normalized paths, as it is a good # indicator that unsanitized data may be getting through. # Mutating the scheme syntax to match is a little gross, but it works # for today. norm_path = os.path.normpath(local_path) if local_path.replace('://', ':/') != norm_path or norm_path.startswith('../'): raise ValueError('path is not normalized') for key in 'background mode width height quality format padding'.split(): if key in kwargs: kwargs[key[0]] = kwargs.pop(key) # Remote URLs are encoded into the query. parsed = urlparse(local_path) if parsed.scheme or parsed.netloc: if parsed.scheme not in ALLOWED_SCHEMES: raise ValueError('scheme %r is not allowed' % parsed.scheme) kwargs['u'] = local_path local_path = 'remote' # Local ones are not. else: abs_path = self.find_img(local_path) if abs_path: kwargs['v'] = encode_int(int(os.path.getmtime(abs_path))) # Sign the query. public_kwargs = ((k, v) for k, v in kwargs.iteritems() if not k.startswith('_')) query = urlencode(sorted(public_kwargs), True) signer = Signer(current_app.secret_key) sig = signer.get_signature('%s?%s' % (local_path, query)) return '%s/%s?%s&s=%s' % ( current_app.config['IMAGES_URL'], urlquote(local_path), query, sig, )
def __init__(self): self.s = {} self.s['ip'] = '127.0.0.1' self.s['first_reg'] = 1442955065 self.s['kolvo_visits'] = 1 self.s['user_id'] = 'yap1442955065' self.s['last_visit'] = '16702' self.minus_days = 0 self.sig = Signer('andrii')