Create the let's encrypt app to verify the ownership of the domain
345288
def create_le_verification_app(self):
        
        if self.LETSENCRYPT_VERIFY_APP_NAME in self._apps:
            logger.debug(
                "The LE verification APP already exists as %s" % self.LETSENCRYPT_VERIFY_APP_NAME
            )
            verification_app = self._apps[self.LETSENCRYPT_VERIFY_APP_NAME]
        else:
            logger.info("Creating the identity-verification app for let's encrypt")
            verification_app = self.api.create_app(
                self.LETSENCRYPT_VERIFY_APP_NAME,
                'static_php70',
            )
            self._apps[self.LETSENCRYPT_VERIFY_APP_NAME] = verification_app

        # LE use the .well-known subfolder of the domain to do its verifications.
        # we will mount the app in the .well-known path, so we apply an hack to serve
        # the app-folder/.well-known on root
        app_root = os.path.join('~/webapps', self.LETSENCRYPT_VERIFY_APP_NAME)
        well_known_folder = os.path.join(app_root, '.well-known')

        if not is_link(well_known_folder):
            logger.info("Preparing static app for the verification")
            run('ln -s {app_root} {well_known_folder}'.format(**locals()))
        return verification_app
937830
def show_rsa(minion_id, dns_name):
    '''
    
    '''
    cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
    bank = 'digicert/domains'
    data = cache.fetch(
        bank, dns_name
    )
    return data['private_key']
647096
def certify(self, no_confirm=True, manual=False):
        

        if not self.domain:
            raise ClickException("Can't certify a domain without " + click.style("domain", fg="red", bold=True) + " configured!")

        if not no_confirm: # pragma: no cover
            confirm = input("Are you sure you want to certify? [y/n] ")
            if confirm != 'y':
                return

        # Make sure this isn't already deployed.
        deployed_versions = self.zappa.get_lambda_function_versions(self.lambda_name)
        if len(deployed_versions) == 0:
            raise ClickException("This application " + click.style("isn't deployed yet", fg="red") +
                                 " - did you mean to call " + click.style("deploy", bold=True) + "?")


        account_key_location = self.stage_config.get('lets_encrypt_key', None)
        cert_location = self.stage_config.get('certificate', None)
        cert_key_location = self.stage_config.get('certificate_key', None)
        cert_chain_location = self.stage_config.get('certificate_chain', None)
        cert_arn = self.stage_config.get('certificate_arn', None)
        base_path = self.stage_config.get('base_path', None)

        # These are sensitive
        certificate_body = None
        certificate_private_key = None
        certificate_chain = None

        # Prepare for custom Let's Encrypt
        if not cert_location and not cert_arn:
            if not account_key_location:
                raise ClickException("Can't certify a domain without " + click.style("lets_encrypt_key", fg="red", bold=True) +
                                     " or " + click.style("certificate", fg="red", bold=True)+
                                     " or " + click.style("certificate_arn", fg="red", bold=True) + " configured!")

            # Get install account_key to /tmp/account_key.pem
            from .letsencrypt import gettempdir
            if account_key_location.startswith('s3://'):
                bucket, key_name = parse_s3_url(account_key_location)
                self.zappa.s3_client.download_file(bucket, key_name, os.path.join(gettempdir(), 'account.key'))
            else:
                from shutil import copyfile
                copyfile(account_key_location, os.path.join(gettempdir(), 'account.key'))

        # Prepare for Custom SSL
        elif not account_key_location and not cert_arn:
            if not cert_location or not cert_key_location or not cert_chain_location:
                raise ClickException("Can't certify a domain without " +
                                     click.style("certificate, certificate_key and certificate_chain", fg="red", bold=True) + " configured!")

            # Read the supplied certificates.
            with open(cert_location) as f:
                certificate_body = f.read()

            with open(cert_key_location) as f:
                certificate_private_key = f.read()

            with open(cert_chain_location) as f:
                certificate_chain = f.read()


        click.echo("Certifying domain " + click.style(self.domain, fg="green", bold=True) + "..")

        # Get cert and update domain.

        # Let's Encrypt
        if not cert_location and not cert_arn:
            from .letsencrypt import get_cert_and_update_domain
            cert_success = get_cert_and_update_domain(
                    self.zappa,
                    self.lambda_name,
                    self.api_stage,
                    self.domain,
                    manual
                )

        # Custom SSL / ACM
        else:
            route53 = self.stage_config.get('route53_enabled', True)
            if not self.zappa.get_domain_name(self.domain, route53=route53):
                dns_name = self.zappa.create_domain_name(
                    domain_name=self.domain,
                    certificate_name=self.domain + "-Zappa-Cert",
                    certificate_body=certificate_body,
                    certificate_private_key=certificate_private_key,
                    certificate_chain=certificate_chain,
                    certificate_arn=cert_arn,
                    lambda_name=self.lambda_name,
                    stage=self.api_stage,
                    base_path=base_path
                )
                if route53:
                    self.zappa.update_route53_records(self.domain, dns_name)
                print("Created a new domain name with supplied certificate. Please note that it can take up to 40 minutes for this domain to be "
                      "created and propagated through AWS, but it requires no further work on your part.")
            else:
                self.zappa.update_domain_name(
                    domain_name=self.domain,
                    certificate_name=self.domain + "-Zappa-Cert",
                    certificate_body=certificate_body,
                    certificate_private_key=certificate_private_key,
                    certificate_chain=certificate_chain,
                    certificate_arn=cert_arn,
                    lambda_name=self.lambda_name,
                    stage=self.api_stage,
                    route53=route53,
                    base_path=base_path
                )

            cert_success = True

        if cert_success:
            click.echo("Certificate " + click.style("updated", fg="green", bold=True) + "!")
        else:
            click.echo(click.style("Failed", fg="red", bold=True) + " to generate or install certificate! :(")
            click.echo("\n==============\n")
            shamelessly_promote()
