Пример #1
0
    def got_data(self):
        while True:
            if len(self.recvbuf) < 4:
                return
            if self.recvbuf[:4] != "\xf9\xbe\xb4\xd9":
                raise ValueError("got garbage %s" % repr(self.recvbuf))

            if len(self.recvbuf) < 4 + 12 + 4 + 4:
                return
            command = self.recvbuf[4:4+12].split("\x00", 1)[0]
            msglen = struct.unpack("<i", self.recvbuf[4+12:4+12+4])[0]
            checksum = self.recvbuf[4+12+4:4+12+4+4]
            if len(self.recvbuf) < 4 + 12 + 4 + 4 + msglen:
                return
            msg = self.recvbuf[4+12+4+4:4+12+4+4+msglen]
            th = SHA256(msg).digest()
            h = SHA256(th).digest()
            if checksum != h[:4]:
                raise ValueError("got bad checksum %s" % repr(self.recvbuf))
            self.recvbuf = self.recvbuf[4+12+4+4+msglen:]

            if command in self.messagemap:
                f = cStringIO.StringIO(msg)
                t = self.messagemap[command]()
                t.deserialize(f)
                self.got_message(t)
            else:
                print "UNKNOWN COMMAND", command, repr(msg)
Пример #2
0
 def calc_hash(self):
     if self.hash is None:
        r = []
        r.append(struct.pack("<i", self.nVersion))
        r.append(ser_uint256(self.hashPrevBlock))
        r.append(ser_uint256(self.hashMerkleRoot))
        r.append(struct.pack("<I", self.nTime))
        r.append(struct.pack("<I", self.nBits))
        r.append(struct.pack("<I", self.nNonce))
        self.hash = uint256_from_str(SHA256(SHA256(''.join(r)).digest()).digest())
     return self.hash
Пример #3
0
 def prepare_message(self, message):
     command = message.command
     data = message.serialize()
     tmsg = "\xf9\xbe\xb4\xd9"
     tmsg += command
     tmsg += "\x00" * (12 - len(command))
     tmsg += struct.pack("<I", len(data))
     th = SHA256(data).digest()
     h = SHA256(th).digest()
     tmsg += h[:4]
     tmsg += data
     return tmsg
Пример #4
0
def login_user(uname, pword, two_fa):
    # User login checks

    # Check if user exists, and if so get the user
    try:
        user_record = db_session.query(User).filter(User.uname == uname).first()
    except exc.SQLAlchemyError as err:
        set_status('Login failed, db error', 'result')
        return False

    if user_record is None:
        set_status('Login failed, username or password incorrect', 'result')
        return False, None

    # Check if password is valid
    hashish = SHA256()
    hashish.update(pword.encode('utf-8'))
    hashish.update(user_record.salt.encode('utf-8'))
    in_password = hashish.hexdigest()
    our_password = user_record.pword
    if our_password != in_password:
        set_status('Login failed, username or password incorrect', 'result')
        return False, None

    # Check if our 2fa simulation is valid or not
    our_2fa = user_record.two_fa
    in_2fa = two_fa
    if our_2fa != in_2fa:
        set_status('Two-factor authentication failure', 'result')
        return False, None

    return True, user_record
Пример #5
0
def login():
    form = UserLoginForm()
    result = None
    if request.method == 'POST':
        DBSessionMaker = setup_db()
        session = DBSessionMaker()
        uname = form.uname.data
        pword = form.pword.data
        mfa = form.mfa.data
        userdetails = session.query(Users).filter(Users.uname == uname).first()
        if (userdetails == None):
            result = "incorrect"
            return render_template('login.html', form=form, result=result)
        salt = userdetails.salt
        hasher = SHA256()
        hasher.update(pword.encode('utf-8'))
        hasher.update(salt.encode('utf-8'))
        passwordhash = hasher.hexdigest()
        if (passwordhash != userdetails.pword):
            result = "incorrect"
            session.close()
            return render_template('login.html', form=form, result=result)
        if (mfa != userdetails.mfa):
            result = "Two-factor failure"
            session.close()
            return render_template('login.html', form=form, result=result)
        user = User()
        user.id = uname
        flask_login.login_user(user)
        loginrec = LoginRecord(user_id=uname, time_on=datetime.now())
        session.add(loginrec)
        session.commit()
        session.close()
        result = "success"
    return render_template('login.html', form=form, result=result)
