Пример #1
0
    def setUp(self):
        self.USER_GNUPGHOME = tempfile.TemporaryDirectory()
        self.ADMIN_GNUPGHOME = tempfile.TemporaryDirectory()
        self.NEW_USER_GNUPGHOME = tempfile.TemporaryDirectory()
        self.NEW_ADMIN_GNUPGHOME = tempfile.TemporaryDirectory()
        self.SEED_DIR = tempfile.TemporaryDirectory()
        self.config = ConfigParser()
        self.config.read_string("""
            [mtls]
            min_lifetime=60
            max_lifetime=0
            seed_dir={seed_dir}

            [ca]
            key = secrets/certs/authority/RootCA.key
            cert = secrets/certs/authority/RootCA.pem
            issuer = My Company Name
            alternate_name = *.myname.com

            [gnupg]
            user={user_gnupghome}
            admin={admin_gnupghome}

            [storage]
            engine=sqlite3

            [storage.sqlite3]
            db_path=:memory:
            """.format(
            user_gnupghome=self.USER_GNUPGHOME.name,
            admin_gnupghome=self.ADMIN_GNUPGHOME.name,
            seed_dir=self.SEED_DIR.name,
        ))
        self.common_name = "user@host"
        self.key = generate_key()
        self.engine = storage.SQLiteStorageEngine(self.config)
        cur = self.engine.conn.cursor()
        cur.execute("DROP TABLE IF EXISTS certs")
        self.engine.conn.commit()
        self.engine.init_db()
        self.cert_processor = CertProcessor(self.config)
        self.user_gpg = gnupg.GPG(gnupghome=self.USER_GNUPGHOME.name)
        self.admin_gpg = gnupg.GPG(gnupghome=self.ADMIN_GNUPGHOME.name)
        self.new_user_gpg = gnupg.GPG(gnupghome=self.NEW_USER_GNUPGHOME.name)
        self.new_admin_gpg = gnupg.GPG(gnupghome=self.NEW_ADMIN_GNUPGHOME.name)
        self.new_users = [
            User("user@host",
                 gen_passwd(),
                 generate_key(),
                 gpg=self.new_user_gpg)
        ]
        self.new_admins = [
            User("admin@host",
                 gen_passwd(),
                 generate_key(),
                 gpg=self.new_admin_gpg)
        ]
Пример #2
0
def add_project_member(prj_id):
    # form = AddProjectMemberForm(request.form)
    # if request.method == 'POST' and form.validate():
    debug_set = current_app.config["DEBUG"]
    if debug_set == True:
        print "\n\n\n==========> account->views.py -> add_project_member() "
    form = AddProjectMemberForm()
    if form.validate_on_submit():
        try:
            # Add new member to project
            proj = Project.get_project_for_projectid(prj_id)
            proj.add_member(name=form.name.data, email=form.email.data, role=Project.ROLE_MEMBER)
            # Create an appkey for the new member

            key = utils.generate_key(settings.APPKEY_LENGTH)
            prjmemkey = ProjectMemberKey(prj_id=proj.prj_id, appkey=key, member_email=form.email.data)
            prjmemkey.save()
            flash("New member has been added.")
            return redirect(url_for(".view_project", prj_id=prj_id))
        except NotUniqueException:
            flash("The member email already exists. Can not add it.", category="error")
            return render_template("add_project_member.html", form=form, prj_id=prj_id)
        else:
            print "Another exception is raised."
    # if method is GET, show a form.
    return render_template("add_project_member.html", form=form, prj_id=prj_id)
Пример #3
0
def peer_auth(name, live=False, cjdroute=False, yrd=False):
    'add a password for inbound connections'

    if '/' in name:
        yield 'nope'
        exit(1)

    path = os.path.join(YRD_PEERS, name)
    if os.path.exists(path):
        with open(path) as f:
            password = json.load(f)['password']
    else:
        password = utils.generate_key(31)

        info = {'type': 'in', 'name': name, 'password': password}

        if not live:
            with open(path, 'w') as f:
                f.write(json.dumps(info))

    conf = utils.load_conf(CJDROUTE_CONF)
    c = cjdns.connect(password=conf['admin']['password'])
    c.addPassword(name, password)
    c.disconnect()

    publicKey = conf['publicKey']
    port = conf['interfaces']['UDPInterface'][0]['bind'].split(':')[1]

    if (not cjdroute and not yrd) or cjdroute:
        yield utils.to_credstr(utils.get_ip(), port, publicKey, password)
    if not cjdroute and not yrd:
        yield ''
    if (not cjdroute and not yrd) or yrd:
        yield 'yrd peer add namehere %s:%s %s %s' % (utils.get_ip(), port,
                                                     publicKey, password)
Пример #4
0
def add_merchant_codes():
    with app.app_context():
        for user in User.all(db.session):
            if not user.merchant_code:
                user.merchant_code = generate_key(4)
                db.session.add(user)
        db.session.commit()
