Exemple #1
0
 def test_get_passphrase_special_delimiter(self):
     # delimiter_special overrules delemiter
     options = handle_options(args=[])
     options.delimiter = " "
     options.delimiter_special = 2
     phrase = get_passphrase(options)
     assert " " not in phrase
Exemple #2
0
def add_user(client,groupName,studentNumber,tempDir):
    myStudent = groupName + '-Student-' + str(studentNumber)
    userFile = tempDir + myStudent + ".json"
    newStudent = {}
    newStudent.update({'name': myStudent})
    studentPass = diceware.get_passphrase()
    newStudent.update({'pass': studentPass})

    f = open(userFile, "a")
    f.write("{\n")
    f.write('"username":"******",\n')
    f.write('"password":"******",\n')
    f.write('"attributes": {\n')
    f.write('  "disabled": "",\n')
    f.write('  "expired": "",\n')
    f.write('  "access-window-start": "",\n')
    f.write('  "access-window-end": "",\n')
    f.write('  "valid-from": "",\n')
    f.write('  "valid-until": "",\n')
    f.write('  "timezone": ""\n')
    f.write('  }\n')
    f.write('}\n')
    f.close()
    f = open(userFile, "r")
    userData = f.read()
    userData = json.loads(userData)
    client.add_user(userData)
    return newStudent
Exemple #3
0
 def test_get_passphrase_specialchars(self):
     # we can request special chars in passphrases
     options = handle_options(args=[])
     options.specials = 2
     phrase = get_passphrase(options)
     specials = [x for x in phrase if x in SPECIAL_CHARS]
     # the 2nd special char position might be equal to 1st.
     assert len(specials) > 0
 def test_get_passphrase_specialchars(self):
     # we can request special chars in passphrases
     options = handle_options(args=[])
     options.specials = 2
     phrase = get_passphrase(options)
     specials = [x for x in phrase if x in SPECIAL_CHARS]
     # the 2nd special char position might be equal to 1st.
     assert len(specials) > 0
Exemple #5
0
def create_pass():
    portal_name = click.prompt('Enter portal name', default="None")
    portal_url = click.prompt('Enter portal_url',default="None")
    user_email = click.prompt('Enter mail-id',default="None")
    tag = click.prompt('Enter tags',default="None")
    notes = click.prompt('Enter notes',default="None")
    password = diceware.get_passphrase()
    creation_date = datetime.now()
    print(f"\n\nPortal Name: {portal_name}\n Portal URL: {portal_url}\n User Email: {user_email}\n Tags: {tag}\n Notes: {notes}\n Password: {password}\n Creation Date: {creation_date}")
Exemple #6
0
def make_diceware():
	'''Generates a diceware password'''
	options = argparse.Namespace()
	options.num = 5
	options.caps = True
	options.specials = 0
	options.delimiter = '-'
	options.randomsource = 'system'
	options.wordlist = 'en_eff'
	options.infile = None
	return diceware.get_passphrase(options)
Exemple #7
0
def createpass():
    """Used for taking input from user to create password"""
    portal_name = click.prompt("Enter portal name", default="None")
    password = diceware.get_passphrase()
    creation_date = date.today()
    email = click.prompt("Enter email id", default="None")
    portal_url = click.prompt("Enter portal url", default="None")
    db_obj.insert_data(
        portal_name=portal_name,
        password=password,
        creation_date=creation_date,
        email=email,
        portal_url=portal_url,
    )
Exemple #8
0
def reset_user_password(request, user: str = None):
    if user is None:
        return HttpResponseBadRequest()
    if request.method == "POST":
        form = ResetPasswordForm(request.POST)
        if form.is_valid():
            user_object = get_object_or_404(get_user_model(), username=user)
            new_password = get_passphrase()
            user_object.set_password(new_password)
            user_object.save()
            context = {
                "password": new_password,
                "email_address": user_object.username,
            }
            return render(request, "user_info_printout.html", context)
        else:
            messages.error(request, "Please check the box to confirm reset.")
            return redirect("administration:manageuser", user=user)
    else:
        return HttpResponseBadRequest()