Пример #6
0
def register():
    form = RegistrationForm()
    DBSessionMaker = setup_db()
    session = DBSessionMaker()
    success = None
    if request.method == 'POST' and form.validate():
        hasher = SHA256()
        pword = form.pword.data
        hasher.update(pword.encode('utf-8'))
        uname = form.uname.data
        salt = token_hex(nbytes=16)
        hasher.update(salt.encode('utf-8'))
        passwordhash = hasher.hexdigest()
        mfa = form.mfa.data
        new_user = Users(uname=uname, pword=passwordhash, mfa=mfa, salt=salt)
        session.add(new_user)
        try:

            session.commit()
        except:
            form.uname.data = 'user already exists'
            success = 'failure'
            session.close()
            return render_template('register.html', form=form, success=success)
        success = "success"
        session.close()
    return render_template('register.html', form=form, success=success)
Пример #7
0
def login(session):
    uname = input("Username: "******"Password: "******"Phone Number: ")
    hasher = SHA256()
    # Get the user we're attempting to log in as.
    user_record = session.query(User).filter(User.uname == uname).first()
    # Grab their salt.
    salt = user_record.salt
    # Add password and salt to hasher.
    hasher.update(pword.encode('utf-8'))
    hasher.update(salt.encode('utf-8'))
    # Get hex digest.
    password_hash = hasher.hexdigest()
    # Confirm that the credentials are correct.
    if(password_hash == user_record.pword):
        if (phone == user_record.phone):
            # Log this login.
            login_record = LoginRecord(user_id=user_record.user_id, time_on=datetime.now())
            session.add(login_record)
            session.commit()
            # return success.
            return True, user_record
    # Auth failed.
    return False
Пример #8
0
def mine(block_number,transactions,previous_hash,prefix_zeros):
    prefix_str='0'*prefix_zeros
    for nonce in range (MAX_NONCE)  
        text=str(block_number)+transactions+previous_hash+str(nonce)
        new_hash=SHA256(text)
        if new_hash=startswith(prefix_str):
            print(f"Yay!!Successfully mind bitcoins with nonce value:{nonce}")
Пример #9
0
def register(session):
    form = RegisterForm()

    if form.validate_on_submit():
        #if len(form.password.data) > 7:
        pword = form.password.data
        hasher = SHA256()
        # Add password to hash algorithm.
        hasher.update(pword.encode('utf-8'))
        # Generate random salt.
        salt = token_hex(nbytes=16)
        # Add random salt to hash algorithm.
        hasher.update(salt.encode('utf-8'))
        # Get the hex of the hash.
        pword_store = hasher.hexdigest()
        # Store the new user in the database.
        new_user = User(uname=form.uname.data,
                        pword=pword_store,
                        salt=salt,
                        phone=form.phone.data)
        session.add(new_user)
        # Probably want error handling, etc. For this simplified code,
        # we're assuming all is well.
        session.commit()

        #hashed_password = generate_password_hash(form.password.data, method='sha256')
        #new_user = User(username=form.username.data, password=hashed_password, phonenumber=form.phonenumber.data)
        #db.session.add(new_user)
        #db.session.commit()
        #if form.phonenumber.data:
        return '<h1 id="success">New user has been created! Success !</h1>'
    #return '<h1 id = "success"> Failure !</h1>'
    #return '<h1>' + form.username.data + ' ' + form.email.data + ' ' + form.password.data + '</h1>'

    return render_template('register.html', form=form)
Пример #10
0
    def send_message(self, message):
        if not self.connected:
            return

        command = message.command
        data = message.serialize()
        tmsg = "\xf9\xbe\xb4\xd9"
        tmsg += command
        tmsg += "\x00" * (12 - len(command))
        tmsg += struct.pack("<I", len(data))
        th = SHA256(data).digest()
        h = SHA256(th).digest()
        tmsg += h[:4]
        tmsg += data

        self.transport.write(tmsg)
        self.last_sent = time.time()
Пример #11
0
def register():
    if request.method == 'POST':
        uname = request.form.get('uname')
        pword = request.form.get('pword')  # TODO: look ma, cleartext password
        two_fa = request.form.get('2fa')
        user_type = 1
        csrf_token = request.form.get('csrf_token')

        # CSRF Check
