Ejemplo n.º 1
0
    def save(self):
        if self._is_new():
            response = super().save()

            if isinstance(response, HTTPFound):
                password = pwgenerator.generate()

                user = self._obj
                user.password = password
                user.is_password_changed = False
                user = self._request.dbsession.merge(user)
                self._request.dbsession.flush()

                send_email_config(
                    settings=self._request.registry.settings,
                    email_config_name="welcome_email",
                    email=user.email,
                    user=user.username,
                    password=password,
                    application_url=self._request.route_url("base"),
                    current_url=self._request.current_route_url(),
                )

            return response

        return super().save()
Ejemplo n.º 2
0
    def editItemInput(self, itemKey, fieldName, fieldCurrentValue):
        """
            Edit a field for an item
        """

        # Show current value
        if fieldName != 'password':
            print("* Current value: %s" % (fieldCurrentValue))

        try:
            # Get new value
            if fieldName == 'password':
                print('* Suggestion: %s' % (pwgenerator.generate()))
                fieldNewValue = getpass.getpass('* New password: '******'category':
                # Show categories
                print()
                print("* Available categories:")
                self.categoriesList()
                print()

                # Category ID
                fieldNewValue = self.input(
                    '* Choose a category number (or leave empty for none): ')

                if fieldNewValue != '':
                    if not self.categoryCheckId(fieldNewValue):
                        print('Invalid category. Please try again.')
                        self.editItemInput(itemKey, fieldName,
                                           fieldCurrentValue)
            elif fieldName == 'notes':
                print('* Notes: (press [ENTER] twice to complete)')
                notes = []
                while True:
                    input_str = self.input("> ")
                    if input_str == "":
                        break
                    else:
                        notes.append(input_str)
                fieldNewValue = "\n".join(notes)
            else:
                fieldNewValue = self.input('* New %s: ' % (fieldName))
        except KeyboardInterrupt as e:
            # Back to menu if user cancels
            print()
            self.menu()

        # Update item
        item = self.vault['secrets'][itemKey][fieldName] = fieldNewValue

        # Debug
        #print(self.vault['secrets'][itemKey])

        # Save the vault
        self.saveVault()

        print('The item has been updated.')

        # Back to Vault menu
        self.menu()
Ejemplo n.º 3
0
    def addItemInput(self):
        """
            Add a new secret based on user input
        """

        if self.vault.get('categories'):
            # Show categories
            print()
            print("* Available categories:")
            self.categoriesList()
            print()

            # Category ID
            try:
                categoryId = self.input(
                    '* Choose a category number (or leave empty for none): ')
            except KeyboardInterrupt as e:
                # Back to menu if user cancels
                print()
                self.menu()

            if categoryId != '':
                if not self.categoryCheckId(categoryId):
                    print('Invalid category. Please try again.')
                    self.addItemInput()
        else:
            print()
            categoryId = ''
            print(
                "* Category: you did not create a category yet. Create one from the main menu to use this feature!"
            )

        # Basic settings
        try:
            name = self.input('* Name / URL: ')
            login = self.input('* Login: '******'* Password suggestion: %s' % (pwgenerator.generate()))
            password = getpass.getpass('* Password: '******'* Notes: (press [ENTER] twice to complete)')
            notes = []
            while True:
                input_str = self.input("> ")
                if input_str == "":
                    break
                else:
                    notes.append(input_str)
        except KeyboardInterrupt as e:
            self.menu()

        # Save item
        self.addItem(categoryId, name, login, password, "\n".join(notes))

        # Confirmation
        print()
        print('The new item has been saved to your vault.')
        print()
        self.menu()
Ejemplo n.º 4
0
def add_input():
    """
        Ask user for a secret details and create it
    """

    # Clear screen
    clear_screen()

    # Ask user input
    category_id = None
    if len(all_categories()) > 0:
        category_id = pick(
            message='* Choose a category number (or leave empty for none): ',
            optional=True)
        if category_id is False:
            return False

    name = menu.get_input(message='* Name: ')
    if name is False:
        return False

    url = menu.get_input(message='* URL: ')
    if url is False:
        return False

    # Get list for auto-completion
    autocomplete.set_parameters(list_=get_top_logins(), case_sensitive=True)
    login = autocomplete.get_input_autocomplete(
        message='* Login (use [tab] for autocompletion): ')
    if login is False:
        return False

    suggestion = pwgenerator.generate()
    print('* Password suggestion: %s' % (suggestion))
    password = menu.get_input(message='* Password: '******'The new item has been saved to your vault.')
    print()

    time.sleep(2)

    return True
Ejemplo n.º 5
0
def munge_passwd(passwd=None):
    """Return new 'passwd' string and boolean 'require_reset'.
    If passwd provided, set 'require_reset' to False.
    """
    if passwd:
        require_reset = False
    else:
        passwd = pwgenerator.generate()
        require_reset = True
    return passwd, require_reset
Ejemplo n.º 6
0
def add_input():
    """
        Ask user for a secret details and create it
    """

    # Clear screen
    clear_screen()

    # Ask user input
    category_id = pick(
        message='* Choose a category number (or leave empty for none): ',
        optional=True)
    if category_id is False:
        return False

    name = menu.get_input(message='* Name: ')
    if name is False:
        return False

    url = menu.get_input(message='* URL: ')
    if url is False:
        return False

    login = menu.get_input(message='* Login: '******'* Password suggestion: %s' % (pwgenerator.generate()))
    password = menu.get_input(message='* Password: '******'The new item has been saved to your vault.')
    print()

    time.sleep(2)

    return True
Ejemplo n.º 7
0
def add_password(con,site,user,user_id,main_pass):
    """ Adds a new password to the database
    :param: con,site,user,user_id,main_pass 
    db connection, website, username, the logged in user, their password 
    :return: the auto generated secure password 
"""
    c = con.cursor()
    
    today = date.today()

    password = pwgenerator.generate()
    ciphered_pass = cipher_pass(password, main_pass)

    sql = """INSERT INTO passwords 
            (site,user,password,date,user_id) VALUES
            (?,?,?,?,?)
            """
    c.execute(sql,(site.lower(),user.lower(),ciphered_pass,today,user_id))
    con.commit()
    return password
Ejemplo n.º 8
0
    def save(self):
        if self._is_new():
            response = super().save()

            if isinstance(response, HTTPFound):
                password = pwgenerator.generate()
                user = self._obj
                user.set_temp_password(password)
                user = self._request.dbsession.merge(user)
                self._request.dbsession.flush()

                send_email_config(
                    settings=self._request.registry.settings,
                    email_config_name='welcome_email',
                    email=user.email,
                    user=user.username,
                    password=password)

            return response

        return super().save()
Ejemplo n.º 9
0
def edit_input(element_name, item):
    """
        Edit an item
    """

    if element_name == 'category':
        print('* Current nategory: %s' %
              (get_category_name(item.category_id) or 'Empty!'))
        category_id = pick(message='* New category: ', optional=True)

        if category_id is not False:
            item.category_id = category_id
        else:
            time.sleep(2)
            print('\nCancelled!')
            return False
    elif element_name == 'name':
        print('* Current name: %s' % (item.name or 'Empty!'))
        name = menu.get_input(message='* New name: ')

        if name is not False:
            item.name = name
        else:
            print('\nCancelled!')
            time.sleep(2)
            return False
    elif element_name == 'url':
        print('* Current URL: %s' % (item.url or 'Empty!'))
        url = menu.get_input(message='* New URL: ')

        if url is not False:
            item.url = url
        else:
            print('\nCancelled!')
            time.sleep(2)
            return False
    elif element_name == 'login':
        print('* Current login: %s' % (item.login or 'Empty!'))
        login = menu.get_input(message='* New login: '******'\nCancelled!')
            time.sleep(2)
            return False
    elif element_name == 'password':
        print('* Password suggestion: %s' % (pwgenerator.generate()))
        password = menu.get_input(message='* New password: '******'\nCancelled!')
            time.sleep(2)
            return False
    elif element_name == 'notes':
        print('* Current notes: %s' % (item.notes or 'Empty!'))
        notes = notes_input()

        if notes is not False:
            item.notes = notes
        else:
            print('\nCancelled!')
            time.sleep(2)
            return False
    else:
        raise ValueError('Element `%s` not not exists.' % (element_name))

    # Process update
    get_session().add(item)
    get_session().commit()

    print('The %s has been updated.' % (element_name))
    time.sleep(2)

    return True
Ejemplo n.º 10
0
    elif "generate password" in query:
        try:
            speak("What should I name the app?")
            r = sr.Recognizer()
            with sr.Microphone() as source:
                print("speak anything")
                audio = r.listen(source)
                try:
                    text = r.recognize_google(audio)
                    print("you said :" + format(text))
                    password_name = format(text)

                except:
                    speak("Sorry I can't recognize it")
            content = password_name
            password = pwgenerator.generate()
            Myfile = open('Main.txt', 'a')
            Myfile.write(f"{content} -- {password} \n")
            Myfile.close()
            speak("password is genrated")
            pyperclip.copy(password)
        except Exception as e:
            print(e)
            speak("password wasn't genrated")

    elif "antonym" in query:
        r = sr.Recognizer()
        with sr.Microphone() as source:
            speak("please say the antoym sir")
            audio = r.listen(source)
            try:
Ejemplo n.º 11
0
def main(MerakiTimer: func.TimerRequest) -> None:
    start_time = dt.datetime.utcnow()
    utc_timestamp = start_time.replace(tzinfo=dt.timezone.utc).isoformat()

    logging.info('Python timer trigger function ran at %s', utc_timestamp)
    logging.info('Python version: %s', sys.version)

    # Obtain Meraki Org ID for API Calls
    mdashboard = meraki.DashboardAPI(MerakiConfig.api_key)
    result_org_id = mdashboard.organizations.getOrganizations()
    for x in result_org_id:
        if x['name'] == MerakiConfig.org_name:
            MerakiConfig.org_id = x['id']

    if not MerakiConfig.org_id:
        logging.error("Could not find Meraki Organization Name.")
        return

    # Check if any changes have been made to the Meraki configuration
    change_log = mdashboard.change_log.getOrganizationConfigurationChanges(
        MerakiConfig.org_id, total_pages=1, timespan=300)
    dashboard_config_change_ts = False
    for tag_events in change_log:
        if tag_events['label'] == 'Network tags' or tag_events[
                'label'] == 'VPN subnets':
            dashboard_config_change_ts = True

    # If no maintenance mode, check if changes were made in last 5 minutes or
    # if script has not been run within 5 minutes; check for updates
    if dashboard_config_change_ts is False and MerakiTimer.past_due is False and MerakiConfig.use_maintenance_window == _NO:
        logging.info(
            "No changes in the past 5 minutes have been detected. No updates needed."
        )
        return

    # Meraki call to obtain Network information
    meraki_networks = mdashboard.networks.getOrganizationNetworks(
        MerakiConfig.org_id)

    # Check if tag placeholder network exists, if not create it
    tags_network = meraki_tag_placeholder_network_check(
        mdashboard, meraki_networks)

    # Check if required tags exist in the tags placeholder network
    meraki_tag_placeholder_network_check_tags(mdashboard, tags_network)

    # Check if we should force changes even if during maintenance window
    # creating list of network IDs that can later be referenced to remove the
    # apply now tag once the script has executed
    remove_network_id_list = get_meraki_networks_by_tag(
        _VWAN_APPLY_NOW_TAG, tags_network)

    # if we are in maintenance mode or if update now tag is seen
    if (MerakiConfig.use_maintenance_window == _YES and MerakiConfig.maintenance_time_in_utc == start_time.hour) or \
            MerakiConfig.use_maintenance_window == _NO or len(remove_network_id_list) > 0:

        # variable with new and existing s2s VPN config
        merakivpns: list = []

        # performing initial get to obtain all Meraki existing VPN info to add to
        # merakivpns list above
        originalvpn = mdashboard.organizations.getOrganizationThirdPartyVPNPeers(
            MerakiConfig.org_id)
        merakivpns.append(originalvpn)

        # Get access token to authenticate to Azure
        access_token = get_bearer_token(_AZURE_MGMT_URL)
        if access_token is None:
            return
        header_with_bearer_token = {'Authorization': f'Bearer {access_token}'}

        # Get list of Azure Virtual WANs
        virtual_wans = get_azure_virtual_wans(header_with_bearer_token)
        if virtual_wans is None:
            return

        # Find virtual wan instance
        virtual_wan = find_azure_virtual_wan(AzureConfig.vwan_name,
                                             virtual_wans)
        if virtual_wan is None:
            logging.error(
                "Could not find vWAN instance.  Please ensure you have created your Virtual WAN resource prior to running "
                "this script or check that the system assigned identity has access to your Virtual WAN instance."
            )
            return

        # Complie list of hubs that are in scope for Meraki
        tagged_hubs = meraki_vwan_hubs(tags_network)
        logging.info(f"Tagged Virtual WAN Hubs found: {tagged_hubs}")

        # Check if VWAN Hubs in scope exist; if not log an error the hub doesn't exist
        hubs_exist = check_vwan_hubs_exist(virtual_wan, tagged_hubs)
        if (not hubs_exist):
            logging.error(
                "Not all Virtual WAN hubs exist, please ensure all hubs are created."
            )
            return

        # Generate random password for site to site VPN config
        psk = pwgenerator.generate()

        new_meraki_vpns = merakivpns[0]

        # Loop through each VWAN hub
        for hub in tagged_hubs:

            logging.info(
                f"Traversing Meraki networks with updates for VWAN Hub: {hub}")

            # Get Virtual WAN hub info
            vwan_hub_info = get_azure_virtual_wan_hub_info(
                virtual_wan['resourceGroup'], hub, header_with_bearer_token)

            # If no Virtual WAN hub or VPN Gateway, skip this hub
            if vwan_hub_info is None:
                continue

            # Get Virtual WAN Gateway Configuration
            vwan_config = get_azure_virtual_wan_gateway_config(
                virtual_wan['resourceGroup'], vwan_hub_info['name'],
                vwan_hub_info['vpnGatewayName'], header_with_bearer_token)
            if vwan_config is None:
                return

            # networks with vWAN in the tag
            found_tagged_networks = False
            for network in tags_network:
                # Check for placeholder network
                if network['name'].lower(
                ) == MerakiConfig.tag_placeholder_network:
                    logging.info(f"{network['name']} network found, skipping.")
                    continue

                # Check if tags exist
                if not network['tags']:
                    logging.info(
                        f"No tags found for {network['name']}, skipping to next network"
                    )
                    continue

                # Check if any vwan tags exist
                tags = meraki_convert_tags_to_list(network['tags'])
                if not check_if_meraki_vwan_tags_exist(tags, network['name'],
                                                       vwan_hub_info['name']):
                    continue

                logging.info(
                    f"Tags found for {network['name']} with hub {vwan_hub_info['name']} | Tags: {tags}"
                )

                # need network ID in order to obtain device/serial information
                network_info = network['id']

                # network name used to label Meraki VPN and Azure config
                netname = str(network['name']).replace(' ', '')

                try:
                    warm_spare_settings = mdashboard.mx_warm_spare_settings.getNetworkWarmSpareSettings(
                        network_info)
                except Exception as e:
                    logging.error('Failed to fetch warm_spare_settings')
                    logging.error(e.message)

                if 'primarySerial' in warm_spare_settings:
                    appliance = Appliance(
                        network_info, warm_spare_settings.get('enabled'),
                        warm_spare_settings.get('primarySerial'),
                        warm_spare_settings.get('spareSerial'))
                else:
                    logging.info(
                        f"MX device not found in {network['name']}, skipping network."
                    )
                    continue

                # check if appliance is on 15 firmware
                if not appliance.is_firmware_compliant():
                    logging.info(
                        f"MX device for {network['name']} not running v15 firmware, skipping network."
                    )
                    continue  # if box isnt firmware skip to next network

                # gets branch local vpn subnets
                va = mdashboard.networks.getNetworkSiteToSiteVpn(network_info)

                # filter for subnets in vpn
                privsub = ([
                    x['localSubnet'] for x in va['subnets']
                    if x['useVpn'] is True
                ])

                # If the site has two uplinks; create and update vwan site with
                wans = appliance.get_wan_links()

                site_config = get_site_config(vwan_hub_info['location'],
                                              virtual_wan['id'], privsub,
                                              netname, wans)

                # Create/Update the vWAN Site + Site Links
                virtual_wan_site_link_update = update_azure_virtual_wan_site_links(
                    virtual_wan['resourceGroup'], netname,
                    header_with_bearer_token, site_config)
                if virtual_wan_site_link_update is None:
                    logging.error(
                        f"Virtual WAN Site Link for {network['name']} could not be created/updated, skipping to next network."
                    )
                    continue

                # Create Virtual WAN Connection
                vwan_connection_result = create_virtual_wan_connection(
                    virtual_wan['resourceGroup'],
                    vwan_hub_info['vpnGatewayName'], netname,
                    AzureConfig.subscription_id, wans.items(), psk,
                    header_with_bearer_token)
                if vwan_connection_result is None:
                    logging.error(
                        f"Virtual WAN Connection for {network['name']} could not be created, skipping to next network."
                    )
                    continue

                # Parse the vwan config file
                azure_instance_0 = "192.0.2.1"  # placeholder value
                azure_instance_1 = "192.0.2.2"  # placeholder value
                azure_connected_subnets = ['1.1.1.1']  # placeholder value

                # Get Azure VPN Gateway Instances
                for instance in vwan_config['properties']['ipConfigurations']:
                    if instance['id'] == 'Instance0':
                        azure_instance_0 = instance['publicIpAddress']
                    elif instance['id'] == 'Instance1':
                        azure_instance_1 = instance['publicIpAddress']

                # Get Azure connected subnets
                if vwan_config['connectedVirtualNetworks']:
                    azure_connected_subnets = vwan_config[
                        'connectedVirtualNetworks']

                # Get specific vwan tag
                for tag in tags:
                    if re.match(MerakiConfig.primary_tag_regex, tag):
                        specific_tag = tag

                # Build meraki configurations for Azure VWAN VPN Gateway Instance 0 & 1
                azure_instance_0_config = get_meraki_ipsec_config(
                    netname, azure_instance_0, azure_connected_subnets, psk,
                    specific_tag)
                azure_instance_1_config = get_meraki_ipsec_config(
                    f"{netname}-sec", azure_instance_1,
                    azure_connected_subnets, psk, f"{specific_tag}-sec")

                primary_peer_exists = False
                secondary_peer_exists = False

                for site in new_meraki_vpns:
                    if site['name'] == netname:
                        primary_peer_exists = True
                    if site['name'] == f"{netname}-sec":
                        secondary_peer_exists = True

                if primary_peer_exists:
                    for vpn_peer in new_meraki_vpns:
                        if vpn_peer['name'] == netname:
                            vpn_peer['secret'] = psk
                            vpn_peer[
                                'privateSubnets'] = azure_connected_subnets
                else:
                    new_meraki_vpns.append(azure_instance_0_config)

                if secondary_peer_exists:
                    for vpn_peer in new_meraki_vpns:
                        if vpn_peer['name'] == f"{netname}-sec":
                            vpn_peer['secret'] = psk
                            vpn_peer[
                                'privateSubnets'] = azure_connected_subnets
                else:
                    new_meraki_vpns.append(azure_instance_1_config)

                found_tagged_networks = True

            if not found_tagged_networks:
                logging.info(f"No tagged networks found for hub {hub}.")
                return

            # Update Meraki VPN config
            update_meraki_vpn = mdashboard.organizations.updateOrganizationThirdPartyVPNPeers(
                MerakiConfig.org_id, new_meraki_vpns)

            logging.info("VPN Peers updated!")

            # Cleanup any found vwan-apply-now tags
            if len(remove_network_id_list) > 0:
                clean_meraki_vwan_tags(mdashboard, _VWAN_APPLY_NOW_TAG,
                                       tags_network)
    else:
        logging.info(
            "Maintenance mode detected but it is not during scheduled hours "
            f"or the {_VWAN_APPLY_NOW_TAG} tag has not been detected. Skipping updates"
        )