Exemple #9
0
def get_action():

    from_number = request.values.get('From')
    body = request.values.get('Body', None).lower()

    resp = MessagingResponse()

    if body == 'riddikulus':
        dw = diceware.handle_options(['-w' 'en_securedrop'])
        passphrase = diceware.get_passphrase(dw)
        resp.message(passphrase)
    elif body == 'roll':
        resp.message(
            'Roll 5 dice per word count you wish to return. Two word count example format: 12345 54321.'
        )
    else:
        numbers = re.findall('\d', body)
        if any(elem in numbers for elem in blacklist) or len(numbers) % 5 > 0:
            resp.message(
                'Value out of range. Please try again. Send `riddikulus` to get a Diceware generated passphrase. Send `roll` to use dice and send results to perform lookup.'
            )
        else:
            passphrase = []
            dicerolls = []
            zipped = zip(*(iter(numbers), ) * 5)
            number_strings = list(zipped)
            for nums in number_strings:
                num_strings = ''.join(map(str, nums))
                dicerolls.append(num_strings)
            for number_set in dicerolls:
                word_result = wordlist_dict[number_set]
                passphrase.append(word_result)
            complete_passphrase = ' '.join(passphrase)
            resp.message(complete_passphrase)

    return str(resp)
Exemple #10
0
 def test_get_passphrase_no_capitals(self):
     # we can turn capitals off
     phrase = get_passphrase(capitalized=False)
     assert phrase.lower() == phrase
Exemple #11
0
 def test_get_passphrase_no_capitals(self):
     # we can turn capitals off
     options = handle_options(args=[])
     options.caps = False
     phrase = get_passphrase(options)
     assert phrase.lower() == phrase
Exemple #12
0
 def test_get_passphrase_capitals(self):
     # by default a passphrase contains upper case chars
     phrase = get_passphrase()
     assert phrase.lower() != phrase
Exemple #13
0
 def test_get_passphrase_max(self):
     options = handle_options(args=[])
     options.max = 15
     phrase = get_passphrase(options)
     assert len(phrase) == 15
 def test_get_passphrase_no_capitals(self):
     # we can turn capitals off
     options = handle_options(args=[])
     options.caps = False
     phrase = get_passphrase(options)
     assert phrase.lower() == phrase
 def test_get_passphrase(self):
     # we can get passphrases
     r1 = get_passphrase()
     r2 = get_passphrase()
     assert r1 != r2