#        our_token = session.get('csrf_token')
#        if csrf_token != our_token:
#            return render_template('404.html')
        session.pop('csrf_token', None)

        # Registration Checks
        if not validate_registration_or_login(uname, pword, two_fa):
            set_status('Registration failure - bad input', 'success')
            session['csrf_token'] = str(random())  # Implement basic CSRF protection
            return render_template('register.html', status=get_status(), csrf_token=session.get('csrf_token'))

        # does user already exist
        try:
            user_record = db_session.query(User).filter(User.uname == uname).first()
        except exc.SQLAlchemyError as err:
            set_status('Registration failure - db error', 'success')
            session['csrf_token'] = str(random())  # Implement basic CSRF protection
            return render_template('register.html', status=get_status(), csrf_token=session.get('csrf_token'))

        if user_record is not None:
            set_status('Registration failure - user exists', 'success')
            session['csrf_token'] = str(random())  # Implement basic CSRF protection
            return render_template('register.html', status=get_status(), csrf_token=session.get('csrf_token'))

        # Otherwise register user
        hashish = SHA256()
        hashish.update(pword.encode('utf-8'))
        salt = token_hex(nbytes=16)
        hashish.update(salt.encode('utf-8'))
        new_user = User(uname=uname, pword=hashish.hexdigest(), two_fa=two_fa, salt=salt, user_type=user_type)
        try:
            db_session.add(new_user)
            db_session.commit()
        except exc.SQLAlchemyError as err:
            set_status('Registration failure, dumb db error', 'success')
            session['csrf_token'] = str(random())  # Implement basic CSRF protection
            return render_template('register.html', status=get_status(), csrf_token=session.get('csrf_token'))
        set_status('Registration success - now please login', 'success')
        return redirect(url_for('login'))

    else:
        session['csrf_token'] = str(random())  # Implement basic CSRF protection
        return render_template('register.html', status=get_status(), csrf_token=session.get('csrf_token'))
Пример #12
0
def login():
    form = LoginForm()

    global logged_in_user

    if form.validate_on_submit():

        hasher = SHA256()
        # Get the user we're attempting to log in as.
        user_record = session.query(User).filter(
            User.uname == form.username.data).first()
        if not user_record:
            return '<p id="result"> Failure </p>'
        # Grab their salt.
        salt = user_record.salt
        # Add password and salt to hasher.
        pword = form.password.data
        hasher.update(pword.encode('utf-8'))
        hasher.update(salt.encode('utf-8'))
        # Get hex digest.
        password_hash = hasher.hexdigest()
        # Confirm that the credentials are correct.
        if (password_hash == user_record.pword):
            if (form.phonenumber.data == user_record.phone):
                # Log this login.
                login_record = LoginRecord(user_id=user_record.id,
                                           time_on=datetime.now())
                session.add(login_record)
                session.commit()
                logged_in_user = user_record
                # return success.
                #return True, user_record
                # Auth failed.
                #return False
                login_user(user_record, remember=form.remember.data)
                return redirect(url_for('spell_check'))

        return '<h1 id = "result">Invalid username or password</h1>'

        #user = User.query.filter_by(username=form.username.data).first()
        #if user:
        #    if check_password_hash(user.password, form.password.data):
        #        phonenumber = User.query.filter_by(phonenumber=form.phonenumber.data).first()
        #        if phonenumber:
        #            login_user(user, remember=form.remember.data)
        #            return redirect(url_for('spell_check'))

        #return '<h1 id = "result">Invalid username or password</h1>'
        #return '<h1>' + form.username.data + ' ' + form.password.data + '</h1>'

    return render_template('login.html', form=form)
Пример #13
0
    def is_valid(self):
        self.calc_hash()
        target = uint256_from_compact(self.nBits)
        if self.hash > target:
           return False
        hashes = []
        for tx in self.vtx:
            tx.sha256 = None
            if not tx.is_valid():
                return False
            tx.calc_sha256()
            hashes.append(ser_uint256(tx.sha256))

        while len(hashes) > 1:
            newhashes = []
            for i in xrange(0, len(hashes), 2):
                i2 = min(i+1, len(hashes)-1)
                newhashes.append(SHA256(SHA256(hashes[i] + hashes[i2]).digest()).digest())
            hashes = newhashes

        if uint256_from_str(hashes[0]) != self.hashMerkleRoot:
            return False
        return True