Пример #5
0
def create_project():
    #with lock:
    form = CreateProjectForm(request.form)
    if request.method == 'POST' and form.validate():
        new_proj = Project(prj_name=form.name.data, prj_desc=form.desc.data,
            is_private=form.is_private.data, owner=current_user.get_id())
        print 'project.is_private:', new_proj.is_private
        prj_id = new_proj.save()
        # Add a user as an owner of a project
        proj = Project.get_project_for_projectid(prj_id)
        print 'project.is_private 2:', proj.is_private
        owner_name = current_user.firstname + ' ' + current_user.lastname
        proj.add_member(name=owner_name, email=current_user.get_id(), 
            role=Project.ROLE_OWNER)
        flash("New project has been created.", category='index_page')
        # Generate a project owner's appkey & save it to ProjectMemberKey coll.
        #keygen = KeyGenerator()
        #key = keygen.getkey(APPKEY_LENGTH)
        key = utils.generate_key()
        prjmemkey = ProjectMemberKey(prj_id=proj.prj_id, appkey=key, 
            member_email=proj.owner)
        prjmemkey.save()
        return redirect(url_for('.list_projects'))

    return render_template('create_project.html', form=form)
Пример #6
0
def add_project_member(prj_id):
    form = AddProjectMemberForm(request.form)
    if request.method == 'POST' and form.validate():
        try:
            # Add new member to project
            proj = Project.get_project_for_projectid(prj_id)
            proj.add_member(name=form.name.data, email=form.email.data, 
                role=Project.ROLE_MEMBER)
            # Create an appkey for the new member
            
            key = utils.generate_key(APPKEY_LENGTH)
            prjmemkey = ProjectMemberKey(prj_id=proj.prj_id, appkey=key, 
                member_email=form.email.data)
            prjmemkey.save()
            flash("New member has been added.")
            return redirect(url_for('.view_project', prj_id=prj_id))   
        except NotUniqueException:
            flash("The member email already exists. Can not add it.", 
                category="error")
            return render_template('add_project_member.html', form=form, 
                prj_id=prj_id)
        else:
            print 'Another exception is raised.'
    # if method is GET, show a form.        
    return render_template('add_project_member.html', form=form, prj_id=prj_id)    
Пример #7
0
def create_project():
    # with lock:
    # form = CreateProjectForm(request.form)
    # if request.method == 'POST' and form.validate_on_submit():
    debug_set = current_app.config["DEBUG"]
    if debug_set == True:
        print "\n\n\n==========> account->views.py -> create_project() "
        # print "=====> is_private() :", form.is_private.data

    form = CreateProjectForm()
    if form.validate_on_submit():
        new_proj = Project(
            prj_name=form.name.data,
            prj_desc=form.desc.data,
            is_private=form.is_private.data,
            owner=current_user.get_id(),
        )
        prj_id = new_proj.save()
        # Add a user as an owner of a project
        proj = Project.get_project_for_projectid(prj_id)
        print "project.is_private 2:", proj.is_private
        owner_name = current_user.firstname + " " + current_user.lastname
        proj.add_member(name=owner_name, email=current_user.get_id(), role=Project.ROLE_OWNER)
        flash("New project has been created.", category="index_page")
        # Generate a project owner's appkey & save it to ProjectMemberKey coll.
        # keygen = KeyGenerator()
        # key = keygen.getkey(settings.APPKEY_LENGTH)
        key = utils.generate_key()
        prjmemkey = ProjectMemberKey(prj_id=proj.prj_id, appkey=key, member_email=proj.owner)
        prjmemkey.save()
        return redirect(url_for(".list_projects"))

    return render_template("create_project.html", form=form)
Пример #8
0
 def save(self, commit=True):
     model = super(ApiKeyModelForm, self).save(commit=False)
     if self.generate_key:
         model.key = generate_key(model.user.email)
     if commit:
         model.save()
     return model
