コード例 #1
0
 def insert_default_users(self, users):
     self.logger.debug('setting up default users')
     admin_user = {
         "uid": "xprdb_admin",
         "firstName": "Xpresso",
         "lastName": "Admin",
         "pwd": sha512_crypt.hash('xprdb@Abz00ba'),
         "email": "*****@*****.**",
         "primaryRole": "Admin",
         "activationStatus": True,
         "loginStatus": False
     }
     users.insert_one(admin_user)
     superuser = {
         "uid": "superuser1",
         "firstName": "superuser1",
         "lastName": "superuser1",
         "pwd": sha512_crypt.hash('superuser1'),
         "email": "*****@*****.**",
         "primaryRole": "Su",
         "activationStatus": True,
         "loginStatus": False
     }
     users.insert_one(superuser)
     admin1_user = {
         "uid": "admin1",
         "firstName": "admin1",
         "lastName": "admin1",
         "pwd": sha512_crypt.hash('admin1'),
         "email": "*****@*****.**",
         "primaryRole": "Admin",
         "activationStatus": True,
         "loginStatus": False
     }
     users.insert_one(admin1_user)
コード例 #2
0
def compute_uhash(count):
    """Generate linux system user couple of clear/hashes passwords (SHA512)"""
    result = dict()
    for i in _compute_clear_passwordlist(count):
        hashed = sha512_crypt.hash(i)
        if sha512_crypt.verify(i, hashed):
            result[sha512_crypt.hash(i)] = i
    return compute_markdown_rendering(1, result)
コード例 #3
0
def generate(switch, model_id):
  model = config.models[model_id]

  mgmt, vlanid = parse_metadata(switch)
  if mgmt is None:
    raise Exception("The switch " + switch + " was not found in ipplan")
  if radius is None:
    raise Exception("Radius key not set")
  if username is None:
    raise Exception("Username not set")
  if password is None:
    raise Exception("User-password not set")
  if enable is None:
    raise Exception("Enable password not set")
  if snmp_ro is None:
    raise Exception("SNMP ro not set")
  if snmp_salt is None:
    raise Exception("SNMP salt not set")

  #
  # Template function definition
  #
  cfg = tempita.Template(open(model.template).read())
  cfg_subbed = cfg.substitute(
            hostname=switch,
            model=model,
            mgmt_ip=mgmt['ip'],
            mgmt_mask=mgmt['mask'],
            mgmt_mask_cidr=mgmt['mask_cidr'],
            mgmt_gw=mgmt['gw'],
            mgmt_vlanid=mgmt['vlanid'],
            vlanid=vlanid,
            wifi_switches=config.wifi_switches,
            wifi_vlanid=config.wifi_vlanid,
            password=config.password,
            password_sha512=sha512_crypt.hash(config.password),
            enable=config.enable,
            enable_sha512=sha512_crypt.hash(config.enable),
            radius=config.radius,
            snmp_ro=config.snmp_ro,
            snmp_rw=hashlib.sha1((config.snmp_salt + mgmt['ip']).encode()).hexdigest(),
            ipplan_host=lambda h: ipplan_host(h),
            ipplan_pkg=lambda p: ipplan_package(p),
#           snmp_user=config.snmp_user,
#           snmp_auth=config.snmp_auth,
#           snmp_priv=config.snmp_priv
            )
  # We make the Juniper config a script, to be able to add the crontab.
  if "Juniper" in model_id:
    jcfg = tempita.Template(open(os.path.join(os.path.dirname(sys.argv[0]), 'juniper.sh.template')).read())
    cfg_subbed = jcfg.substitute(config=cfg_subbed)
  return cfg_subbed
コード例 #4
0
ファイル: test_legacy.py プロジェクト: cprovencher/dcos-e2e
    def test_enterprise(
        self,
        cluster_backend: ClusterBackend,
        enterprise_1_9_installer: Path,
    ) -> None:
        """
        A DC/OS Enterprise 1.9 cluster can be started.
        """
        superuser_username = str(uuid.uuid4())
        superuser_password = str(uuid.uuid4())
        config = {
            'superuser_username': superuser_username,
            'superuser_password_hash': sha512_crypt.hash(superuser_password),
        }

        with Cluster(cluster_backend=cluster_backend) as cluster:
            cluster.install_dcos_from_path(
                dcos_installer=enterprise_1_9_installer,
                dcos_config={
                    **cluster.base_config,
                    **config,
                },
                output=Output.CAPTURE,
                ip_detect_path=cluster_backend.ip_detect_path,
            )
            cluster.wait_for_dcos_ee(
                superuser_username=superuser_username,
                superuser_password=superuser_password,
            )