294947
def _generateForTokenSecurity(self,
                                  username, password,
                                  tokenUrl,
                                  expiration=None,
                                  client='requestip'):
        

        query_dict = {'username': username,
                      'password': password,
                      'expiration':str(_defaultTokenExpiration),
                      'client': client,
                      'f': 'json'}
        if client == "referer":
            query_dict['referer'] = self._referer_url
        if expiration is not None:
            query_dict['expiration'] = expiration

        secHandler = None
        if self.cookiejar is not None:
            secHandler = self
            if secHandler is not None:
                secHandler._method = "HANDLER"
        token = self._post(url=tokenUrl,
                           param_dict=query_dict,
                           securityHandler=secHandler,
                           proxy_port=self._proxy_port,
                           proxy_url=self._proxy_url)
        if self.cookiejar is not None:
            if secHandler is not None:
                secHandler._method = "TOKEN"
        if 'error' in token:
            self._token = None
            self._token_created_on = None
            self._token_expires_on = None
            self._expires_in = None

            return token
        elif 'status' in token:
            self._token = None
            self._token_created_on = None
            self._token_expires_on = None
            self._expires_in = None
            #print token['message']
            return token

        else:
            self._token = token['token']
            self._token_created_on = datetime.datetime.now()
            self._token_expires_on = datetime.datetime.fromtimestamp(token['expires'] /1000) - \
                datetime.timedelta(seconds=1)
            self._expires_in = (self._token_expires_on - self._token_created_on).total_seconds()
            return token['token']
1140990
def _populate_domain(self):
        '''
        '''

        self.domain = {}
        for device in self.devices:
            device_name = get_device_info(device).name
            ca_devices = \
                device.tm.cm.trust_domains.trust_domain.load(
                    name='Root'
                ).caDevices
            self.domain[device_name] = [
                d.replace('/%s/' % self.partition, '') for d in ca_devices
            ]
408653
def create_domain(self, domain_name):
        
        params = {'DomainName':domain_name}
        d = self.get_object('CreateDomain', params, Domain)
        d.name = domain_name
        return d
370109
def from_domain(cls, domain, *args, **kwargs):
        
        version = kwargs.pop('version', None)
        require = kwargs.pop('require_https', False)
        return cls(Hive.from_domain(domain, version, require), *args, **kwargs)
394766
def create(self, key=None, label=None):
        
        key = '%s' % key
        url = self.bitbucket.url('SET_SSH_KEY')
        return self.bitbucket.dispatch('POST', url, auth=self.bitbucket.auth, key=key, label=label)
478009
def _authenticate(self):
        """"""
        response = self._get("/v1/domains/{0}".format(self.domain))

        self.domain_id = response["domain"]["id"]