Пример #9
0
    def setUp(self):
        self.USER_GNUPGHOME = tempfile.TemporaryDirectory()
        self.ADMIN_GNUPGHOME = tempfile.TemporaryDirectory()
        self.NEW_USER_GNUPGHOME = tempfile.TemporaryDirectory()
        self.NEW_ADMIN_GNUPGHOME = tempfile.TemporaryDirectory()
        self.SEED_DIR = tempfile.TemporaryDirectory()
        self.config = ConfigParser()
        self.config.read_string("""
            [mtls]
            min_lifetime=60
            max_lifetime=0
            seed_dir={seed_dir}

            [ca]
            key = secrets/certs/authority/RootCA.key
            cert = secrets/certs/authority/RootCA.pem
            issuer = My Company Name
            alternate_name = *.myname.com

            [gnupg]
            user={user_gnupghome}
            admin={admin_gnupghome}

            [storage]
            engine=sqlite3

            [storage.sqlite3]
            db_path=:memory:
            """.format(
            seed_dir=self.SEED_DIR.name,
            user_gnupghome=self.USER_GNUPGHOME.name,
            admin_gnupghome=self.ADMIN_GNUPGHOME.name,
        ))
        self.new_user_gpg = gnupg.GPG(gnupghome=self.NEW_USER_GNUPGHOME.name)
        self.new_admin_gpg = gnupg.GPG(gnupghome=self.NEW_ADMIN_GNUPGHOME.name)
        self.new_users = [
            User("user@host",
                 gen_passwd(),
                 generate_key(),
                 gpg=self.new_user_gpg)
        ]
        self.new_admins = [
            User("admin@host",
                 gen_passwd(),
                 generate_key(),
                 gpg=self.new_admin_gpg)
        ]
Пример #10
0
def generate_newappkey(prj_id, member_email):
    debug_set = current_app.config["DEBUG"]
    if debug_set == True:
        print "\n\n\n==========> account->views.py -> generate_newappkey() "
    key = utils.generate_key(settings.APPKEY_LENGTH)
    prjmemkey = ProjectMemberKey(prj_id=prj_id, member_email=member_email, appkey=key)
    prjmemkey.save()
    return redirect(url_for(".view_project", prj_id=prj_id))
Пример #11
0
    def setUp(self):
        self.USER_GNUPGHOME = tempfile.TemporaryDirectory()
        self.ADMIN_GNUPGHOME = tempfile.TemporaryDirectory()
        self.AUTHORITY_FOLDER = tempfile.TemporaryDirectory()
        self.FQDN = "my.test.server"
        self.fqdn_patch = patch.dict("os.environ", {"FQDN": self.FQDN})
        self.fqdn_patch.start()
        config = ConfigParser()
        config.read_string(
            """
            [ca]
            key = {authority_folder}/RootCA.key
            cert = {authority_folder}/RootCA.pem
            issuer = My Company Name
            alternate_name = *.myname.com

            [gnupg]
            user={user_gnupghome}
            admin={admin_gnupghome}

            [storage]
            engine=sqlite3

            [storage.sqlite3]
            db_path=:memory:
            """.format(
                user_gnupghome=self.USER_GNUPGHOME.name,
                admin_gnupghome=self.ADMIN_GNUPGHOME.name,
                authority_folder=self.AUTHORITY_FOLDER.name,
            )
        )
        self.common_name = "user@host"
        self.key = generate_key()
        self.engine = storage.SQLiteStorageEngine(config)
        cur = self.engine.conn.cursor()
        cur.execute("DROP TABLE IF EXISTS certs")
        self.engine.conn.commit()
        self.engine.init_db()
        self.cert_processor = CertProcessor(config)
        self.user_gpg = gnupg.GPG(gnupghome=self.USER_GNUPGHOME.name)
        self.admin_gpg = gnupg.GPG(gnupghome=self.ADMIN_GNUPGHOME.name)
        self.users = [
            User("*****@*****.**", gen_passwd(), generate_key(), gpg=self.user_gpg)
        ]
        for user in self.users:
            self.user_gpg.import_keys(self.user_gpg.export_keys(user.fingerprint))
Пример #12
0
def profile_for(email_addr: str) -> (str, bytes):
    assert type(email_addr) == str
    email_addr = email_addr.strip("&").strip("=")
    uid = 10
    role = "user"
    key = generate_key()
    profile = parse_profile(f"email={email_addr}&uid={uid}&role={role}")
    a = AES.new(key, AES.MODE_ECB)
    return key, a.encrypt(pad(bytes(unparse_profile(profile), "utf-8")))
Пример #13
0
 def __init__(self, user, bank, amount, settlement_address, amount_receive):
     self.date = datetime.datetime.now()
     self.user = user
     self.token = generate_key(4)
     self.bank = bank
     self.amount = amount
     self.settlement_address = settlement_address
     self.amount_receive = amount_receive
     self.txid = None
     self.status = Settlement.STATE_CREATED
Пример #14
0
 def __init__(self, proposal, mobile, email, wallet_address, message,
              amount):
     self.proposal = proposal
     self.token = generate_key(8)
     self.mobile = mobile
     self.email = email
     self.wallet_address = wallet_address
     self.message = message
     self.amount = amount
     self.status = self.STATE_CREATED
     self.txid = None
Пример #15
0
 def __init__(self, proposal, mobile, email, recipient, message, amount):
     assert amount > 0
     self.proposal = proposal
     self.token = generate_key(8)
     self.mobile = mobile
     self.email = email
     self.recipient = recipient
     self.message = message
     self.amount = amount
     self.status = self.STATE_CREATED
     self.txid = None
