def request_certificate(conf): dns_class = sewer.Route53Dns() # https://github.com/komuw/sewer/blob/43c3c8efae36489939d93096579ec54e941f67c7/sewer/client.py # 1. to create a new certificate: # Increase ACME_AUTH_STATUS_MAX_CHECKS for a timeout of about 60s. client = sewer.Client(domain_name=conf['domain'], domain_alt_names=conf['domain_alt_names'], contact_email=conf['contact_email'], dns_class=dns_class, account_key=load_from_s3(conf, "account.key.rsa"), ACME_AUTH_STATUS_MAX_CHECKS=8) if is_new(conf): print('requesting new certificate') certificate = client.cert() else: print('renewing existing certificate') certificate = client.renew() # will need to switch apache to not use chain or extract it per this issue certificate_key = client.certificate_key #https://github.com/komuw/sewer/issues/97 to get chain # openssl x509 -in some_certificate_and_chain.crt -text -noout account_key = client.account_key print("your certificate is:", certificate) #print("your certificate's key is:", certificate_key) #print("your letsencrypt.org account key is:", account_key) save_certificates_to_s3(conf, certificate, certificate_key, account_key)
def mock_instantiate_client(): self.client = sewer.Client( domain_name=self.domain_name, dns_class=self.dns_class, ACME_REQUEST_TIMEOUT=1, ACME_AUTH_STATUS_WAIT_PERIOD=0, ACME_DIRECTORY_URL=ACME_DIRECTORY_URL_STAGING, domain_alt_names="domain_alt_names")
def mock_instantiate_client(): self.client = sewer.Client( domain_name=self.domain_name, dns_class=self.dns_class, ACME_REQUEST_TIMEOUT=1, ACME_AUTH_STATUS_WAIT_PERIOD=0, ACME_DIRECTORY_URL= 'https://acme-staging-v02.api.letsencrypt.org/directory', domain_alt_names="domain_alt_names")
def setUp(self): self.domain_name = 'example.com' with mock.patch('requests.post') as mock_requests_post, mock.patch( 'requests.get') as mock_requests_get: mock_requests_post.return_value = test_utils.MockResponse() mock_requests_get.return_value = test_utils.MockResponse() self.dns_class = test_utils.ExmpleDnsProvider() self.client = sewer.Client( domain_name=self.domain_name, dns_class=self.dns_class, ACME_REQUEST_TIMEOUT=1, ACME_AUTH_STATUS_WAIT_PERIOD=0, ACME_DIRECTORY_URL=ACME_DIRECTORY_URL_STAGING)
def get_certs(domain, cert_dir, dns_class, email): try: create_dir(cert_dir) cert_file = cert_dir / 'certificate.crt' cert_key_file = cert_dir / 'certificate.key' account_key_file = cert_dir / 'account.key' renew = False account_key = None if cert_file.exists() and cert_key_file.exists( ) and account_key_file.exists(): renew = should_renew_cert(cert_file) if not renew: return True with open(account_key_file, 'r') as stream: account_key = stream.read() client = sewer.Client(domain_name=domain, dns_class=dns_class, account_key=account_key) certificate = None if renew: print( '{t.normal}Renewing certificate for {t.magenta}{t.bold}{domain}{t.normal}...' .format(t=Terminal(), domain=domain)) certificate = client.renew() else: print( '{t.normal}Requesting new certificate for {t.magenta}{t.bold}{domain}{t.normal}...' .format(t=Terminal(), domain=domain)) certificate = client.cert() certificate_key = client.certificate_key with open(cert_file, 'w') as f: f.write(certificate) with open(cert_key_file, 'w') as f: f.write(certificate_key) if account_key is None: account_key = client.account_key with open(account_key_file, 'w') as f: f.write(account_key) return True except Exception: print( '{t.normal}{t.bold}{t.red}Failed to get certificate for domain {domain}, due to error: {e}{t.normal}' .format(t=Terminal(), e=traceback.format_exc(), domain=domain)) return False
def setUp(self): self.domain_name = 'example.com' with mock.patch('requests.post') as mock_requests_post, mock.patch( 'requests.get') as mock_requests_get: mock_requests_post.return_value = test_utils.MockResponse() mock_requests_get.return_value = test_utils.MockResponse() self.dns_class = test_utils.ExmpleDnsProvider() self.client = sewer.Client( domain_name=self.domain_name, dns_class=self.dns_class, ACME_REQUEST_TIMEOUT=1, ACME_AUTH_STATUS_WAIT_PERIOD=0, ACME_DIRECTORY_URL= 'https://acme-staging-v02.api.letsencrypt.org/directory')
def setUp(self): self.domain_name = "example.com" with mock.patch("requests.post") as mock_requests_post, mock.patch( "requests.get" ) as mock_requests_get: mock_requests_post.return_value = test_utils.MockResponse() mock_requests_get.return_value = test_utils.MockResponse() self.auth_provider = test_utils.ExmpleHttpProvider() self.client = sewer.Client( domain_name=self.domain_name, auth_provider=self.auth_provider, ACME_REQUEST_TIMEOUT=1, ACME_AUTH_STATUS_WAIT_PERIOD=0, ACME_DIRECTORY_URL=ACME_DIRECTORY_URL_STAGING, )
def setUp(self): self.domain_name = 'example.com' with mock.patch('requests.post') as mock_requests_post, mock.patch( 'requests.get') as mock_requests_get: mock_requests_post.return_value = test_utils.MockResponse() mock_requests_get.return_value = test_utils.MockResponse() self.dns_class = test_utils.ExmpleDnsProvider() self.client = sewer.Client( domain_name=self.domain_name, dns_class=self.dns_class, ACME_CHALLENGE_WAIT_PERIOD=0, GET_NONCE_URL= "https://acme-staging.api.letsencrypt.org/directory", ACME_CERTIFICATE_AUTHORITY_URL= "https://acme-staging.api.letsencrypt.org")
def setUp(self): self.domain_name = 'exampleSAN.com' self.domain_alt_names = [ 'blog.exampleSAN.com', 'staging.exampleSAN.com', 'www.exampleSAN.com' ] with mock.patch('requests.post') as mock_requests_post, mock.patch( 'requests.get') as mock_requests_get: mock_requests_post.return_value = test_utils.MockResponse() mock_requests_get.return_value = test_utils.MockResponse() self.dns_class = test_utils.ExmpleDnsProvider() self.client = sewer.Client( domain_name=self.domain_name, dns_class=self.dns_class, domain_alt_names=self.domain_alt_names, ACME_REQUEST_TIMEOUT=1, ACME_AUTH_STATUS_WAIT_PERIOD=0, ACME_DIRECTORY_URL=ACME_DIRECTORY_URL_STAGING) super(TestClientForSAN, self).setUp()
def setUp(self): self.domain_name = '*.exampleSTARcom' self.domain_alt_names = [ 'blog.exampleSAN.com', 'staging.exampleSAN.com', 'www.exampleSAN.com' ] with mock.patch('requests.post') as mock_requests_post, mock.patch( 'requests.get') as mock_requests_get: mock_requests_post.return_value = test_utils.MockResponse() mock_requests_get.return_value = test_utils.MockResponse() self.dns_class = test_utils.ExmpleDnsProvider() self.client = sewer.Client( domain_name=self.domain_name, dns_class=self.dns_class, domain_alt_names=self.domain_alt_names, ACME_REQUEST_TIMEOUT=1, ACME_AUTH_STATUS_WAIT_PERIOD=0, ACME_AUTH_STATUS_MAX_CHECKS=1, ACME_DIRECTORY_URL= 'https://acme-staging-v02.api.letsencrypt.org/directory') super(TestClientForWildcard, self).setUp()
def setUp(self): self.domain_name = "*.exampleSTARcom" self.domain_alt_names = [ "blog.exampleSAN.com", "staging.exampleSAN.com", "www.exampleSAN.com", ] with mock.patch("requests.post") as mock_requests_post, mock.patch( "requests.get" ) as mock_requests_get: mock_requests_post.return_value = test_utils.MockResponse() mock_requests_get.return_value = test_utils.MockResponse() self.dns_class = test_utils.ExmpleDnsProvider() self.client = sewer.Client( domain_name=self.domain_name, dns_class=self.dns_class, domain_alt_names=self.domain_alt_names, ACME_REQUEST_TIMEOUT=1, ACME_AUTH_STATUS_WAIT_PERIOD=0, ACME_AUTH_STATUS_MAX_CHECKS=1, ACME_DIRECTORY_URL=ACME_DIRECTORY_URL_STAGING, ) super(TestClientForWildcard, self).setUp()
def crate_let_by_oper(self, data): result = {} result['status'] = False try: if not data['email']: data['email'] = public.M('users').getField('email') #手动解析记录值 if not 'renew' in data: BTPanel.dns_client = sewer.Client( domain_name=data['first_domain'], dns_class=None, account_key=data['account_key'], domain_alt_names=data['domains'], contact_email=str(data['email']), ACME_AUTH_STATUS_WAIT_PERIOD=15, ACME_AUTH_STATUS_MAX_CHECKS=5, ACME_REQUEST_TIMEOUT=20, ACME_DIRECTORY_URL=self.let_url) domain_dns_value = "placeholder" dns_names_to_delete = [] BTPanel.dns_client.acme_register() authorizations, finalize_url = BTPanel.dns_client.apply_for_cert_issuance( ) responders = [] for url in authorizations: identifier_auth = BTPanel.dns_client.get_identifier_authorization( url) authorization_url = identifier_auth["url"] dns_name = identifier_auth["domain"] dns_token = identifier_auth["dns_token"] dns_challenge_url = identifier_auth["dns_challenge_url"] acme_keyauthorization, domain_dns_value = BTPanel.dns_client.get_keyauthorization( dns_token) acme_name = self.get_acme_name(dns_name) dns_names_to_delete.append({ "dns_name": public.de_punycode(dns_name), "acme_name": acme_name, "domain_dns_value": domain_dns_value }) responders.append({ "authorization_url": authorization_url, "acme_keyauthorization": acme_keyauthorization, "dns_challenge_url": dns_challenge_url, }) dns = {} dns['dns_names'] = dns_names_to_delete dns['responders'] = responders dns['finalize_url'] = finalize_url return dns else: responders = data['dns']['responders'] dns_names_to_delete = data['dns']['dns_names'] finalize_url = data['dns']['finalize_url'] for i in responders: auth_status_response = BTPanel.dns_client.check_authorization_status( i["authorization_url"]) if auth_status_response.json()["status"] == "pending": BTPanel.dns_client.respond_to_challenge( i["acme_keyauthorization"], i["dns_challenge_url"]) for i in responders: BTPanel.dns_client.check_authorization_status( i["authorization_url"], ["valid", "invalid"]) certificate_url = BTPanel.dns_client.send_csr(finalize_url) certificate = BTPanel.dns_client.download_certificate( certificate_url) if certificate: certificate = self.split_ca_data(certificate) result['cert'] = certificate['cert'] result['ca_data'] = certificate['ca_data'] result['key'] = BTPanel.dns_client.certificate_key result['account_key'] = BTPanel.dns_client.account_key result['status'] = True BTPanel.dns_client = None else: result['msg'] = '证书获取失败,请稍后重试.' except Exception as e: res = str(e).split('>>>>') err = False try: err = json.loads(res[1]) except: err = False result['msg'] = [self.get_error(res[0]), err] return result
def crate_let_by_dns(self, data): dns_class = self.get_dns_class(data) if not dns_class: self.write_log("|-错误,DNS连接失败,请检查密钥是否正确。") self.write_log("|-已退出申请程序!") self.write_log("=" * 50) return public.returnMsg(False, 'DNS连接失败,请检查密钥是否正确.') result = {} result['status'] = False try: log_level = "INFO" if data['account_key']: log_level = 'ERROR' if not data['email']: data['email'] = public.M('users').getField('email') self.write_log("|-正在初始化ACME协议...") client = sewer.Client(domain_name=data['first_domain'], domain_alt_names=data['domains'], account_key=data['account_key'], contact_email=str(data['email']), LOG_LEVEL=log_level, ACME_AUTH_STATUS_WAIT_PERIOD=15, ACME_AUTH_STATUS_MAX_CHECKS=5, ACME_REQUEST_TIMEOUT=20, dns_class=dns_class, ACME_DIRECTORY_URL=self.let_url) domain_dns_value = "placeholder" dns_names_to_delete = [] try: self.write_log("|-正在注册帐户...") client.acme_register() authorizations, finalize_url = client.apply_for_cert_issuance() responders = [] self.write_log("|-正在获取验证信息...") for url in authorizations: identifier_auth = client.get_identifier_authorization(url) authorization_url = identifier_auth["url"] dns_name = identifier_auth["domain"] dns_token = identifier_auth["dns_token"] dns_challenge_url = identifier_auth["dns_challenge_url"] acme_keyauthorization, domain_dns_value = client.get_keyauthorization( dns_token) self.write_log("|-正在添加解析记录,域名[{}],记录值[{}]...".format( dns_name, domain_dns_value)) dns_class.create_dns_record(public.de_punycode(dns_name), domain_dns_value) dns_names_to_delete.append({ "dns_name": public.de_punycode(dns_name), "domain_dns_value": domain_dns_value }) responders.append({ "dns_name": dns_name, "domain_dns_value": domain_dns_value, "authorization_url": authorization_url, "acme_keyauthorization": acme_keyauthorization, "dns_challenge_url": dns_challenge_url }) try: for i in responders: self.write_log("|-尝试验证解析结果,域名[{}],记录值[{}]...".format( i['dns_name'], i['domain_dns_value'])) self.check_dns(self.get_acme_name(i['dns_name']), i['domain_dns_value']) self.write_log("|-请求CA验证域名[{}]...".format( i['dns_name'])) auth_status_response = client.check_authorization_status( i["authorization_url"]) r_data = auth_status_response.json() if r_data["status"] == "pending": client.respond_to_challenge( i["acme_keyauthorization"], i["dns_challenge_url"]) for i in responders: self.write_log("|-检查CA验证结果[{}]...".format( i['dns_name'])) client.check_authorization_status( i["authorization_url"], ["valid", "invalid"]) except Exception as ex: self.write_log("|-发生错误,尝试重试一次 [{}]".format(ex)) for i in responders: self.write_log("|-尝试验证解析结果,域名[{}],记录值[{}]...".format( i['dns_name'], i['domain_dns_value'])) self.check_dns(self.get_acme_name(i['dns_name']), i['domain_dns_value']) self.write_log("|-请求CA验证域名[{}]...".format( i['dns_name'])) auth_status_response = client.check_authorization_status( i["authorization_url"]) r_data = auth_status_response.json() if r_data["status"] == "pending": client.respond_to_challenge( i["acme_keyauthorization"], i["dns_challenge_url"]) for i in responders: self.write_log("|-检查CA验证结果[{}]...".format( i['dns_name'])) client.check_authorization_status( i["authorization_url"], ["valid", "invalid"]) self.write_log("|-所有域名验证通过,正在发送CSR...") certificate_url = client.send_csr(finalize_url) self.write_log("|-正在获取证书内容...") certificate = client.download_certificate(certificate_url) if certificate: certificate = self.split_ca_data(certificate) result['cert'] = certificate['cert'] result['ca_data'] = certificate['ca_data'] result['key'] = client.certificate_key result['account_key'] = client.account_key result['status'] = True except Exception as e: raise e finally: try: for i in dns_names_to_delete: self.write_log("|-正在清除解析记录[{}]".format(i["dns_name"])) dns_class.delete_dns_record(i["dns_name"], i["domain_dns_value"]) except: pass except Exception as e: try: for i in dns_names_to_delete: self.write_log("|-正在清除解析记录[{}]".format(i["dns_name"])) dns_class.delete_dns_record(i["dns_name"], i["domain_dns_value"]) except: pass self.write_log("|-错误:{},退出申请程序。".format(public.get_error_info())) self.write_log("=" * 50) res = str(e).split('>>>>') err = False try: err = json.loads(res[1]) except: err = False result['msg'] = [self.get_error(res[0]), err] return result
def mock_create_acme_client(): sewer.Client( domain_name='example.com', dns_class=test_utils.ExmpleDnsProvider(), ACME_DIRECTORY_URL= 'https://acme-staging-v02.api.letsencrypt.org/directory')
def mock_create_acme_client(): sewer.Client(domain_name='example.com', dns_class=test_utils.ExmpleDnsProvider(), ACME_DIRECTORY_URL=ACME_DIRECTORY_URL_STAGING)
def crate_let_by_oper(self, data): result = {} result['status'] = False try: if not data['email']: data['email'] = public.M('users').getField('email') #手动解析记录值 if not 'renew' in data: self.write_log("|-Initializing ACME protocol...") BTPanel.dns_client = sewer.Client( domain_name=data['first_domain'], dns_class=None, account_key=data['account_key'], domain_alt_names=data['domains'], contact_email=str(data['email']), ACME_AUTH_STATUS_WAIT_PERIOD=15, ACME_AUTH_STATUS_MAX_CHECKS=5, ACME_REQUEST_TIMEOUT=20, ACME_DIRECTORY_URL=self.let_url) domain_dns_value = "placeholder" dns_names_to_delete = [] self.write_log("|-Registering account...") BTPanel.dns_client.acme_register() authorizations, finalize_url = BTPanel.dns_client.apply_for_cert_issuance( ) responders = [] self.write_log("|-Getting verification information...") for url in authorizations: identifier_auth = BTPanel.dns_client.get_identifier_authorization( url) authorization_url = identifier_auth["url"] dns_name = identifier_auth["domain"] dns_token = identifier_auth["dns_token"] dns_challenge_url = identifier_auth["dns_challenge_url"] acme_keyauthorization, domain_dns_value = BTPanel.dns_client.get_keyauthorization( dns_token) acme_name = self.get_acme_name(dns_name) dns_names_to_delete.append({ "dns_name": public.de_punycode(dns_name), "acme_name": acme_name, "domain_dns_value": domain_dns_value }) responders.append({ "dns_name": dns_name, "authorization_url": authorization_url, "acme_keyauthorization": acme_keyauthorization, "dns_challenge_url": dns_challenge_url, }) dns = {} dns['dns_names'] = dns_names_to_delete dns['responders'] = responders dns['finalize_url'] = finalize_url self.write_log( "|-Return the verification information to the front end, wait for the user to manually resolve the domain name and complete the verification..." ) return dns else: self.write_log("|-User submits verification request...") responders = data['dns']['responders'] dns_names_to_delete = data['dns']['dns_names'] finalize_url = data['dns']['finalize_url'] for i in responders: self.write_log( "|-Requesting CA to verify domain name [{}]...".format( i['dns_name'])) auth_status_response = BTPanel.dns_client.check_authorization_status( i["authorization_url"]) if auth_status_response.json()["status"] == "pending": BTPanel.dns_client.respond_to_challenge( i["acme_keyauthorization"], i["dns_challenge_url"]) for i in responders: self.write_log( "|-Get CA verification results [{}]...".format( i['dns_name'])) BTPanel.dns_client.check_authorization_status( i["authorization_url"], ["valid", "invalid"]) self.write_log( "|-All domain names are verified and CSR is being sent...") certificate_url = BTPanel.dns_client.send_csr(finalize_url) self.write_log("|-Getting certificate content...") certificate = BTPanel.dns_client.download_certificate( certificate_url) if certificate: certificate = self.split_ca_data(certificate) result['cert'] = certificate['cert'] result['ca_data'] = certificate['ca_data'] result['key'] = BTPanel.dns_client.certificate_key result['account_key'] = BTPanel.dns_client.account_key result['status'] = True BTPanel.dns_client = None else: result[ 'msg'] = 'Certificate acquisition failed, please try again later.' except Exception as e: self.write_log( "|-Error: {}, exited the application process.".format(e)) self.write_log("=" * 50) res = str(e).split('>>>>') err = False try: err = json.loads(res[1]) except: err = False result['msg'] = [self.get_error(res[0]), err] return result
def mock_create_acme_client(): sewer.Client(domain_name='example.com', dns_class=test_utils.ExmpleDnsProvider(), ACME_CERTIFICATE_AUTHORITY_URL= "https://acme-staging.api.letsencrypt.org")
def mock_create_acme_client(): sewer.Client( domain_name="example.com", auth_provider=test_utils.ExmpleAuthProvider(), ACME_DIRECTORY_URL=ACME_DIRECTORY_URL_STAGING, )
def crate_let_by_dns(self, data): dns_class = self.get_dns_class(data) if not dns_class: self.write_log(public.getMsg("DNS_APPLY_ERR")) self.write_log(public.getMsg("EXIT_APPLY_PROCESS")) self.write_log("=" * 50) return public.returnMsg(False, 'DNS_APPLY_ERR1') result = {} result['status'] = False try: log_level = "INFO" if data['account_key']: log_level = 'ERROR' if not data['email']: data['email'] = public.M('users').getField('email') self.write_log(public.getMsg("INIT_ACME")) client = sewer.Client(domain_name=data['first_domain'], domain_alt_names=data['domains'], account_key=data['account_key'], contact_email=str(data['email']), LOG_LEVEL=log_level, ACME_AUTH_STATUS_WAIT_PERIOD=15, ACME_AUTH_STATUS_MAX_CHECKS=5, ACME_REQUEST_TIMEOUT=20, dns_class=dns_class, ACME_DIRECTORY_URL=self.let_url) domain_dns_value = "placeholder" dns_names_to_delete = [] try: self.write_log(public.getMsg("REGISTER_ACCOUNT")) client.acme_register() authorizations, finalize_url = client.apply_for_cert_issuance() responders = [] self.write_log(public.getMsg("GET_VERIFICATION_INFO")) for url in authorizations: identifier_auth = client.get_identifier_authorization(url) authorization_url = identifier_auth["url"] dns_name = identifier_auth["domain"] dns_token = identifier_auth["dns_token"] dns_challenge_url = identifier_auth["dns_challenge_url"] acme_keyauthorization, domain_dns_value = client.get_keyauthorization( dns_token) self.write_log( public.getMsg("ADD_TXT_RECORD", (dns_name, domain_dns_value))) dns_class.create_dns_record(public.de_punycode(dns_name), domain_dns_value) dns_names_to_delete.append({ "dns_name": public.de_punycode(dns_name), "domain_dns_value": domain_dns_value }) responders.append({ "dns_name": dns_name, "domain_dns_value": domain_dns_value, "authorization_url": authorization_url, "acme_keyauthorization": acme_keyauthorization, "dns_challenge_url": dns_challenge_url }) try: for i in responders: self.write_log( public.getMsg( "CHECK_TXT_RECORD", (i['dns_name'], i['domain_dns_value']))) self.check_dns(self.get_acme_name(i['dns_name']), i['domain_dns_value']) self.write_log( public.getMsg("CA_CHECK_RECORD", (i['dns_name']))) auth_status_response = client.check_authorization_status( i["authorization_url"]) r_data = auth_status_response.json() if r_data["status"] == "pending": client.respond_to_challenge( i["acme_keyauthorization"], i["dns_challenge_url"]) for i in responders: self.write_log( public.getMsg("CHECK_CA_RES", (i['dns_name'], ))) client.check_authorization_status( i["authorization_url"], ["valid", "invalid"]) except Exception as ex: self.write_log( public.getMsg("APPLY_WITH_DNS_ERR", (str(ex), ))) for i in responders: self.write_log( public.getMsg( "CHECK_TXT_RECORD", (i['dns_name'], i['domain_dns_value']))) self.check_dns(self.get_acme_name(i['dns_name']), i['domain_dns_value']) self.write_log( public.getMsg("CA_CHECK_RECORD", (i['dns_name']))) auth_status_response = client.check_authorization_status( i["authorization_url"]) r_data = auth_status_response.json() if r_data["status"] == "pending": client.respond_to_challenge( i["acme_keyauthorization"], i["dns_challenge_url"]) for i in responders: self.write_log( public.getMsg("CHECK_CA_RES", (i['dns_name'], ))) client.check_authorization_status( i["authorization_url"], ["valid", "invalid"]) self.write_log(public.getMsg("ALL_DOMAIN_V_PASS")) certificate_url = client.send_csr(finalize_url) self.write_log(public.getMsg("FETCH_CERT_CONTENT")) certificate = client.download_certificate(certificate_url) if certificate: certificate = self.split_ca_data(certificate) result['cert'] = certificate['cert'] result['ca_data'] = certificate['ca_data'] result['key'] = client.certificate_key result['account_key'] = client.account_key result['status'] = True except Exception as e: raise e finally: try: for i in dns_names_to_delete: self.write_log( public.getMsg("CLEAR_RESOLVE_HISTORY", (i["dns_name"]))) dns_class.delete_dns_record(i["dns_name"], i["domain_dns_value"]) except: pass except Exception as e: try: for i in dns_names_to_delete: self.write_log( public.getMsg("CLEAR_RESOLVE_HISTORY", (i["dns_name"]))) dns_class.delete_dns_record(i["dns_name"], i["domain_dns_value"]) except: pass self.write_log( public.getMsg("DNS_APPLY_ERR", (str(public.get_error_info()), ))) self.write_log("=" * 50) res = str(e).split('>>>>') err = False try: err = json.loads(res[1]) except: err = False result['msg'] = [self.get_error(res[0]), err] return result
def mock_create_acme_client(): sewer.Client( domain_name="example.com", dns_class=test_utils.ExmpleDnsProvider(), # NOTE: dns_class used here ACME_DIRECTORY_URL=ACME_DIRECTORY_URL_STAGING, )
def crate_let_by_dns(self, data): dns_class = self.get_dns_class(data) if not dns_class: self.write_log( "|-The DNS connection failed. Please check if the key is correct." ) self.write_log("|-Exited the application process!") self.write_log("=" * 50) return public.returnMsg( False, 'The DNS connection failed. Please check if the key is correct.' ) result = {} result['status'] = False try: log_level = "INFO" if data['account_key']: log_level = 'ERROR' if not data['email']: data['email'] = public.M('users').getField('email') self.write_log("|-Initializing ACME protocol...") client = sewer.Client(domain_name=data['first_domain'], domain_alt_names=data['domains'], account_key=data['account_key'], contact_email=str(data['email']), LOG_LEVEL=log_level, ACME_AUTH_STATUS_WAIT_PERIOD=15, ACME_AUTH_STATUS_MAX_CHECKS=5, ACME_REQUEST_TIMEOUT=20, dns_class=dns_class, ACME_DIRECTORY_URL=self.let_url) domain_dns_value = "placeholder" dns_names_to_delete = [] try: self.write_log("|-Registering account...") client.acme_register() authorizations, finalize_url = client.apply_for_cert_issuance() responders = [] self.write_log("|-Getting verification information...") for url in authorizations: identifier_auth = client.get_identifier_authorization(url) authorization_url = identifier_auth["url"] dns_name = identifier_auth["domain"] dns_token = identifier_auth["dns_token"] dns_challenge_url = identifier_auth["dns_challenge_url"] acme_keyauthorization, domain_dns_value = client.get_keyauthorization( dns_token) self.write_log( "|-Adding resolution record, domain name [{}], record value [{}]..." .format(dns_name, domain_dns_value)) dns_class.create_dns_record(public.de_punycode(dns_name), domain_dns_value) dns_names_to_delete.append({ "dns_name": public.de_punycode(dns_name), "domain_dns_value": domain_dns_value }) responders.append({ "dns_name": dns_name, "domain_dns_value": domain_dns_value, "authorization_url": authorization_url, "acme_keyauthorization": acme_keyauthorization, "dns_challenge_url": dns_challenge_url }) try: for i in responders: self.write_log( "|-Attempt to verify the resolution result, domain name [{}], record value [{}]..." .format(i['dns_name'], i['domain_dns_value'])) self.check_dns(self.get_acme_name(i['dns_name']), i['domain_dns_value']) self.write_log( "|-Request CA to verify domain name [{}]...". format(i['dns_name'])) auth_status_response = client.check_authorization_status( i["authorization_url"]) r_data = auth_status_response.json() if r_data["status"] == "pending": client.respond_to_challenge( i["acme_keyauthorization"], i["dns_challenge_url"]) for i in responders: self.write_log( "|-Check CA verification results [{}]...".format( i['dns_name'])) client.check_authorization_status( i["authorization_url"], ["valid", "invalid"]) except Exception as ex: self.write_log( "|-An error occurred, try again [{}]".format(ex)) for i in responders: self.write_log( "|-Attempt to verify the resolution result, domain name [{}], record value [{}]..." .format(i['dns_name'], i['domain_dns_value'])) self.check_dns(self.get_acme_name(i['dns_name']), i['domain_dns_value']) self.write_log( "|-Request CA to verify domain name [{}]...". format(i['dns_name'])) auth_status_response = client.check_authorization_status( i["authorization_url"]) r_data = auth_status_response.json() if r_data["status"] == "pending": client.respond_to_challenge( i["acme_keyauthorization"], i["dns_challenge_url"]) for i in responders: self.write_log( "|-Check CA verification results [{}]...".format( i['dns_name'])) client.check_authorization_status( i["authorization_url"], ["valid", "invalid"]) self.write_log( "|-All domain names are verified and CSR is being sent...") certificate_url = client.send_csr(finalize_url) self.write_log("|-Fetching certificate content...") certificate = client.download_certificate(certificate_url) if certificate: certificate = self.split_ca_data(certificate) result['cert'] = certificate['cert'] result['ca_data'] = certificate['ca_data'] result['key'] = client.certificate_key result['account_key'] = client.account_key result['status'] = True except Exception as e: raise e finally: try: for i in dns_names_to_delete: self.write_log( "|-Clearing parsing history [{}]".format( i["dns_name"])) dns_class.delete_dns_record(i["dns_name"], i["domain_dns_value"]) except: pass except Exception as e: try: for i in dns_names_to_delete: self.write_log("|-Clearing parsing history [{}]".format( i["dns_name"])) dns_class.delete_dns_record(i["dns_name"], i["domain_dns_value"]) except: pass self.write_log("|-Error: {}, exit the application process.".format( public.get_error_info())) self.write_log("=" * 50) res = str(e).split('>>>>') err = False try: err = json.loads(res[1]) except: err = False result['msg'] = [self.get_error(res[0]), err] return result
def crate_let_by_dns(self, data): dns_class = self.get_dns_class(data) if not dns_class: return public.returnMsg(False, 'DNS连接失败,请检查密钥是否正确.') result = {} result['status'] = False try: log_level = "INFO" if data['account_key']: log_level = 'ERROR' if not data['email']: data['email'] = public.M('users').getField('email') client = sewer.Client(domain_name=data['first_domain'], domain_alt_names=data['domains'], account_key=data['account_key'], contact_email=str(data['email']), LOG_LEVEL=log_level, ACME_AUTH_STATUS_WAIT_PERIOD=15, ACME_AUTH_STATUS_MAX_CHECKS=5, ACME_REQUEST_TIMEOUT=20, dns_class=dns_class, ACME_DIRECTORY_URL=self.let_url) domain_dns_value = "placeholder" dns_names_to_delete = [] try: client.acme_register() authorizations, finalize_url = client.apply_for_cert_issuance() responders = [] for url in authorizations: identifier_auth = client.get_identifier_authorization(url) authorization_url = identifier_auth["url"] dns_name = identifier_auth["domain"] dns_token = identifier_auth["dns_token"] dns_challenge_url = identifier_auth["dns_challenge_url"] acme_keyauthorization, domain_dns_value = client.get_keyauthorization( dns_token) dns_class.create_dns_record(public.de_punycode(dns_name), domain_dns_value) self.check_dns(self.get_acme_name(dns_name), domain_dns_value) dns_names_to_delete.append({ "dns_name": public.de_punycode(dns_name), "domain_dns_value": domain_dns_value }) responders.append({ "authorization_url": authorization_url, "acme_keyauthorization": acme_keyauthorization, "dns_challenge_url": dns_challenge_url }) try: for i in responders: auth_status_response = client.check_authorization_status( i["authorization_url"]) r_data = auth_status_response.json() if r_data["status"] == "pending": client.respond_to_challenge( i["acme_keyauthorization"], i["dns_challenge_url"]) for i in responders: client.check_authorization_status( i["authorization_url"], ["valid", "invalid"]) except: for i in responders: auth_status_response = client.check_authorization_status( i["authorization_url"]) r_data = auth_status_response.json() if r_data["status"] == "pending": client.respond_to_challenge( i["acme_keyauthorization"], i["dns_challenge_url"]) for i in responders: client.check_authorization_status( i["authorization_url"], ["valid", "invalid"]) certificate_url = client.send_csr(finalize_url) certificate = client.download_certificate(certificate_url) if certificate: certificate = self.split_ca_data(certificate) result['cert'] = certificate['cert'] result['ca_data'] = certificate['ca_data'] result['key'] = client.certificate_key result['account_key'] = client.account_key result['status'] = True except Exception as e: raise e finally: try: for i in dns_names_to_delete: dns_class.delete_dns_record(i["dns_name"], i["domain_dns_value"]) except: pass except Exception as e: try: for i in dns_names_to_delete: dns_class.delete_dns_record(i["dns_name"], i["domain_dns_value"]) except: pass res = str(e).split('>>>>') err = False try: err = json.loads(res[1]) except: err = False result['msg'] = [self.get_error(res[0]), err] return result
def crate_let_by_file(self,data): result = {} result['status'] = False result['clecks'] = [] try: log_level = "INFO" if data['account_key']: log_level = 'ERROR' if not data['email']: data['email'] = public.M('users').getField('email') client = sewer.Client(domain_name = data['first_domain'],dns_class = None,account_key = data['account_key'],domain_alt_names = data['domains'],contact_email = str(data['email']),LOG_LEVEL = log_level,ACME_AUTH_STATUS_WAIT_PERIOD = 15,ACME_AUTH_STATUS_MAX_CHECKS = 5,ACME_REQUEST_TIMEOUT = 20,ACME_DIRECTORY_URL = self.let_url) client.acme_register() authorizations, finalize_url = client.apply_for_cert_issuance() responders = [] sucess_domains = [] for url in authorizations: identifier_auth = self.get_identifier_authorization(client,url) authorization_url = identifier_auth["url"] http_name = identifier_auth["domain"] http_token = identifier_auth["http_token"] http_challenge_url = identifier_auth["http_challenge_url"] acme_keyauthorization, domain_http_value = client.get_keyauthorization(http_token) acme_dir = '%s/.well-known/acme-challenge' % (data['site_dir']); if not os.path.exists(acme_dir): os.makedirs(acme_dir) #写入token wellknown_path = acme_dir + '/' + http_token public.writeFile(wellknown_path,acme_keyauthorization) wellknown_url = "http://{0}/.well-known/acme-challenge/{1}".format(http_name, http_token) result['clecks'].append({'wellknown_url':wellknown_url,'http_token':http_token}); is_check = False n = 0 while n < 5: print("wait_check_authorization_status") try: retkey = public.httpGet(wellknown_url,20) if retkey == acme_keyauthorization: is_check = True break except : pass n += 1 time.sleep(1) sucess_domains.append(http_name) responders.append({"authorization_url": authorization_url, "acme_keyauthorization": acme_keyauthorization,"http_challenge_url": http_challenge_url}) if len(sucess_domains) > 0: #验证 for i in responders: auth_status_response = client.check_authorization_status(i["authorization_url"]) if auth_status_response.json()["status"] == "pending": client.respond_to_challenge(i["acme_keyauthorization"], i["http_challenge_url"]).json() for i in responders: client.check_authorization_status(i["authorization_url"], ["valid","invalid"]) certificate_url = client.send_csr(finalize_url) certificate = client.download_certificate(certificate_url) if certificate: certificate = self.split_ca_data(certificate) result['cert'] = certificate['cert'] result['ca_data'] = certificate['ca_data'] result['key'] = client.certificate_key result['account_key'] = client.account_key result['status'] = True else: result['msg'] = 'Certificate acquisition failed, please try again later.' else: result['msg'] = "The signing failed, we were unable to verify your domain name:<p>1. Check if the domain name is bound to the corresponding site.</p><p>2. Check if the domain name is correctly resolved to the server, or the resolution is not fully effective.</p><p>3. If your site has a reverse proxy set up, or if you are using a CDN, please turn it off first.</p><p>4. If your site has a 301 redirect, please turn it off first</p><p>5. If the above checks confirm that there is no problem, please try to change the DNS service provider.</p>'" except Exception as e: res = str(e).split('>>>>') err = False try: err = json.loads(res[1]) except: err = False result['msg'] = [self.get_error(res[0]),err] return result
def crate_let_by_file(self, data): result = {} result['status'] = False result['clecks'] = [] try: log_level = "INFO" if data['account_key']: log_level = 'ERROR' if not data['email']: data['email'] = public.M('users').getField('email') client = sewer.Client(domain_name=data['first_domain'], dns_class=None, account_key=data['account_key'], domain_alt_names=data['domains'], contact_email=str(data['email']), LOG_LEVEL=log_level, ACME_AUTH_STATUS_WAIT_PERIOD=15, ACME_AUTH_STATUS_MAX_CHECKS=5, ACME_REQUEST_TIMEOUT=20, ACME_DIRECTORY_URL=self.let_url) client.acme_register() authorizations, finalize_url = client.apply_for_cert_issuance() responders = [] sucess_domains = [] for url in authorizations: identifier_auth = self.get_identifier_authorization( client, url) authorization_url = identifier_auth["url"] http_name = identifier_auth["domain"] http_token = identifier_auth["http_token"] http_challenge_url = identifier_auth["http_challenge_url"] acme_keyauthorization, domain_http_value = client.get_keyauthorization( http_token) acme_dir = '%s/.well-known/acme-challenge' % (data['site_dir']) if not os.path.exists(acme_dir): os.makedirs(acme_dir) #写入token wellknown_path = acme_dir + '/' + http_token public.writeFile(wellknown_path, acme_keyauthorization) wellknown_url = "http://{0}/.well-known/acme-challenge/{1}".format( http_name, http_token) result['clecks'].append({ 'wellknown_url': wellknown_url, 'http_token': http_token }) is_check = False n = 0 while n < 5: print("wait_check_authorization_status") try: retkey = public.httpGet(wellknown_url, 20) if retkey == acme_keyauthorization: is_check = True break except: pass n += 1 time.sleep(1) sucess_domains.append(http_name) responders.append({ "authorization_url": authorization_url, "acme_keyauthorization": acme_keyauthorization, "http_challenge_url": http_challenge_url }) if len(sucess_domains) > 0: #验证 for i in responders: auth_status_response = client.check_authorization_status( i["authorization_url"]) if auth_status_response.json()["status"] == "pending": client.respond_to_challenge( i["acme_keyauthorization"], i["http_challenge_url"]).json() for i in responders: client.check_authorization_status(i["authorization_url"], ["valid", "invalid"]) certificate_url = client.send_csr(finalize_url) certificate = client.download_certificate(certificate_url) if certificate: certificate = self.split_ca_data(certificate) result['cert'] = certificate['cert'] result['ca_data'] = certificate['ca_data'] result['key'] = client.certificate_key result['account_key'] = client.account_key result['status'] = True else: result['msg'] = '证书获取失败,请稍后重试.' else: result[ 'msg'] = "签发失败,我们无法验证您的域名:<p>1、检查域名是否绑定到对应站点</p><p>2、检查域名是否正确解析到本服务器,或解析还未完全生效</p><p>3、如果您的站点设置了反向代理,或使用了CDN,请先将其关闭</p><p>4、如果您的站点设置了301重定向,请先将其关闭</p><p>5、如果以上检查都确认没有问题,请尝试更换DNS服务商</p>'" except Exception as e: res = str(e).split('>>>>') err = False try: err = json.loads(res[1]) except: err = False result['msg'] = [self.get_error(res[0]), err] return result
def crate_let_by_file(self, data): result = {} result['status'] = False result['clecks'] = [] try: self.write_log(public.getMsg("INIT_ACME")) log_level = "INFO" if data['account_key']: log_level = 'ERROR' if not data['email']: data['email'] = public.M('users').getField('email') client = sewer.Client(domain_name=data['first_domain'], dns_class=None, account_key=data['account_key'], domain_alt_names=data['domains'], contact_email=str(data['email']), LOG_LEVEL=log_level, ACME_AUTH_STATUS_WAIT_PERIOD=15, ACME_AUTH_STATUS_MAX_CHECKS=5, ACME_REQUEST_TIMEOUT=20, ACME_DIRECTORY_URL=self.let_url) self.write_log(public.getMsg("REGISTER_ACCOUNT")) client.acme_register() authorizations, finalize_url = client.apply_for_cert_issuance() responders = [] sucess_domains = [] self.write_log(public.getMsg("GET_VERIFICATION_INFO")) for url in authorizations: identifier_auth = self.get_identifier_authorization( client, url) authorization_url = identifier_auth["url"] http_name = identifier_auth["domain"] http_token = identifier_auth["http_token"] http_challenge_url = identifier_auth["http_challenge_url"] acme_keyauthorization, domain_http_value = client.get_keyauthorization( http_token) acme_dir = '%s/.well-known/acme-challenge' % (data['site_dir']) if not os.path.exists(acme_dir): os.makedirs(acme_dir) #写入token wellknown_path = acme_dir + '/' + http_token self.write_log( public.getMsg("CREATE_V_FILE", (wellknown_path, ))) public.writeFile(wellknown_path, acme_keyauthorization) wellknown_url = "http://{0}/.well-known/acme-challenge/{1}".format( http_name, http_token) result['clecks'].append({ 'wellknown_url': wellknown_url, 'http_token': http_token }) is_check = False n = 0 self.write_log( public.getMsg("CHECK_FILE_CONTENT", (wellknown_url))) while n < 5: print("wait_check_authorization_status") try: retkey = public.httpGet(wellknown_url, 20) if retkey == acme_keyauthorization: is_check = True self.write_log( public.getMsg("CHECK_FILE_CONTENT1", (retkey, ))) break except: pass n += 1 time.sleep(1) sucess_domains.append(http_name) responders.append({ "http_name": http_name, "authorization_url": authorization_url, "acme_keyauthorization": acme_keyauthorization, "http_challenge_url": http_challenge_url }) if len(sucess_domains) > 0: #验证 for i in responders: self.write_log( public.getMsg("CA_CHECK_RECORD", (i['http_name'], ))) auth_status_response = client.check_authorization_status( i["authorization_url"]) if auth_status_response.json()["status"] == "pending": client.respond_to_challenge( i["acme_keyauthorization"], i["http_challenge_url"]).json() for i in responders: self.write_log( public.getMsg("CHECK_CA_RES", (i['http_name'], ))) client.check_authorization_status(i["authorization_url"], ["valid", "invalid"]) self.write_log(public.getMsg("ALL_DOMAIN_V_PASS")) certificate_url = client.send_csr(finalize_url) self.write_log(public.getMsg("GET_CERT_CONTENT")) certificate = client.download_certificate(certificate_url) if certificate: certificate = self.split_ca_data(certificate) result['cert'] = certificate['cert'] result['ca_data'] = certificate['ca_data'] result['key'] = client.certificate_key result['account_key'] = client.account_key result['status'] = True else: result['msg'] = public.getMsg('CERT_APPLY_ERR') else: result['msg'] = public.getMsg("APPLY_SSL_ERROR_MSG") except Exception as e: self.write_log( public.getMsg("DNS_APPLY_ERR", (str(public.get_error_info()), ))) self.write_log("=" * 50) res = str(e).split('>>>>') err = False try: err = json.loads(res[1]) except: err = False result['msg'] = [self.get_error(res[0]), err] return result