387346
def run_putgist(filename, user, **kwargs):
    """"""
    assume_yes = kwargs.get("yes_to_all")
    private = kwargs.get("private")
    getgist = GetGist(
        user=user,
        filename=filename,
        assume_yes=assume_yes,
        create_private=private,
        allow_none=True,
    )
    getgist.put()
1326318
def _init_server_authentication(self, ssl_verify: OpenSslVerifyEnum, ssl_verify_locations: Optional[str]) -> None:
        
        self._ssl_ctx.set_verify(ssl_verify.value)
        if ssl_verify_locations:
            # Ensure the file exists
            with open(ssl_verify_locations):
                pass
            self._ssl_ctx.load_verify_locations(ssl_verify_locations)
1329652
def install(self):  # pragma: no cover
        """"""
        keys = self.get_keys_from_ldap()
        for user, ssh_keys in keys.items():
            user_dir = API.__authorized_keys_path(user)
            if not os.path.isdir(user_dir):
                os.makedirs(user_dir)
            authorized_keys_file = os.path.join(user_dir, 'authorized_keys')
            with open(authorized_keys_file, 'w') as FILE:
                print("\n".join([k.decode() for k in ssh_keys]), file=FILE)
611881
def security(self, domains):
        
        api_name = 'opendns-security'
        fmt_url_path = u'security/name/{0}.json'
        return self._multi_get(api_name, fmt_url_path, domains)
49582
def privateparts(self, domain):
        
        s = self.privatesuffix(domain)
        if s is None:
            return None
        else:
            # I know the domain is valid and ends with private suffix
            pre = domain[0:-(len(s)+1)]
            if pre == "":
                return (s,)
            else:
                return tuple(pre.split(".") + [s])
1332745
def auth_app(self, app_id, app_secret, auth_code, state=''):
        
        headers = {
            'Content-type': 'application/json'
        }
        payload = {
            'application': app_id,
            'auth_code': auth_code,
            'state': state
        }
        try:
            full_url = utils.urljoin(
                self.host,
                '/api/v1/application-tokens/validate'
            )
            response = requests.post(
                full_url,
                data=json.dumps(payload),
                headers=headers,
                verify=self.tls_verify
            )
        except RequestException:
            raise exceptions.TaigaRestException(
                full_url, 400,
                'NETWORK ERROR', 'POST'
            )
        if response.status_code != 200:
            raise exceptions.TaigaRestException(
                full_url,
                response.status_code,
                response.text,
                'POST'
            )
        cyphered_token = response.json().get('cyphered_token', '')
        if cyphered_token:
            from jwkest.jwk import SYMKey
            from jwkest.jwe import JWE

            sym_key = SYMKey(key=app_secret, alg='A128KW')
            data, success = JWE().decrypt(cyphered_token, keys=[sym_key]), True
            if isinstance(data, tuple):
                data, success = data
            try:
                self.token = json.loads(data.decode('utf-8')).get('token', None)
            except ValueError:  # pragma: no cover
                self.token = None
            if not success:
                self.token = None
        else:
            self.token = None

        if self.token is None:
            raise exceptions.TaigaRestException(
                full_url, 400,
                'INVALID TOKEN', 'POST'
            )

        self.raw_request = RequestMaker('/api/v1', self.host, self.token,
                                        'Application', self.tls_verify)
        self._init_resources()
432192
def create(gandi, private_key, certificate, certificate_id):
    
    if not certificate and not certificate_id:
        gandi.echo('One of --certificate or --certificate-id is needed.')
        return
    if certificate and certificate_id:
        gandi.echo('Only one of --certificate or --certificate-id is needed.')

    if os.path.isfile(private_key):
        with open(private_key) as fhandle:
            private_key = fhandle.read()

    if certificate:
        if os.path.isfile(certificate):
            with open(certificate) as fhandle:
                certificate = fhandle.read()
    else:
        cert = gandi.certificate.info(certificate_id)
        certificate = gandi.certificate.pretty_format_cert(cert)

    result = gandi.hostedcert.create(private_key, certificate)

    output_keys = ['id', 'subject', 'date_created', 'date_expire',
                   'fqdns', 'vhosts']

    output_hostedcert(gandi, result, output_keys)

    return result
774894
def create_private_ip(linode_id):
    
    '''
    kwargs = {'LinodeID': linode_id}
    result = _query('linode', 'ip.addprivate', args=kwargs)

    return _clean_data(result)