コード例 #5
0
def update_password(username: str, password: str, new_password: str,
                    salt: str) -> User:
    """
    Update a user's password.

    :param username: The user's username.
    :type username: str
    :param password: The user's current password.
    :type password: str
    :param new_password: The user's new password.
    :type new_password: str
    :param salt: The user's salt.
    :type salt: str
    :return: User
    """
    user = User.query.filter(User.username == username).one()

    if sha512_crypt.verify(salt_password(password, salt), user.password):
        user.password = sha512_crypt.hash(salt_password(new_password, salt))
        db.session.add(user)
        db.session.commit()

        return user
    else:
        raise PasswordException(message='Current password is not correct.')
コード例 #6
0
    def test_run_pytest(
        self,
        cluster_backend: ClusterBackend,
        enterprise_artifact: Path,
    ) -> None:
        """
        Integration tests can be run with `pytest`.
        Errors are raised from `pytest`.
        """
        superuser_username = str(uuid.uuid4())
        superuser_password = str(uuid.uuid4())
        extra_config = {
            'superuser_username': superuser_username,
            'superuser_password_hash': sha512_crypt.hash(superuser_password),
        }

        with Cluster(
                generate_config_path=enterprise_artifact,
                cluster_backend=cluster_backend,
                extra_config=extra_config,
                log_output_live=True,
        ) as cluster:
            # No error is raised with a successful command.
            cluster.run_integration_tests(
                pytest_command=['pytest', '-vvv', '-s', '-x', 'test_tls.py'],
                env={
                    'DCOS_LOGIN_UNAME': superuser_username,
                    'DCOS_LOGIN_PW': superuser_password,
                },
            )
コード例 #7
0
ファイル: app.py プロジェクト: ramstar3000/Cheat-Sheet
def register():
    if request.method == 'POST':
        name = request.form.get("name")
        username = request.form.get("username")
        password = request.form.get("password")
        confirm = request.form.get("confirm")
        users = mongo.db.Credentials.find({})
        for item in users:
            if item["User"] == username:
                val = render_template(
                    "Error.html",
                    message="This username already exists please choose another"
                )
                return render_template("Error.html", message="Bad username")
            else:
                pass
        secure_password = sha512_crypt.hash(str(password))
        creds = {
            "Name": name,
            "User": username,
            "Pass": secure_password,
            "Admin": False
        }
        if password == confirm:
            mongo.db.Credentials.insert_one(creds)
            return redirect(url_for('index'))
        else:
            return render_template("Error.html", message="Oh No!!!!")

    else:
        return render_template("Registration.html")
コード例 #8
0
ファイル: fixtures.py プロジェクト: opennode/waldur-ansible
 def jupyter_hub_whitelisted_user(self):
     return factories.JupyterHubUserFactory(
         username='******',
         password=sha512_crypt.hash('pass'),
         whitelisted=True,
         admin=False,
         jupyter_hub_management=self.jupyter_hub_management)
コード例 #9
0
def _encode_secret(attribute, new_value=None):
    if attribute == 'NT-Password':
        attribute_value = nthash.hash(new_value)
    elif attribute == 'LM-Password':
        attribute_value = lmhash.hash(new_value)
    elif attribute == 'MD5-Password':
        attribute_value = md5(new_value.encode('utf-8')).hexdigest()
    elif attribute == 'SMD5-Password':
        salt = urandom(4)
        hash = md5(new_value.encode('utf-8'))
        hash.update(salt)
        hash_encoded = encodestring(hash.digest() + salt)
        attribute_value = hash_encoded.decode('utf-8')[:-1]
    elif attribute == 'SHA-Password':
        attribute_value = sha1(new_value.encode('utf-8')).hexdigest()
    elif attribute == 'SSHA-Password':
        salt = urandom(4)
        hash = sha1(new_value.encode('utf-8'))
        hash.update(salt)
        hash_encoded = encodestring(hash.digest() + salt)
        attribute_value = hash_encoded.decode('utf-8')[:-1]
    elif attribute == 'Crypt-Password':
        attribute_value = sha512_crypt.hash(new_value)
    else:
        attribute_value = new_value
    return attribute_value