Exemple #16
0
def main(interactive):
    # Get current commit:
    try:
        currentCommit = git.Repo(os.getcwd()).head.commit.hexsha
    except:
        currentCommit = None

    tempVars = {
        'appObject': 'app',
        'appName': 'app',
        'mainFile': 'main.py',
        'appPort': 80,
        'codeDir': '.',
        'dependencyFile': 'requirements.txt',
        'baseImage': 'python:3-alpine3.12',
        'currentCommit': currentCommit[:8] if currentCommit else 'latest',
        'baseDir': os.path.basename(os.getcwd()),
        'imageWorkDir': '/code',
        'userID': 0,
        'ports': [],
        'dnsName': 'localhost'
    }
    tempVars['appName'] = slugify(os.getenv('PROJECT_NAME', 'project'))

    ##### Main session #####
    print('🙌 GEPP Starting!')

    print('📍 Locating main.py file... ', end='')
    try:
        mainFile = get_main()
    except:
        print('Could not get main.py, exiting.')
        import sys
        sys.exit(1)
    tempVars['mainFile'] = mainFile

    if interactive:
        config = get_interactive_config()

        # TODO Should use `get_interactive_config` function for rest of this block
        yesNoValidator = Validator.from_callable(
            is_yes_or_no,
            error_message='This input contains non-yes/no',
            move_cursor_to_end=True)

        listening = prompt(
            "Is the app listening additional ports (for exposing metrics, healthchecks etc.)? [Y/n]: ",
            validator=yesNoValidator)

        if is_yes(listening):
            print('Write additional ports following this template:\n\
                    name: any,\n\
                    protocol: TCP | UDP\n\
                    port: number')

            nameValidator = Validator.from_callable(
                is_name,
                error_message=
                'This input contains non-alphanumeric characters for name',
                move_cursor_to_end=True)

            protocolValidator = Validator.from_callable(
                is_protocol,
                error_message='This input must TCP or UDP',
                move_cursor_to_end=True)

            protocolCompleter = WordCompleter(['TCP', 'UDP'])

            portValidator = Validator.from_callable(
                is_port,
                error_message='This input must between 1 and 65535',
                move_cursor_to_end=True)

            while True:

                dicewareOpts = diceware.handle_options(args=["-n", "3"])

                additionalPortName = prompt(
                    "name: ",
                    validator=nameValidator,
                    default=diceware.get_passphrase(dicewareOpts))
                additionalPortProtocol = prompt("protocol: ",
                                                validator=protocolValidator,
                                                completer=protocolCompleter,
                                                default='TCP')
                additionalPort = prompt("port: ", validator=portValidator)

                tempVars['ports'].append({
                    'name': additionalPortName,
                    'protocol': additionalPortProtocol,
                    'port': additionalPort
                })
                print("\n🌸\n")

                isContinue = prompt("Continue? [Y/n]: ",
                                    validator=yesNoValidator)
                if is_no(isContinue):
                    break

    else:
        config = generate_default_config()

    templates = jinja2.Environment(
        loader=jinja2.PackageLoader(package_name='main'), autoescape=True)

    tempVars['ports'].append({
        'name': 'http',
        'protocol': 'TCP',
        'port': tempVars['appPort']
    })
    # TODO: remove after testing
    tempVars['ports'].append({'name': 'api', 'protocol': 'TCP', 'port': 8080})

    # Check for Dockerfile and create if not exists
    check_and_create('Dockerfile',
                     templates,
                     'Dockerfile.j2',
                     '🐳',
                     vars=tempVars)

    # Check for .dockerignore file and create if not exists
    check_and_create('.dockerignore', templates, 'dockerignore.j2', '🐳')

    # Build Docker image
    print('🏗  Trying Docker image build... ', end='', flush=True)
    # TODO: check whether main.py, requirements.txt exists or manually supplied
    tempVars['imageName'] = build_image(repo=tempVars['appName'],
                                        tag=tempVars['currentCommit'])

    print('☸️  Generating YAMLs for Kubernetes:')
    create_k8s_dir()
    check_and_create(f'kubernetes/deployment-{tempVars["appName"]}.yaml',
                     templates,
                     'deployment.yaml.j2',
                     '   -',
                     vars=tempVars)
    check_and_create(f'kubernetes/service-{tempVars["appName"]}.yaml',
                     templates,
                     'service.yaml.j2',
                     '   -',
                     vars=tempVars)
    check_and_create(f'kubernetes/ingress-{tempVars["appName"]}.yaml',
                     templates,
                     'ingress.yaml.j2',
                     '   -',
                     vars=tempVars)
    check_and_create(f'kubernetes/hp-autoscaler-{tempVars["appName"]}.yaml',
                     templates,
                     'hp-autoscaler.yaml.j2',
                     '   -',
                     vars=tempVars)

    # k3d cluster create $NAME + k3d kubeconfig get $NAME
    print('⚓ Creating a test cluster with k3d')
    create_k3d_cluster(tempVars['appName'], images=[tempVars['imageName']])

    # Get exposed port list and print
    exposedPorts = get_k3d_info(tempVars['appName'])
    print(
        f'   - Connect to Kubernetes Ingress via HTTP using \033[1mhttp://localhost:{exposedPorts["80"]}\033[0m'
    )
    print(
        f'   - Connect to Kubernetes Ingress via HTTPS using \033[1mhttps://localhost:{exposedPorts["443"]}\033[0m'
    )

    print('🚀 Deploying apps to Kubernetes')
    deploy_to_k8s(tempVars['appName'])

    print('📦 Generating Terraform file for Azure Kubernetes Service')

    generate_terraform(tempVars['appName'])

    print('Done! ✅')
 def test_get_passphrase_delimiters(self):
     # we can set separators
     options = handle_options(args=[])
     options.delimiter = " "
     phrase = get_passphrase(options)
     assert " " in phrase