Пример #14
0
def login():
    login_form = LoginForm()
    if login_form.validate_on_submit():
        queryforuser = User.query.filter_by(uname=login_form.uname.data).all()
        if len(queryforuser) == 1:
            pword = login_form.pword.data
            hasher = SHA256()
            # Add password to hash algorithm.
            hasher.update(pword.encode('utf-8'))
            # Generate random salt.
            salt = queryforuser[0].salt
            # Add random salt to hash algorithm.
            hasher.update(salt.encode('utf-8'))
            # Get the hex of the hash.
            pword_store = hasher.hexdigest()
            # use this to see what's being compared - flash(f"{queryforuser[0].pword}, {pword_store}")
            if queryforuser[0].pword == pword_store:
                if queryforuser[0].twofa == login_form.two_fa_field.data:
                    flash(
                        "Login successful for user {}".format(
                            login_form.uname.data), 'success')
                    session[
                        'uname'] = login_form.uname.data  # create session cookie
                    # create a log record  (login record)
                    new_login = LoginRecord(user_id=login_form.uname.data)
                    db.session.add(new_login)
                    db.session.commit()
                    return render_template('login.html',
                                           form=login_form,
                                           result='success')
                else:
                    flash("Login unsuccessful.  bad 2fa")
                    return render_template('login.html',
                                           form=login_form,
                                           result='Two-factor failure')
            else:
                flash("Login unsuccessful, bad password")
                return render_template('login.html',
                                       form=login_form,
                                       result='incorrect')
        else:
            flash("You are not registered user, please register")
            return render_template('login.html',
                                   form=login_form,
                                   result='incorrect')
    return render_template(
        'login.html',
        form=login_form,
    )
Пример #15
0
def register_admin():
    uname = 'admin'
    pword = 'Administrator@1'
    two_fa = '12345678901'
    user_type = 0
    hashish = SHA256()
    hashish.update(pword.encode('utf-8'))
    salt = token_hex(nbytes=16)
    hashish.update(salt.encode('utf-8'))
    new_user = User(uname=uname, pword=hashish.hexdigest(), two_fa=two_fa, salt=salt, user_type=user_type)
    try:
        db_session.add(new_user)
        db_session.commit()
    except exc.SQLAlchemyError as err:
        print("Failed to register Admin user. DB Erorr")
        db_session.rollback()
Пример #16
0
def register():
    register_form = RegistrationForm()
    if register_form.validate_on_submit():
        queryforuser = User.query.filter_by(
            uname=register_form.uname.data).all()
        # flash(f"your query resulted in {queryforuser}")
        if len(queryforuser) == 0:
            uname = register_form.uname.data
            pword = register_form.pword.data
            hasher = SHA256()
            # Add password to hash algorithm.
            hasher.update(pword.encode('utf-8'))
            # Generate random salt.
            salt = token_hex(nbytes=16)
            # Add random salt to hash algorithm.
            hasher.update(salt.encode('utf-8'))
            # Get the hex of the hash.
            pword_store = hasher.hexdigest()
            # Add a two factor auth number
            twofa = register_form.two_fa_field.data
            # Is an admin? 0 is no; 1 is yes
            isadm = 0
            # Store the new user in the database.
            new_user = User(uname=uname,
                            pword=pword_store,
                            salt=salt,
                            twofa=twofa,
                            isadm=isadm)
            db.session.add(new_user)
            # Probably want error handling, etc. For this simplified code, we're assuming all is well.
            db.session.commit()
            flash(
                f"Registration successful for user {register_form.uname.data} Please login"
            )
            return render_template('register.html',
                                   form=register_form,
                                   success='success')
        else:
            flash(f"User {register_form.uname.data} already registered")
            return render_template('register.html',
                                   form=register_form,
                                   success='failure')
    return render_template('register.html', form=register_form)
Пример #17
0
def default(session):
    uname = "admin"
    pword = "Administrator@1"
    #email = "*****@*****.**"
    phone = "12345678901"
    hasher = SHA256()
    # Add password to hash algorithm.
    hasher.update(pword.encode('utf-8'))
    # Generate random salt.
    salt = token_hex(nbytes=16)
    # Add random salt to hash algorithm.
    hasher.update(salt.encode('utf-8'))
    # Get the hex of the hash.
    pword_store = hasher.hexdigest()
    # Store the new user in the database.
    new_user = User(uname=uname, pword=pword_store, salt=salt, phone=phone)
    session.add(new_user)
    # Probably want error handling, etc. For this simplified code,
    # we're assuming all is well.
    session.commit()