コード例 #10
0
def encode_secret(attribute=settings.FREERADIUS_DEFAULT_SECRET_FORMAT,
                  new_value=None):
    if attribute == 'Cleartext-Password':
        password_renewed = new_value
    elif attribute == 'NT-Password':
        password_renewed = nthash.hash(new_value)
    elif attribute == 'LM-Password':
        password_renewed = lmhash.hash(new_value)
    elif attribute == 'MD5-Password':
        password_renewed = md5(new_value.encode('utf-8')).hexdigest()
    elif attribute == 'SMD5-Password':
        salt = urandom(4)
        hash = md5(new_value.encode('utf-8'))
        hash.update(salt)
        hash_encoded = encodestring(hash.digest() + salt)
        password_renewed = hash_encoded.decode('utf-8')[:-1]
    elif attribute == 'SHA-Password':
        password_renewed = sha1(new_value.encode('utf-8')).hexdigest()
    elif attribute == 'SSHA-Password':
        salt = urandom(4)
        hash = sha1(new_value.encode('utf-8'))
        hash.update(salt)
        hash_encoded = encodestring(hash.digest() + salt)
        password_renewed = hash_encoded.decode('utf-8')[:-1]
    elif attribute == 'Crypt-Password':
        password_renewed = sha512_crypt.hash(new_value)
    return password_renewed
コード例 #11
0
ファイル: main.py プロジェクト: Ravindradhanapal/eyegazeauth
    def calcAndSaveGridOffset(self, selections):
        pswdFile = open(curdir + "/picturepointspassword.txt", "w+")
        pswdFile.seek(0)
        offsetFile = open(curdir + "/picturepointsoffset.txt", "w+")
        offsetFile.seek(0)

        self.selected_grids = []

        for selection in selections:

            print("SAVED", selection.x, selection.y)
            gridBoxX = math.ceil(selection.x / GRID_SIZE)
            gridBoxY = math.ceil(selection.y / GRID_SIZE)
            print("SAVED", gridBoxX, gridBoxY)
            self.selected_grids.append(str(gridBoxX) + " " + str(gridBoxY))

            # x and y value of the center of the grid box containing this selected point
            gridBoxCenterX = gridBoxX * GRID_SIZE - (math.floor(GRID_SIZE / 2))
            gridBoxCenterY = gridBoxY * GRID_SIZE - (math.floor(GRID_SIZE / 2))
            offsetX = gridBoxCenterX - selection.x
            offsetY = gridBoxCenterY - selection.y

            offsetFile.write(str(offsetX) + " " + str(offsetY) + '\n')

        pswd_hash = sha512_crypt.hash(''.join(self.selected_grids))
        pswdFile.write(pswd_hash)
        sys.exit(0)
コード例 #12
0
def create_account(name, password, auth_code):
    file_name = directory + "accounts/" + name + ".json"

    # The account file already exists
    if os.path.isfile(file_name):
        return None

    # Generate an auth code if one isn't provided
    if auth_code == "":
        auth_code = create_signup_auth()

    # Make sure the auth is valid if it was provided
    # This is also use up the auth if it was generated above
    if not is_valid_signup_auth(auth_code, True):
        print("invalid auth")
        return None

    # Create the directory for account information if it doesn't exist
    os.makedirs(directory + "accounts/", exist_ok=True)

    # Create account file and write information
    file = open(file_name, "w")
    file.write(
        json.dumps({
            "password": sha512_crypt.hash(password),
            "auth_code": auth_code,
            "settings": {},
        }))
    file.close()

    return _create_session(Account(name, auth_code, {}))
コード例 #13
0
 def hash_password(password):
     """
     Hashes a password using pbkdf2_sha512
     :param password: The sha512 password from the login/register form
     :return: A sha512->pbkdf2_sha512 encrypted password
     """
     return sha512_crypt.hash(password)