Пример #16
0
def init_db():
    db.connect(reuse_if_open=True)
    db.create_tables([File, FileState, User])
    FileState.create(state="Загружается", r_accessible=False)
    FileState.create(state="Загружен")
    FileState.create(state="Кодируется", r_accessible=False)
    FileState.create(state="Закодирован")
    FileState.create(state="Удален", r_accessible=False, d_accessible=False)
    pkey = generate_key()
    u = User.create(auth_token=uuid4(), pkey=pkey)
    app.logger.info("First user: %s" % u.auth_token)
    db.commit()
Пример #17
0
def wrbt_confirm(name, url):
    'confirm a peering request'
    import wrbt
    request = wrbt.decode(url)

    conf = utils.load_conf(CJDROUTE_CONF, CJDROUTE_BIN)

    host = utils.get_ip()
    port = conf['interfaces']['UDPInterface'][0]['bind'].split(':')[1]
    publicKey = conf['publicKey']
    password = utils.generate_key(31)

    # TODO: authorize

    yield wrbt.confirm(request, (host, port), publicKey, password)
Пример #18
0
    def setUp(self):
        self.USER_GNUPGHOME = tempfile.TemporaryDirectory()
        self.ADMIN_GNUPGHOME = tempfile.TemporaryDirectory()
        config = ConfigParser()
        config.read_string(
            """
            [ca]
            key = secrets/certs/authority/RootCA.key
            cert = secrets/certs/authority/RootCA.pem
            issuer = My Company Name
            alternate_name = *.myname.com

            [gnupg]
            user={user_gnupghome}
            admin={admin_gnupghome}

            [storage]
            engine=postgres

            [storage.postgres]
            database = mtls
            user = postgres
            password = postgres
            host = localhost
            """.format(
                user_gnupghome=self.USER_GNUPGHOME.name,
                admin_gnupghome=self.ADMIN_GNUPGHOME.name,
            )
        )
        self.common_name = "user@host"
        self.key = generate_key()
        self.engine = storage.PostgresqlStorageEngine(config)
        cur = self.engine.conn.cursor()
        cur.execute("DROP TABLE IF EXISTS certs")
        self.engine.conn.commit()
        self.engine.init_db()

        self.cert_processor = CertProcessor(config)
        self.user_gpg = gnupg.GPG(gnupghome=self.USER_GNUPGHOME.name)
        self.admin_gpg = gnupg.GPG(gnupghome=self.ADMIN_GNUPGHOME.name)
        self.users = [
            User("user@host", gen_passwd(), generate_key(), gpg=self.user_gpg),
            User("user2@host", gen_passwd(), generate_key(), gpg=self.user_gpg),
            User("user3@host", gen_passwd(), generate_key(), gpg=self.user_gpg),
        ]
        self.invalid_users = [
            User("user4@host", gen_passwd(), generate_key(), gpg=self.user_gpg)
        ]
        self.admin_users = [
            User("admin@host", gen_passwd(), generate_key(), gpg=self.admin_gpg)
        ]
        for user in self.users:
            self.user_gpg.import_keys(self.user_gpg.export_keys(user.fingerprint))
        for user in self.admin_users:
            self.admin_gpg.import_keys(self.admin_gpg.export_keys(user.fingerprint))
Пример #19
0
 def last_view(self, name, surname):
     key = generate_key(name, surname)
     with HistorySession() as manager:
         history = manager.read(key)
         last_found_id = history['found_ids'][-1]
     with FoundsSession() as manager:
         found = manager.read(last_found_id)
     with FacesDatabase() as manager:
         face = manager.read(found['face_id'])
     with PersonsDatabase() as manager:
         person = manager.read(face['person_id'])
     return {
         'person': person,
         'found': found,
         'face': face,
     }
Пример #20
0
 def response_change(self,request,object):
     msg = _('The local key was re-generated successfully.')
     if "_regen_key" in request.POST:
         
         object.local_key = generate_key()
         object.save()
         self.message_user(request, msg)
         if "_popup" in request.REQUEST:
             return HttpResponseRedirect(request.path + "?_popup=1")
         else:
             return HttpResponseRedirect(request.path)
     elif '_test' in request.POST:
         if push_test_batch():
             messages.info(request, "It works! Communication with remote server was successful.")
         else:
             messages.error(request, "Pushing a test batch failed-- please see a system administrator")
     return super(SettingsAdmin, self).response_change(request,object)