Пример #18
0
def register(session):
    # Get username and password.
    uname = input("Username: "******"Password: "******"Email: ")
    phone = input("Phone Number: ")
    hasher = SHA256()
    # Add password to hash algorithm.
    hasher.update(pword.encode('utf-8'))
    # Generate random salt.
    salt = token_hex(nbytes=16)
    # Add random salt to hash algorithm.
    hasher.update(salt.encode('utf-8'))
    # Get the hex of the hash.
    pword_store = hasher.hexdigest()
    # Store the new user in the database.
    new_user = User(uname=uname, pword=pword_store, salt=salt, email=email, phone=phone)
    session.add(new_user)
    # Probably want error handling, etc. For this simplified code,
    # we're assuming all is well.
    session.commit()
Пример #19
0
def setup_db():
    global BASE
    engine = create_engine(f'sqlite:///{DBFILE}')
    BASE.metadata.bind = engine
    if not (os.path.isfile(DBFILE)):
        BASE.metadata.create_all(engine)
        DBSessionMaker = sessionmaker(bind=engine)
        session = DBSessionMaker()
        #ADD ADMINISTRATOR
        hasher = SHA256()
        pword = "Administrator@1"
        hasher.update(pword.encode('utf-8'))
        uname = "admin"
        salt = token_hex(nbytes=16)
        hasher.update(salt.encode('utf-8'))
        passwordhash = hasher.hexdigest()
        mfa = "12345678901"
        new_user = Users(uname=uname, pword=passwordhash, mfa=mfa, salt=salt)
        session.add(new_user)
        session.commit()
        session.close()
    else:
        DBSessionMaker = sessionmaker(bind=engine)
    return DBSessionMaker
Пример #20
0
 def is_valid(self):
     self.calc_hash()
     target = util.uint256_from_compact(self.nBits)
     if self.sha256 > self.target:
         return False
     hashes = []
     hashes.append(b'\0' * 0x20)
     for tx in self.vtx[1:]:
         hashes.append(SHA256(SHA256(tx.serialize()).digest()).digest())
     while len(hashes) > 1:
         newhashes = []
         for i in xrange(0, len(hashes), 2):
             i2 = min(i + 1, len(hashes) - 1)
             newhashes.append(
                 SHA256(SHA256(hashes[i] + hashes[i2]).digest()).digest())
         hashes = newhashes
     calcwitness = SHA256(SHA256(hashes[0] +
                                 witness_nonce).digest()).digest()
     if calcwitness != self.witness:
         return False
     return True
Пример #21
0
def sha256(x) -> Hash32:
    return SHA256(x).digest()
Пример #22
0
    def fill_from_rpc(self, data):
        '''Convert getblocktemplate result into BlockTemplate instance'''

        commitment = None
        txids = []
        hashes = [None] + [
            util.ser_uint256(int(t['hash'], 16)) for t in data['transactions']
        ]
        try:
            txids = [None] + [
                util.ser_uint256(int(t['txid'], 16))
                for t in data['transactions']
            ]
            mt = merkletree.MerkleTree(txids)
        except KeyError:
            mt = merkletree.MerkleTree(hashes)

        wmt = merkletree.MerkleTree(hashes).withFirst(
            binascii.unhexlify(
                '0000000000000000000000000000000000000000000000000000000000000000'
            ))
        self.witness = SHA256(SHA256(wmt + witness_nonce).digest()).digest()
        commitment = b'\x6a' + struct.pack(
            ">b",
            len(self.witness) +
            len(witness_magic)) + witness_magic + self.witness
        try:
            default_witness = data['default_witness_commitment']
            commitment_check = binascii.unhexlify(default_witness)
            if (commitment != commitment_check):
                print(
                    "calculated witness does not match supplied one! This block probably will not be accepted!"
                )
                commitment = commitment_check
        except KeyError:
            pass
        self.witness = commitment[6:]

        coinbasetxn = data['coinbasetxn']['data']
        coinbasetxn = binascii.unhexlify(coinbasetxn)
        coinbase = self.coinbase_transaction_class(coinbasetxn,
                                                   settings.COINBASE_EXTRAS)

        self.height = data['height']
        self.nVersion = data['version']
        self.hashPrevBlock = int(data['previousblockhash'], 16)
        self.nBits = int(data['bits'], 16)
        self.hashMerkleRoot = 0
        self.nTime = 0
        self.nNonce = 0
        self.vtx = [
            coinbase,
        ]

        for tx in data['transactions']:
            t = TxBlob()
            t.deserialize(binascii.unhexlify(tx['data']))
            self.vtx.append(t)

        self.curtime = data['curtime']
        self.timedelta = self.curtime - int(self.timestamper.time())
        self.merkletree = mt
        self.target = util.uint256_from_compact(self.nBits)

        # Reversed prevhash
        self.prevhash_bin = binascii.unhexlify(
            util.reverse_hash(data['previousblockhash']))
        self.prevhash_hex = "%064x" % self.hashPrevBlock

        self.broadcast_args = self.build_broadcast_args()
        return self.broadcast_args