コード例 #14
0
def calico_ipip_cluster(docker_backend: Docker, artifact_path: Path,
                        request: SubRequest, log_dir: Path) -> Iterator[Cluster]:
    with Cluster(
            cluster_backend=docker_backend,
            masters=1,
            agents=2,
            public_agents=1,
    ) as cluster:

        config = {
            "superuser_username": superuser_username,
            # We can hash the password with any `passlib`-based method here.
            # We choose `sha512_crypt` arbitrarily.
            "superuser_password_hash": sha512_crypt.hash(superuser_password),
            "calico_vxlan_enabled": "false",
            "calico_network_cidr": "192.168.128.0/17",
        }
        cluster.install_dcos_from_path(
            dcos_installer=artifact_path,
            dcos_config={
                **cluster.base_config,
                **config,
            },
            output=Output.LOG_AND_CAPTURE,
            ip_detect_path=docker_backend.ip_detect_path,
        )
        wait_for_dcos_oss(
            cluster=cluster,
            request=request,
            log_dir=log_dir,
        )
        yield cluster
コード例 #15
0
ファイル: fixtures.py プロジェクト: opennode/waldur-ansible
 def jupyter_hub_admin_user(self):
     return factories.JupyterHubUserFactory(
         username='******',
         password=sha512_crypt.hash('pass'),
         whitelisted=False,
         admin=True,
         jupyter_hub_management=self.jupyter_hub_management_linux_pam)
コード例 #16
0
def register():
    form = Reg(request.form)
    if request.method == 'GET':  # make sure the method used is define above
        return render_template('register.html', form=form), logging.warning(
            "you are under the register page now using GET, well done bacco ")
    elif request.method == 'POST' and form.validate():
        name = form.name.data  # the following are the data from the registration form
        username = form.username.data
        email = form.email.data
        password = sha512_crypt.hash(str(
            form.password.data))  # passsword is encrypted

        # defining a new variable taking as input the values from the registration form
        myuser = [{
            "name": name,
            "username": username,
            "email": email,
            "password": password
        }]
        # insert the list into the mongo db
        x = mycol.insert_many(myuser), print("inserting this user: "******"in the database called ", mycol)

        return render_template('register.html', form=form), print(
            "you are under the register page now using POST, data are sent to database"
        )
    else:
        print("this is the error")
コード例 #17
0
ファイル: create.py プロジェクト: rajcspsg/dcos-e2e
def get_config(
    cluster_representation: ClusterRepresentation,
    extra_config: Dict[str, Any],
    dcos_variant: DCOSVariant,
    security_mode: Optional[str],
    license_key: Optional[Path],
) -> Dict[str, Any]:
    """
    Get a DC/OS configuration to use for the given cluster.
    """
    is_enterprise = bool(dcos_variant == DCOSVariant.ENTERPRISE)

    if is_enterprise:
        superuser_username = DEFAULT_SUPERUSER_USERNAME
        superuser_password = DEFAULT_SUPERUSER_PASSWORD

        enterprise_extra_config = {
            'superuser_username': superuser_username,
            'superuser_password_hash': sha512_crypt.hash(superuser_password),
            'fault_domain_enabled': False,
        }
        if license_key is not None:
            key_contents = license_key.read_text()
            enterprise_extra_config['license_key_contents'] = key_contents

        extra_config = {**enterprise_extra_config, **extra_config}
        if security_mode is not None:
            extra_config['security'] = security_mode

    dcos_config = {
        **cluster_representation.base_config,
        **extra_config,
    }

    return dcos_config
コード例 #18
0
    def test_enterprise(
        self,
        cluster_backend: ClusterBackend,
        enterprise_1_10_artifact: Path,
        license_key_contents: str,
    ) -> None:
        """
        A DC/OS Enterprise 1.10 cluster can be started.
        """
        superuser_username = str(uuid.uuid4())
        superuser_password = str(uuid.uuid4())
        config = {
            'superuser_username': superuser_username,
            'superuser_password_hash': sha512_crypt.hash(superuser_password),
            'fault_domain_enabled': False,
            'license_key_contents': license_key_contents,
        }

        with Cluster(cluster_backend=cluster_backend) as cluster:
            cluster.install_dcos_from_path(
                build_artifact=enterprise_1_10_artifact,
                dcos_config={
                    **cluster.base_config,
                    **config,
                },
                log_output_live=True,
            )
            cluster.wait_for_dcos_ee(
                superuser_username=superuser_username,
                superuser_password=superuser_password,
            )