Пример #21
0
    def setUp(self):
        dir_path = os.path.dirname(os.path.realpath(__file__))
        self.USER_GNUPGHOME = tempfile.TemporaryDirectory(prefix=dir_path + "/secrets/")
        self.ADMIN_GNUPGHOME = tempfile.TemporaryDirectory(prefix=dir_path + "/secrets/")
        relative_user = "******" + self.USER_GNUPGHOME.name.split(dir_path)[1]
        relative_admin = "." + self.ADMIN_GNUPGHOME.name.split(dir_path)[1]
        config = ConfigParser()
        config.read_string(
            """
            [ca]
            key = secrets/certs/authority/RootCA.key
            cert = secrets/certs/authority/RootCA.pem
            issuer = My Company Name
            alternate_name = *.myname.com

            [gnupg]
            user={user_gnupghome}
            admin={admin_gnupghome}

            [storage]
            engine=sqlite3

            [storage.sqlite3]
            db_path=:memory:
            """.format(
                user_gnupghome=relative_user, admin_gnupghome=relative_admin
            )
        )
        self.common_name = "user@host"
        self.key = generate_key()
        self.engine = storage.SQLiteStorageEngine(config)
        cur = self.engine.conn.cursor()
        cur.execute("DROP TABLE IF EXISTS certs")
        self.engine.conn.commit()
        self.engine.init_db()
        self.cert_processor = CertProcessor(config)
        self.user_gpg = gnupg.GPG(gnupghome=self.USER_GNUPGHOME.name)
        self.admin_gpg = gnupg.GPG(gnupghome=self.ADMIN_GNUPGHOME.name)
        self.users = [
            User("user@host", gen_passwd(), generate_key(), gpg=self.user_gpg),
            User("user2@host", gen_passwd(), generate_key(), gpg=self.user_gpg),
            User("user3@host", gen_passwd(), generate_key(), gpg=self.user_gpg),
        ]
        self.invalid_users = [
            User("user4@host", gen_passwd(), generate_key(), gpg=self.user_gpg)
        ]
        self.admin_users = [
            User("admin@host", gen_passwd(), generate_key(), gpg=self.admin_gpg)
        ]
        for user in self.users:
            self.user_gpg.import_keys(self.user_gpg.export_keys(user.fingerprint))
        for user in self.admin_users:
            self.admin_gpg.import_keys(self.admin_gpg.export_keys(user.fingerprint))
Пример #22
0
def register(request):
    '''
    Shows a registration page for users to register new applications
    '''
    if request.method == 'GET':
        f = ConsumerRegisterForm()
        return render_to_response('register.html', {'form':f}, context_instance=RequestContext(request))
    
    form  = ConsumerRegisterForm(request.POST)
    if form.is_valid():
        f  = form.save(commit=False)
        f.user = request.user
        f.key = utils.generate_key()
        f.secret = utils.generate_secret()
        f.save()
    else:
        return render_to_response('register.html', {'form':form}, context_instance=RequestContext(request))
    
    return HttpResponseRedirect('/api/applications/')
Пример #23
0
def register_user(request):
    if request.user.is_authenticated():
        return redirect(HOME_URL)

    state = "Please register"

    reg_form = RegistrationForm(request.POST or None)
    pass_form = SetPasswordForm(request.user, request.POST or None)
    temp1 = reg_form.is_valid()     # prevent short circuit
    temp2 = pass_form.is_valid()    # prevent short circuit
    if temp1 and temp2:
        d = dict(
            reg_form.cleaned_data.items() + pass_form.cleaned_data.items()
        )

        new_user = get_user_model().objects.create_user(d["username"],
                                                        d["email"],
                                                        d["new_password1"])
        new_user.is_active = False

        activation_key = utils.generate_key(d["username"])
        new_user.activation_key = activation_key
        keypair = utils.generate_key_pair(d["username"])
        new_user.public_key = keypair["public"]
        new_user.private_key = keypair["private"]

        new_user.save()
        logger.info("New user '%s' registered." % new_user.username)
        c = {
            "key": activation_key,
        }
        return render(request, "account/post_register.html", c)

    c = {
        "state": state,
        "reg_form": reg_form,
        "pass_form": pass_form,
    }
    return render(request, "account/register.html", c)
Пример #24
0
def register_user(request):
    if request.user.is_authenticated():
        return redirect(HOME_URL)

    state = "Please register"

    reg_form = RegistrationForm(request.POST or None)
    pass_form = SetPasswordForm(request.user, request.POST or None)
    temp1 = reg_form.is_valid()  # prevent short circuit
    temp2 = pass_form.is_valid()  # prevent short circuit
    if temp1 and temp2:
        d = dict(reg_form.cleaned_data.items() +
                 pass_form.cleaned_data.items())

        new_user = get_user_model().objects.create_user(
            d["username"], d["email"], d["new_password1"])
        new_user.is_active = False

        activation_key = utils.generate_key(d["username"])
        new_user.activation_key = activation_key
        keypair = utils.generate_key_pair(d["username"])
        new_user.public_key = keypair["public"]
        new_user.private_key = keypair["private"]

        new_user.save()
        logger.info("New user '%s' registered." % new_user.username)
        c = {
            "key": activation_key,
        }
        return render(request, "account/post_register.html", c)

    c = {
        "state": state,
        "reg_form": reg_form,
        "pass_form": pass_form,
    }
    return render(request, "account/register.html", c)