Пример #23
0
def login():
    form = LoginForm()
    result = ""
    unameSuccess = "false"
    pwordSuccess = "false"
    ID_2faSuccess = "false"
    pw_hasher = SHA512()
    mfa_hasher = SHA256()

    if form.validate_on_submit():

        global DBSessionMaker
        session = DBSessionMaker()

        uname = form.uname.data
        ID_2fa = form.ID_2fa.data
        pword = form.pword.data

        # Retrieve user info from DB
        user_record = session.query(User).filter(User.uname == uname).first()
        pw_salt = user_record.pw_salt
        mfa_salt = user_record.mfa_salt

        # Add password and pw salt to hasher
        pw_hasher.update(pword.encode('utf-8'))
        pw_hasher.update(pw_salt.encode('utf-8'))
        password_hash = pw_hasher.hexdigest()

        # Add mfa and mfa salt to hasher
        mfa_hasher.update(ID_2fa.encode('utf-8'))
        mfa_hasher.update(mfa_salt.encode('utf-8'))
        mfa_hash = mfa_hasher.hexdigest()

        # Confirm that the credentials are correct
        if (password_hash == user_record.pword):
            # Return success on uname & pword
            unameSuccess = "true"
            pwordSuccess = "true"

            # Confirm MFA is correct
            if (mfa_hash == user_record.ID_2fa):
                # Return success on uname & pword
                ID_2faSuccess = "true"

        if unameSuccess == "true" and pwordSuccess == "true" and ID_2faSuccess == "true":
            global logged_in
            global user_logged_in
            logged_in = True
            user_logged_in = user_record.user_ID

            # Create log record of login
            new_log = Log_Record(user_ID=user_record.user_ID,
                                 action_type="login")

            # Add log record to DB
            session.add(new_log)
            session.commit()

            result = "Success"

        elif unameSuccess == "false":
            result = "incorrect"
        elif pwordSuccess == "false":
            result = "incorrect"
        elif ID_2faSuccess == "false":
            result = "Two-factor failure"

        session.close()

    # Doesn't pass validation
    else:
        result = "failure"

    return render_template("login.html",
                           title="Login",
                           form=form,
                           login=True,
                           result=result,
                           logged_in=logged_in,
                           user_logged_in=user_logged_in)
Пример #24
0
def register():

    form = RegisterForm()
    success = ""

    pw_hasher = SHA512()
    mfa_hasher = SHA256()

    # If submitted and validated, save info but do not login
    if form.validate_on_submit():

        global DBSessionMaker
        session = DBSessionMaker()

        # Pull info from form
        uname = form.uname.data
        ID_2fa = form.ID_2fa.data
        pword = form.pword.data

        # Check if already exists
        existing_user = session.query(User).filter(User.uname == uname).first()

        if not existing_user:

            # SALT PW
            pw_hasher.update(pword.encode('utf-8'))
            salt_pw_value = token_hex(nbytes=16)
            pw_hasher.update(salt_pw_value.encode('utf-8'))
            pword_hexed = pw_hasher.hexdigest()
            # SALT MFA
            mfa_hasher.update(ID_2fa.encode('utf-8'))
            salt_mfa_value = token_hex(nbytes=16)
            mfa_hasher.update(salt_mfa_value.encode('utf-8'))
            mfa_hexed = mfa_hasher.hexdigest()

            # Create User class with user info
            new_user = User(uname=uname,
                            pword=pword_hexed,
                            ID_2fa=mfa_hexed,
                            pw_salt=salt_pw_value,
                            mfa_salt=salt_mfa_value)

            # Add new user and log to DB
            session.add(new_user)
            session.commit()

            # Get just added user's user_ID
            just_added_user = session.query(User).filter(
                User.uname == uname).first()

            # Create log record of registration
            new_log = Log_Record(user_ID=just_added_user.user_ID,
                                 action_type="register")
            session.add(new_log)
            session.commit()

            # Return success
            success = "succcess"

        else:
            success = "failure - user already exists"

        session.close()

    # Doesn't pass validation
    else:
        success = "failure"

    return render_template("register.html",
                           title="Register",
                           form=form,
                           register=True,
                           success=success,
                           logged_in=logged_in,
                           user_logged_in=user_logged_in)