コード例 #19
0
ファイル: account.py プロジェクト: Fischa7/File-Server
    def create_account(name, password, auth_code):
        directory = Account.directory

        file_name = directory + "accounts/" + name + ".json"

        if os.path.isfile(file_name):
            return None

        if not Account.is_valid_auth(auth_code):
            print("invalid auth")
            return None

        if auth_code == "":
            auth_code = create_auth()

        settings = {
            "refresh_rate": 0,
        }

        account = Account(name, auth_code, settings)

        os.makedirs(directory + "accounts/", exist_ok=True)
        file = open(file_name, "w")
        file.write(
            json.dumps({
                "password": sha512_crypt.hash(password),
                "auth_code": auth_code,
                "settings": settings,
            }))
        file.close()

        return Account._create_session(Account(name, auth_code, settings))
コード例 #20
0
def pw_crypt():
    '''
    Function to hash an inputed string.
    Hashed string is then saved to variable and returned.
    '''
    pw = getpass.getpass(prompt='Enter the proposed esxi password: ')
    resp = sha512.hash(pw, rounds=5000)
    return resp
コード例 #21
0
def responsavel_create(usuario):
    responsavel = facade.create_observador_facade(tipo=TIPO_USUARIOS['responsavel'], nome=usuario['nome'],
                                                  senha=sha512_crypt.hash(password_generate()), email=usuario['email'])
    if isinstance(responsavel, object):
        itens = facade.set_itens_responsaveis_facade(id=responsavel.id, itens=facade.get_itens_free_facade())
        aluno = facade.vincular_responsavel_facade(id_aluno=request.params['vinculo_aluno'], id_responsavel=responsavel.id)
        if itens and aluno.vinculo_responsavel == str(responsavel.id):
            return '/gestao_aprendizagem/usuario'
コード例 #22
0
def sha512_hash(txt):
    """
    Returns the SHA512 Hashed secret for use as a password hash in the PanOS configuration
    :param txt: text to be hashed
    :return: password hash of the string with salt and configuration information. Suitable to place in the
    phash field in the configurations
    """
    return sha512_crypt.hash(txt)
コード例 #23
0
ファイル: app_passwd.py プロジェクト: mfrancis95/self-service
def _hash_passwd(password):
    """
    Hash the provided string using SHA512-Crypt

    Keyword arguments:
    password -- Key to hash
    """
    pwhash = sha512.hash(password)
    return "{SHA512-CRYPT}" + pwhash
コード例 #24
0
def gestor_create(usuario):
    gestor = facade.create_observador_facade(tipo=TIPO_USUARIOS['gestor'], nome=usuario['nome'],
                                             senha=sha512_crypt.hash(password_generate()),
                                             data_nascimento=usuario['nascimento'], email=usuario['email'],
                                             vinculo_rede=usuario['vinculo_rede'])
    if isinstance(gestor, object):
        itens = facade.set_itens_responsaveis_facade(id=gestor.id, itens=facade.get_itens_free_facade())
        if itens:
            return '/gestao_aprendizagem/usuario'
コード例 #25
0
    def test_auth_with_cli(
        self,
        cluster_backend: ClusterBackend,
        enterprise_artifact: Path,
        license_key_contents: str,
    ) -> None:
        """
        After `Cluster.wait_for_dcos_ee`, the DC/OS Enterprise cluster can
        communicate with the CLI.
        """
        superuser_username = str(uuid.uuid4())
        superuser_password = str(uuid.uuid4())
        config = {
            'superuser_username': superuser_username,
            'superuser_password_hash': sha512_crypt.hash(superuser_password),
            'fault_domain_enabled': False,
            'license_key_contents': license_key_contents,
        }

        with Cluster(cluster_backend=cluster_backend) as cluster:
            cluster.install_dcos_from_path(
                build_artifact=enterprise_artifact,
                dcos_config={
                    **cluster.base_config,
                    **config,
                },
                log_output_live=True,
                ip_detect_path=cluster_backend.ip_detect_path,
            )
            (master, ) = cluster.masters

            cluster.wait_for_dcos_ee(
                superuser_username=superuser_username,
                superuser_password=superuser_password,
            )

            setup_args = [
                'dcos',
                'cluster',
                'setup',
                'https://' + str(master.public_ip_address),
                '--no-check',
                '--username',
                superuser_username,
                '--password',
                superuser_password,
            ]

            setup = subprocess.run(
                args=setup_args,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
            )

            assert setup.returncode == 0
            assert setup.stderr == b''