Пример #25
0
                -0.05753206, 0.20200214, -0.03205916, 0.09661192, 0.01162372,
                0.04892446, -0.07492174, 0.05936784, -0.13485461, -0.01149346,
                0.01463353, -0.00378702, 0.08008318, 0.12226085, -0.15904135,
                0.14667791, 0.05253032, 0.02490245, 0.0747448, 0.06177796,
                -0.10587548, -0.080835, 0.07810656, -0.28147438, 0.17082673,
                0.15265331, 0.08263268, 0.15049241, 0.09658341, 0.08624546,
                0.03394255, -0.01679912, -0.18509068, -0.01626917, 0.09690015,
                -0.01231677, 0.10738206, -0.02170994
            ])
        ],
    },
]

with PersonsDatabase() as manager:
    for person in data:
        key = generate_key(person['name'], person['surname'])
        manager.create(key, {
            'name': person['name'],
            'surname': person['surname'],
        })

with FacesDatabase() as manager:
    for person in data:
        key = generate_key(person['name'], person['surname'])
        counter = 0
        for face in person['faces']:
            counter += 1
            manager.create(key + str(counter), {
                'person_id': key,
                'encoding': face,
                'updated': datetime.now()
Пример #26
0
""" 
set 3 challenge 17: the CBC padding oracle, or Vaudenay's attack.
Generate a random AES key (which it should save for all future encryptions), 
pad the string out to the 16-byte AES block size and CBC-encrypt it under that key, providing the caller the ciphertext and IV.
"""

from base64 import b64decode
from Crypto.Cipher import AES
from random import choice
from secrets import token_bytes
from utils import BLOCK_SIZE, generate_key, generate_IV, pad, depad, InvalidPaddingError, FailedDecryptionError, make_chunks
# from targets import cbc_oracle

key, IV = generate_key(), generate_IV()

def cbc_oracle(ciphertxt):
    d = AES.new(key, AES.MODE_CBC, IV)
    try:
        depad(d.decrypt(ciphertxt))
        return True
    except InvalidPaddingError:
        return False

def make_pad(intermediate: bytes) -> bytes:
    pad = bytes()
    l = len(intermediate) + 1
    for i in intermediate[::-1]:
        pad = bytes([l ^ int(i)]) + pad
    #print(f"padded {intermediate} to {pad}")
    return pad
Пример #27
0
import utils
import gui

utils.generate_key()
data_file = "data.json"
utils.check_file(data_file)


def login_variable(var):
    global login_entry_variable
    login_entry_variable = var


def password_variable(var):
    global password_entry_variable
    password_entry_variable = var


def register_login_variable(var):
    global login_register_entry_variable
    login_register_entry_variable = var


def register_password_variable(var):
    global password_register_entry_variable
    password_register_entry_variable = var


def register_repassword_variable(var):
    global repassword_register_entry_variable
    repassword_register_entry_variable = var
Пример #28
0
 def on_admin_created(self):
     self.merchant_code = generate_key(4)
     self.password = encrypt_password(generate_random_password(16))
     self.confirmed_at = datetime.datetime.now()
     self.active = True
Пример #29
0
    def setUp(self):
        self.USER_GNUPGHOME = tempfile.TemporaryDirectory()
        self.ADMIN_GNUPGHOME = tempfile.TemporaryDirectory()
        self.INVALID_GNUPGHOME = tempfile.TemporaryDirectory()
        self.NEW_USER_GNUPGHOME = tempfile.TemporaryDirectory()
        self.config = ConfigParser()
        self.config.read_string("""
            [mtls]
            min_lifetime=60
            max_lifetime=0

            [ca]
            key = secrets/certs/authority/RootCA.key
            cert = secrets/certs/authority/RootCA.pem
            issuer = My Company Name
            alternate_name = *.myname.com

            [gnupg]
            user={user_gnupghome}
            admin={admin_gnupghome}

            [storage]
            engine=sqlite3

            [storage.sqlite3]
            db_path=:memory:
            """.format(
            user_gnupghome=self.USER_GNUPGHOME.name,
            admin_gnupghome=self.ADMIN_GNUPGHOME.name,
        ))
        self.key = generate_key()
        self.engine = storage.SQLiteStorageEngine(self.config)
        cur = self.engine.conn.cursor()
        cur.execute("DROP TABLE IF EXISTS certs")
        self.engine.conn.commit()
        self.engine.init_db()
        self.user_gpg = gnupg.GPG(gnupghome=self.USER_GNUPGHOME.name)
        self.admin_gpg = gnupg.GPG(gnupghome=self.ADMIN_GNUPGHOME.name)
        self.invalid_gpg = gnupg.GPG(gnupghome=self.INVALID_GNUPGHOME.name)
        self.new_user_gpg = gnupg.GPG(gnupghome=self.NEW_USER_GNUPGHOME.name)
        app = create_app(self.config)
        self.app = app.test_client()
        self.users = [
            User("user@host", gen_passwd(), generate_key(), gpg=self.user_gpg),
            User("user2@host", gen_passwd(), generate_key(),
                 gpg=self.user_gpg),
            User("user3@host", gen_passwd(), generate_key(),
                 gpg=self.user_gpg),
        ]
        self.invalid_users = [
            User("user4@host",
                 gen_passwd(),
                 generate_key(),
                 gpg=self.invalid_gpg)
        ]
        self.admin_users = [
            User("admin@host",
                 gen_passwd(),
                 generate_key(),
                 gpg=self.admin_gpg)
        ]
        self.new_users = [
            User("newuser@host",
                 gen_passwd(),
                 generate_key(),
                 gpg=self.new_user_gpg),
            User("newuser2@host",
                 gen_passwd(),
                 generate_key(),
                 gpg=self.new_user_gpg),
        ]
        for user in self.users:
            self.user_gpg.import_keys(
                self.user_gpg.export_keys(user.fingerprint))
            self.user_gpg.trust_keys([user.fingerprint], "TRUST_ULTIMATE")
        for user in self.admin_users:
            # Import to admin keychain
            self.admin_gpg.import_keys(
                self.admin_gpg.export_keys(user.fingerprint))
            self.admin_gpg.trust_keys([user.fingerprint], "TRUST_ULTIMATE")
            # Import to user keychain
            self.user_gpg.import_keys(
                self.admin_gpg.export_keys(user.fingerprint))
            self.user_gpg.trust_keys([user.fingerprint], "TRUST_ULTIMATE")
        for user in self.invalid_users:
            self.invalid_gpg.import_keys(
                self.invalid_gpg.export_keys(user.fingerprint))
            self.invalid_gpg.trust_keys([user.fingerprint], "TRUST_ULTIMATE")
        for user in self.new_users:
            self.new_user_gpg.import_keys(
                self.new_user_gpg.export_keys(user.fingerprint))
            self.new_user_gpg.trust_keys([user.fingerprint], "TRUST_ULTIMATE")
Пример #30
0
def cbc(plaintxt):
    #print(f"encrypting... {plaintxt}")
    return cbc_mode(plaintxt, generate_key(), generate_IV())
Пример #31
0
 def test_generate_key(self):
     self.assertIsNotNone(utils.generate_key("some string"))
Пример #32
0
 def generate_defaults(self):
     self.user = current_user
     self.token = generate_key(4)
Пример #33
0
 def generate_defaults(self):
     self.user = current_user
     self.date = datetime.datetime.now()
     self.token = generate_key(8)
     self.nonce = 0
     self.secret = generate_key(16)
Пример #34
0
 def generate_sessionid(self):
     # TODO set salt
     return generate_key(salt='')
Пример #35
0
 def generate_sessionid(self):
     # TODO set salt
     return generate_key(salt='')
Пример #36
0
"""
set 2 challenge 16: CBC bitflipping attacks (from https://cryptopals.com/sets/2/challenges/16)

"""

from Crypto.Cipher import AES
from utils import BLOCK_SIZE, generate_key, generate_IV, pad

key = generate_key()
IV = generate_IV()
a, b = AES.new(key, AES.MODE_CBC, IV), AES.new(key, AES.MODE_CBC, IV)

def surrounded_CBC(msg):
    prefix = "comment1=cooking%20MCs;userdata="
    postfix = ";comment2=%20like%20a%20pound%20of%20bacon"
    msg = prefix.replace(";","").replace("=","") + msg.replace(";","").replace("=","") + postfix.replace(";","").replace("=","")
    return a.encrypt(pad(bytes(msg, encoding="utf-8")))

def bitflip_cbc():
    ciphertext = surrounded_CBC("   " + "admin" + chr(0) + "true")
    target = b.decrypt(ciphertext).index(b"admin") + 5 - BLOCK_SIZE
    ciphertext = ciphertext[0:target] + bytes([ciphertext[target] ^ ord("=")]) + ciphertext[target+1:]
    new_plaintxt = "".join([chr(i) for i in b.decrypt(ciphertext)])
    return "admin=true" in new_plaintxt

if __name__ == "__main__":
    print(bitflip_cbc())
Пример #37
0
 def test_generate_key(self):
     self.assertIsNotNone(utils.generate_key("some string"))
Пример #38
0
 def __init__(self, **kwargs):
     self.merchant_code = generate_key(4)
     super().__init__(**kwargs)
Пример #39
0
def generate_newappkey(prj_id, member_email):
    key = utils.generate_key(APPKEY_LENGTH)
    prjmemkey = ProjectMemberKey(prj_id=prj_id, member_email=member_email,
        appkey=key)
    prjmemkey.save()
    return redirect(url_for('.view_project', prj_id=prj_id))  
Пример #40
0
def ecb(plaintxt):
    #print(f"encrypting... {plaintxt}")
    a = AES.new(generate_key(), AES.MODE_ECB)
    return a.encrypt(pad(plaintxt))
Пример #41
0
from django.conf import settings
from django.conf.urls.defaults import patterns, url, include
from django.contrib.sites.models import get_current_site
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponseRedirect

from paypal.standard.forms import PayPalPaymentsForm
from paypal.standard.ipn.signals import payment_was_successful as success_signal
from shop import order_signals
from shop.models import Order

from utils import generate_key
IPN_RETURN_KEY = generate_key(96, 1024)

import logging
logger = logging.getLogger('paypal')

class OffsitePaypalBackend(object):
    '''
    Glue code to let django-SHOP talk to django-paypal's.

    The django-paypal package already defines an IPN view, that logs everything
    to the database (desirable), and fires up a signal.
    It is therefore more convenient to listen to the signal instead of rewriting
    the ipn view (and necessary tests)
    '''

    backend_name = "Paypal"
Пример #42
0
    def client_init(self):

        # Sending message with message_type, client nonce and chosen  cipher, with fields separated
        # by the carachter '|'

        message_type = 'ClientInit'
        self.generate_client_nonce()
        self.clientinit = message_type + '|' + self.client_nonce + '|' + self.cipher


        self.server_connection.send(self.clientinit)




        # ---------------------------------------------------------------------------------------------------




        # Receiving the first response from the server
        self.serverinit = self.server_connection.recv(8192) # Should be enough to receive all the data

        print '-------------------------------\n'
        print self.serverinit
        print '\n-------------------------------'


        response_splitted = self.serverinit.split('|')

        # We check if it is the expected message type and if the server
        # acknowledged our cipher

        if not response_splitted[0] == 'ServerInit' or not response_splitted[2] == self.cipher:
            print 'Invalid response type, %s' % self.serverinit
            self.server_connection.close()
            return

        self.server_certificate = response_splitted[3]
        if not self.certificate_is_valid(self.server_certificate):
            print 'Invalid certificate'
            self.server_connection.close()
            raise Exception('Invalid server certificate')

        # Checking if the server requires client authentication
        try:
            if response_splitted[4] == 'CertReq':
                self.server_requires_authentication = True
        except IndexError:
            pass

        self.server_nonce = response_splitted[1]
        pre_master_secret = utils.generate_key(bytes=48)

        # Generating the 2 keys (for encryption and mac)
        key_1_payload = binascii.unhexlify(self.client_nonce + self.server_nonce + '00000000')
        key_2_payload = binascii.unhexlify(self.client_nonce + self.server_nonce + '11111111')
        self.key_1 = utils.create_hmac(pre_master_secret, key_1_payload)
        self.key_2 = utils.create_hmac(pre_master_secret, key_2_payload)




        # The control message is like this:
        # ClientInit| nc|AES-CBC-128-HMAC-SHA1|ServerInit|ns|Certs [|CertReq])
        # We remove the cipher from the server msg since it's already in the client one

        message_control = utils.create_hmac(
            self.key_2,
            self.clientinit + self.serverinit.replace( '|' + self.cipher, '')
            )

        # Sending to the server the PMS, mac of messages and optional client certificate

        server_public_key = utils.read_pubkey_from_pem(self.server_certificate)
        rsa_encrypted_pms = utils.encrypt_rsa(server_public_key, pre_master_secret)

        message_for_server = 'ClientKex' + '|' + rsa_encrypted_pms + '|' + message_control

        signed_nonce = ''

        if self.server_requires_authentication:

            with open (self.client_certificate, 'r') as client_certificate:
                client_certificate_data=client_certificate.read()
            message_for_server = message_for_server + '|' + client_certificate_data

            # I send the signed server nonce to the server so he can verify it

            signed_nonce = utils.sign_rsa(self.client_private_key, self.server_nonce + rsa_encrypted_pms)

            message_for_server = message_for_server + '|' + signed_nonce


        self.server_connection.send(message_for_server)






        # -------------------------------------------------------------------------------------------------------------------





        # Receiving last message of handshake

        server_response = self.server_connection.recv(8192)

        print '-------------------------------\n'
        print server_response
        print '\n-------------------------------'

        # If the message checksum send from the server is equals to ours,
        # the handshake is finally terminated!

        if signed_nonce!='':
            expected_verification_messages = utils.create_hmac(self.key_2, message_for_server.replace('|' + signed_nonce, ''))
        else:
            expected_verification_messages = utils.create_hmac(self.key_2, message_for_server)

        if server_response == expected_verification_messages:
            
            self.handshake_done = True

        else:

            raise Exception('Detected some problems with verification of messages')