Пример #25
0
        self.text_submitted = text_submitted
        self.results_received = results_received


# Create DB again
BASE.metadata.create_all(engine)
DBSessionMaker = sessionmaker(bind=engine)

session = DBSessionMaker()

# Create Admin
admin_uname = "admin"
admin_pword = "Administrator@1"
admin_ID_2fa = "12345678901"
pw_hasher = SHA512()
mfa_hasher = SHA256()
# SALT PW
pw_hasher.update(admin_pword.encode('utf-8'))
salt_pw_value = token_hex(nbytes=16)
pw_hasher.update(salt_pw_value.encode('utf-8'))
pword_hexed = pw_hasher.hexdigest()
# SALT MFA
mfa_hasher.update(admin_ID_2fa.encode('utf-8'))
salt_mfa_value = token_hex(nbytes=16)
mfa_hasher.update(salt_mfa_value.encode('utf-8'))
mfa_hexed = mfa_hasher.hexdigest()
# Create User class with admin info
admin_user = User(uname=admin_uname,
                  pword=pword_hexed,
                  pw_salt=salt_pw_value,
                  ID_2fa=mfa_hexed,
Пример #26
0
def sha256(string):
    sh = SHA256()
    sh.update(string)
    return sh.digest()
def main(argc, argv):

    # Check for valid input arguments
    if argc != 2:
        raise SystemExit('\nUsage: %s [Input]' % argv[0])

    # Open Syscon Update file
    with open(sys.argv[1], 'rb') as INPUT:

        # Parse Packet Type 1
        data = Header(INPUT)
        fw_version = '0x%08X' % data.FW_VERSION
        hw_info = '0x%08X' % data.HW_INFO
        hw_info_mask = '0x%02X' % ((data.HW_INFO & 0x00F00000) >> 0x10)
        output_filename = 'psvita_syscon_patch_' + hw_info + '_' + fw_version + '.bin'

        # Parse Packet Type 2
        data = Header(INPUT)
        img_size = '0x%02X' % (data.IMG_SIZE)
        fw_type = '0x%02X' % (data.FW_TYPE)

        # Check for valid Update Key
        try:
            if SHA256(uhx(KEYS[hw_info_mask])).hexdigest().upper() != KEY_HASHES[hw_info_mask]:
                raise SystemExit('\nError: Invalid key!')
        except KeyError:
            raise SystemExit('\nError: Unsupported model!')

        # Check for valid Update IV
        try:
            if SHA256(uhx(IVS[hw_info_mask])).hexdigest().upper() != IV_HASHES[hw_info_mask]:
                raise SystemExit('\nError: Invalid IV!')
        except KeyError:
            raise SystemExit('\nError: Unsupported model!')

        # Parse Packet Type 0x10
        header_data = Header(INPUT)
        encrypted_data = bytearray()
        segment_indexes = []

        # Loop through the input file by packets and save the encrypted data to a buffer
        while (header_data.SIZE != 0):
            #debug('')
            #debug('Type           : 0x%X' % header_data.TYPE)
            #debug('Header Size    : 0x%X' % header_data.HEADER_SIZE)
            #debug('Size           : 0x%X' % header_data.SIZE)
            body_data = INPUT.read(header_data.SIZE)
            if header_data.TYPE == 0x10:
                #debug('Segment Number : 0x%X' % header_data.SEGMENT_NO)
                #debug('Segment Size   : 0x%X' % header_data.SEGMENT_SIZE)
                segment_size = header_data.SEGMENT_SIZE
                segment_indexes.append(header_data.SEGMENT_NO)
                encrypted_data.extend(body_data)
            header_data = Header(INPUT)

    # Parse Packet Type 0x20
    hash = header_data.HASH

    # Decrypt the concatenated data
    decrypted_data = aes_decrypt_cbc(KEYS[hw_info_mask], IVS[hw_info_mask], encrypted_data)

    # Check for valid Update data
    if SHA1(decrypted_data).digest() != hash:
        raise SystemExit('\nError: Invalid Update data!')

    # Write decrypted data to a file
    with open(output_filename, 'wb') as OUTPUT:
        # Zero-ify
        OUTPUT.write(b'\0' * 0x100000)
        OUTPUT.seek(0)
		
        # Write
        debug('')
        debug('Offset   | Segment Index')
        decrypted_data_offset = 0
        for segment_no in segment_indexes:
            output_offset = segment_size * segment_no
            OUTPUT.seek(output_offset)
            OUTPUT.write(decrypted_data[decrypted_data_offset : decrypted_data_offset + segment_size])
            debug('0x%06X | 0x%X' % (output_offset, segment_no))
            decrypted_data_offset += segment_size
    print('')
    print('Syscon Update successfully decrypted to ' + output_filename)
Пример #28
0
 def calc_sha256(self):
     if self.sha256 is None:
         self.sha256 = uint256_from_str(SHA256(SHA256(self.serialize()).digest()).digest())
     return self.sha256
Пример #29
0
def setup_db():
    db.drop_all()
    db.create_all()
    # add default users

    # add tester (non-admin account)
    # get tester password from docker secrets:
    # pword = open("/run/secrets/tester_password_data", "r").read().strip()
    pword = 'testpass'
    uname = 'tester'
    # get rid of old password definition -- pword = 'testpass'
    hasher = SHA256()
    # Add password to hash algorithm.
    hasher.update(pword.encode('utf-8'))
    # Generate random salt.
    salt = token_hex(nbytes=16)
    # Add random salt to hash algorithm.
    hasher.update(salt.encode('utf-8'))
    # Get the hex of the hash.
    pword_store = hasher.hexdigest()
    # Add a two factor auth number
    twofa = '5555555555'
    # Is an admin? 0 is no; 1 is yes
    isadm = 0
    # Store the new user in the database.
    new_user = User(uname=uname,
                    pword=pword_store,
                    salt=salt,
                    twofa=twofa,
                    isadm=isadm)
    db.session.add(new_user)
    # Probably want error handling, etc. For this simplified code,
    # we're assuming all is well.
    db.session.commit()

    # add tester2 (non-admin account)
    uname = 'tester5'
    # pword = open("/run/secrets/tester5_password_data", "r").read().strip()
    pword = 'testpass'
    hasher = SHA256()
    # Add password to hash algorithm.
    hasher.update(pword.encode('utf-8'))
    # Generate random salt.
    salt = token_hex(nbytes=16)
    # Add random salt to hash algorithm.
    hasher.update(salt.encode('utf-8'))
    # Get the hex of the hash.
    pword_store = hasher.hexdigest()
    # Add a two factor auth number
    twofa = '2222222222'
    # Is an admin? 0 is no; 1 is yes
    isadm = 0
    # Store the new user in the database.
    new_user = User(uname=uname,
                    pword=pword_store,
                    salt=salt,
                    twofa=twofa,
                    isadm=isadm)
    db.session.add(new_user)
    # Probably want error handling, etc. For this simplified code,
    # we're assuming all is well.
    db.session.commit()

    # add admin (admin account)
    uname = 'admin'
    #pword = open("/run/secrets/admin_password_data", "r").read().strip()
    pword = 'Administrator@1'
    hasher = SHA256()
    # Add password to hash algorithm.
    hasher.update(pword.encode('utf-8'))
    # Generate random salt.
    salt = token_hex(nbytes=16)
    # Add random salt to hash algorithm.
    hasher.update(salt.encode('utf-8'))
    # Get the hex of the hash.
    pword_store = hasher.hexdigest()
    # Add a two factor auth number
    twofa = '12345678901'
    # Is an admin? 0 is no; 1 is yes
    isadm = 1
    # Store the new user in the database.
    new_user = User(uname=uname,
                    pword=pword_store,
                    salt=salt,
                    twofa=twofa,
                    isadm=isadm)
    db.session.add(new_user)
    # Probably want error handling, etc. For this simplified code,
    # we're assuming all is well.
    db.session.commit()

    # create some test query's
    new_query1 = SpellCheck(user_id='tester',
                            input_checked='wrods aer worng1',
                            results='wrods, aer, worng1')
    new_query2 = SpellCheck(user_id='tester',
                            input_checked='wrods aer worng2',
                            results='wrods, aer, worng2')
    new_query3 = SpellCheck(user_id='admin',
                            input_checked='wrods aer worng3',
                            results='wrods, aer, worng3')
    new_query4 = SpellCheck(user_id='tester5',
                            input_checked='wrods aer worng4',
                            results='wrods, aer, worng4')
    new_query5 = SpellCheck(user_id='tester5',
                            input_checked='wrods aer worng5',
                            results='wrods, aer, worng5')
    db.session.add(new_query1)
    db.session.add(new_query2)
    db.session.add(new_query3)
    db.session.add(new_query4)
    db.session.add(new_query5)
    db.session.commit()