コード例 #26
0
def j2_template(string):
    env = Environment(
        trim_blocks=False,
        lstrip_blocks=False,
        variable_start_string="{$",
        variable_end_string="$}",
        undefined=StrictUndefined,
    )
    env.filters["crypt"] = lambda x: sha512_crypt.hash(x, rounds=5000)
    return env.from_string(string if type(string) == str else str(string))
コード例 #27
0
ファイル: standard.py プロジェクト: AmI-2018/NTMY-code
    def make_password(password: str) -> str:
        """Returns the hashed password.
        
        :param password: The password to encrypt
        :type password: str
        :return: The encrypted password
        :rtype: str
        """

        return sha512_crypt.hash(password)
コード例 #28
0
 def addUser(self, name, password):
     h = sha512_crypt.hash(password)
     c = self._conn.cursor()
     c.execute("SELECT id FROM user WHERE name = ? LIMIT 1", (name, ))
     r = c.fetchone()
     if r is None:
         c.execute("INSERT INTO user (name, password) VALUES (?, ?)",
                   (name, h))
     else:
         c.execute("UPDATE user SET password = ? WHERE name = ?", (h, name))
     self._conn.commit()
コード例 #29
0
ファイル: Verifier.py プロジェクト: tanveerkn/voting-protocol
    def verify(self, vote):

        env_counter1 = str(encrypt(pub, vote)) + '_' + str(
            encrypt(pub, self.share_common)) + '_' + str(uid)

        env_counter1_hash = CryptContext.hash(env_counter1)

        if env_counter1_hash == self.env1_hash or self.env2_hash:
            print("verified")
        else:
            print("vote not counted")
コード例 #30
0
    def button_handler(self, event):
        label = event.GetEventObject().GetLabel()
        lst = ['first', 'second', 'third', 'fourth']
        self.selected_pictures.append(label)\

        if len(self.selected_pictures) == 4:
            self.label_1.SetLabel('Passwowrd set')
            pswd_hash = sha512_crypt.hash(''.join(self.selected_pictures))
            print("Hash: " + str(pswd_hash))
        else:
            self.label_1.SetLabel('Select the {s} picture'.format(s=lst[len(self.selected_pictures)]))
コード例 #31
0
ファイル: advanced.py プロジェクト: brucewu16899/modoboa
 def _encrypt(self, clearvalue, salt=None):
     rounds = param_tools.get_global_parameter("rounds_number")
     sha512_crypt.using(rounds=rounds)
     return sha512_crypt.hash(clearvalue)
コード例 #32
0
ファイル: bdb.py プロジェクト: ioos/glider-dac
 def set(self, username, password):
     """Writes a SHA512 hashed password into the specified username"""
     with self._use_db() as bdb:
         bdb.put(username, sha512_crypt.hash(password))
コード例 #33
0
ファイル: launch_cluster.py プロジェクト: dcos/dcos-cli
if not dcos_variant:
    print("Please set DCOS_TEST_VARIANT to 'open' or 'enterprise'.", file=sys.stderr)
    sys.exit(1)

private_key_path = os.environ.get('DCOS_TEST_SSH_KEY_PATH')
aws_key_pair = ('default', private_key_path) if private_key_path else None

cluster_backend = AWS(aws_region='us-east-1', aws_key_pair=aws_key_pair)
cluster = Cluster(cluster_backend=cluster_backend, agents=0, public_agents=0)

username = '******'
password = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(12))

extra_config = {
    'superuser_username': username,
    'superuser_password_hash': sha512_crypt.hash(password),
#    'fault_domain_enabled': False,
}

test_license = os.environ.get('DCOS_TEST_LICENSE')
if test_license:
    extra_config['license_key_contents'] = test_license

dcos_config = {**cluster.base_config, **extra_config}

cluster.install_dcos_from_url(
    dcos_installer=sys.argv[1],
    dcos_config=dcos_config,
    ip_detect_path=cluster_backend.ip_detect_path,
    output=Output.LOG_AND_CAPTURE,
)