Exemple #18
0
 def test_get_passphrase(self):
     test_wordlist = {'12345': 'test', '23456': 'foo', '34567': 'bar'}
     test_rolls = ['34567', '12345']
     # Test that the correct passphrase is returned.
     self.assertEqual(diceware.get_passphrase(test_rolls, test_wordlist),
                      "bar test")
Exemple #19
0
 def test_get_passphrase_wordlist_fd(self):
     #  we can pass in an own wordlist
     wordlist_fd = StringIO("word1\n")
     phrase = get_passphrase(wordlist_fd=wordlist_fd)
     assert "Word1" in phrase
Exemple #20
0
 def test_get_passphrase_delimiters(self):
     # we can set separators
     phrase = get_passphrase(delimiter=" ")
     assert " " in phrase
Exemple #21
0
 def test_get_passphrase_no_capitals(self):
     # we can turn capitals off
     phrase = get_passphrase(capitalized=False)
     assert phrase.lower() == phrase
Exemple #22
0
def get_passphrase():
    options = diceware.handle_options(['--num', '4'])

    return diceware.get_passphrase(options)
Exemple #23
0
 def test_get_passphrase_delimiters(self):
     # we can set separators
     options = handle_options(args=[])
     options.delimiter = " "
     phrase = get_passphrase(options)
     assert " " in phrase
Exemple #24
0
 def test_get_passphrase_wordlist_fd(self):
     #  we can pass in an own wordlist
     options = handle_options(args=[])
     options.infile = StringIO("word1\n")
     phrase = get_passphrase(options)
     assert "Word1" in phrase
Exemple #25
0
 def test_get_passphrase_wordlist_fd(self):
     #  we can pass in an own wordlist
     wordlist_fd = StringIO("word1\n")
     phrase = get_passphrase(wordlist_fd=wordlist_fd)
     assert "Word1" in phrase
Exemple #26
0
def gen_phrase(length=5):
    return get_passphrase(handle_options(["-n", str(length)]))
Exemple #27
0
def generate(*args):
    passphrase.set(get_passphrase())
 def test_get_passphrase_capitals(self):
     # by default a passphrase contains upper case chars
     phrase = get_passphrase()
     assert phrase.lower() != phrase
Exemple #29
0
 def test_get_passphrase_delimiters(self):
     # we can set separators
     phrase = get_passphrase(delimiter=" ")
     assert " " in phrase
Exemple #30
0
 def test_get_passphrase(self):
     # we can get passphrases
     r1 = get_passphrase()
     r2 = get_passphrase()
     assert r1 != r2
Exemple #31
0
def passphrase():
    return diceware.get_passphrase(diceware.handle_options(["--delimiter", "-", "--no-caps"]))
Exemple #32
0
 def test_get_passphrase_wordlist_fd(self):
     #  we can pass in an own wordlist
     options = handle_options(args=[])
     options.infile = StringIO("word1\n")
     phrase = get_passphrase(options)
     assert "Word1" in phrase
Exemple #33
0
def createpass():
    """Used for taking input from user to create password"""
    portal_name = click.prompt('Enter portal name', default="None")
    password = diceware.get_passphrase()
    db_obj.create_table()
    db_obj.insert_data(portal_name=portal_name, password=password)