예제 #1
0
 def register(self, new_reg=None):
     self._registered = True
     if new_reg is None:
         new_reg = messages.NewRegistration()
     self.regr = messages.RegistrationResource(body=messages.Registration(
         contact=new_reg.contact, agreement=new_reg.agreement))
     return succeed(self.regr)
예제 #2
0
파일: client_test.py 프로젝트: rwky/certbot
    def setUp(self):
        self.response = mock.MagicMock(
            ok=True, status_code=http_client.OK, headers={}, links={})
        self.net = mock.MagicMock()
        self.net.post.return_value = self.response
        self.net.get.return_value = self.response

        self.identifier = messages.Identifier(
            typ=messages.IDENTIFIER_FQDN, value='example.com')

        # Registration
        self.contact = ('mailto:[email protected]', 'tel:+12025551212')
        reg = messages.Registration(
            contact=self.contact, key=KEY.public_key())
        self.new_reg = messages.NewRegistration(**dict(reg))
        self.regr = messages.RegistrationResource(
            body=reg, uri='https://www.letsencrypt-demo.org/acme/reg/1')

        # Authorization
        authzr_uri = 'https://www.letsencrypt-demo.org/acme/authz/1'
        challb = messages.ChallengeBody(
            uri=(authzr_uri + '/1'), status=messages.STATUS_VALID,
            chall=challenges.DNS(token=jose.b64decode(
                'evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA')))
        self.challr = messages.ChallengeResource(
            body=challb, authzr_uri=authzr_uri)
        self.authz = messages.Authorization(
            identifier=messages.Identifier(
                typ=messages.IDENTIFIER_FQDN, value='example.com'),
            challenges=(challb,), combinations=None)
        self.authzr = messages.AuthorizationResource(
            body=self.authz, uri=authzr_uri)
예제 #3
0
    def setUp(self):
        from letsencrypt.account import Account

        logging.disable(logging.CRITICAL)

        self.accounts_dir = tempfile.mkdtemp("accounts")
        self.account_keys_dir = os.path.join(self.accounts_dir, "keys")
        os.makedirs(self.account_keys_dir, 0o700)

        self.config = mock.MagicMock(spec=configuration.NamespaceConfig,
                                     accounts_dir=self.accounts_dir,
                                     account_keys_dir=self.account_keys_dir,
                                     rsa_key_size=2048,
                                     server="letsencrypt-demo.org")

        key_file = pkg_resources.resource_filename(
            "acme.jose", os.path.join("testdata", "rsa512_key.pem"))
        key_pem = pkg_resources.resource_string(
            "acme.jose", os.path.join("testdata", "rsa512_key.pem"))

        self.key = le_util.Key(key_file, key_pem)
        self.email = "*****@*****.**"
        self.regr = messages.RegistrationResource(
            uri="uri",
            new_authzr_uri="new_authzr_uri",
            terms_of_service="terms_of_service",
            body=messages.Registration(recovery_token="recovery_token",
                                       agreement="agreement"))

        self.test_account = Account(self.config, self.key, self.email, None,
                                    self.regr)
예제 #4
0
    def setUp(self):
        self.response = mock.MagicMock(ok=True,
                                       status_code=http_client.OK,
                                       headers={},
                                       links={})
        self.net = mock.MagicMock()
        self.net.post.return_value = self.response
        self.net.get.return_value = self.response

        self.directory = messages.Directory({
            messages.NewRegistration:
            'https://www.letsencrypt-demo.org/acme/new-reg',
            messages.Revocation:
            'https://www.letsencrypt-demo.org/acme/revoke-cert',
        })

        from acme.client import Client
        self.client = Client(directory=self.directory,
                             key=KEY,
                             alg=jose.RS256,
                             net=self.net)

        self.identifier = messages.Identifier(typ=messages.IDENTIFIER_FQDN,
                                              value='example.com')

        # Registration
        self.contact = ('mailto:[email protected]', 'tel:+12025551212')
        reg = messages.Registration(contact=self.contact, key=KEY.public_key())
        self.new_reg = messages.NewRegistration(**dict(reg))
        self.regr = messages.RegistrationResource(
            body=reg,
            uri='https://www.letsencrypt-demo.org/acme/reg/1',
            new_authzr_uri='https://www.letsencrypt-demo.org/acme/new-reg',
            terms_of_service='https://www.letsencrypt-demo.org/tos')

        # Authorization
        authzr_uri = 'https://www.letsencrypt-demo.org/acme/authz/1'
        challb = messages.ChallengeBody(
            uri=(authzr_uri + '/1'),
            status=messages.STATUS_VALID,
            chall=challenges.DNS(token=jose.b64decode(
                'evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA')))
        self.challr = messages.ChallengeResource(body=challb,
                                                 authzr_uri=authzr_uri)
        self.authz = messages.Authorization(identifier=messages.Identifier(
            typ=messages.IDENTIFIER_FQDN, value='example.com'),
                                            challenges=(challb, ),
                                            combinations=None)
        self.authzr = messages.AuthorizationResource(
            body=self.authz,
            uri=authzr_uri,
            new_cert_uri='https://www.letsencrypt-demo.org/acme/new-cert')

        # Request issuance
        self.certr = messages.CertificateResource(
            body=messages_test.CERT,
            authzrs=(self.authzr, ),
            uri='https://www.letsencrypt-demo.org/acme/cert/1',
            cert_chain_uri='https://www.letsencrypt-demo.org/ca')
예제 #5
0
    def setUp(self):
        self.verify_ssl = mock.MagicMock()
        self.wrap_in_jws = mock.MagicMock(return_value=mock.sentinel.wrapped)

        from acme.client import Client
        self.net = Client(
            new_reg_uri='https://www.letsencrypt-demo.org/acme/new-reg',
            key=KEY,
            alg=jose.RS256,
            verify_ssl=self.verify_ssl)
        self.nonce = jose.b64encode('Nonce')
        self.net._nonces.add(self.nonce)  # pylint: disable=protected-access

        self.response = mock.MagicMock(ok=True, status_code=httplib.OK)
        self.response.headers = {}
        self.response.links = {}

        self.post = mock.MagicMock(return_value=self.response)
        self.get = mock.MagicMock(return_value=self.response)

        self.identifier = messages.Identifier(typ=messages.IDENTIFIER_FQDN,
                                              value='example.com')

        # Registration
        self.contact = ('mailto:[email protected]', 'tel:+12025551212')
        reg = messages.Registration(contact=self.contact,
                                    key=KEY.public(),
                                    recovery_token='t')
        self.regr = messages.RegistrationResource(
            body=reg,
            uri='https://www.letsencrypt-demo.org/acme/reg/1',
            new_authzr_uri='https://www.letsencrypt-demo.org/acme/new-reg',
            terms_of_service='https://www.letsencrypt-demo.org/tos')

        # Authorization
        authzr_uri = 'https://www.letsencrypt-demo.org/acme/authz/1'
        challb = messages.ChallengeBody(uri=(authzr_uri + '/1'),
                                        status=messages.STATUS_VALID,
                                        chall=challenges.DNS(token='foo'))
        self.challr = messages.ChallengeResource(body=challb,
                                                 authzr_uri=authzr_uri)
        self.authz = messages.Authorization(identifier=messages.Identifier(
            typ=messages.IDENTIFIER_FQDN, value='example.com'),
                                            challenges=(challb, ),
                                            combinations=None)
        self.authzr = messages.AuthorizationResource(
            body=self.authz,
            uri=authzr_uri,
            new_cert_uri='https://www.letsencrypt-demo.org/acme/new-cert')

        # Request issuance
        self.certr = messages.CertificateResource(
            body=messages_test.CERT,
            authzrs=(self.authzr, ),
            uri='https://www.letsencrypt-demo.org/acme/cert/1',
            cert_chain_uri='https://www.letsencrypt-demo.org/ca')
예제 #6
0
    def setUp(self):
        self.tmp = tempfile.mkdtemp()
        self.config = mock.MagicMock(
            accounts_dir=os.path.join(self.tmp, "accounts"))
        from certbot.account import AccountFileStorage
        self.storage = AccountFileStorage(self.config)

        from certbot.account import Account
        self.acc = Account(regr=messages.RegistrationResource(
            uri=None, body=messages.Registration()),
                           key=KEY)
예제 #7
0
 def setUp(self):
     super(SubscriptionTest, self).setUp()
     self.account = account.Account(
         regr=messages.RegistrationResource(
             uri=None, body=messages.Registration(),
             new_authzr_uri='hi'),
         key=_KEY,
         meta=account.Account.Meta(
             creation_host='test.certbot.org',
             creation_dt=datetime.datetime(
                 2015, 7, 4, 14, 4, 10, tzinfo=pytz.UTC)))
     self.config.email = '*****@*****.**'
     self.config.eff_email = None
예제 #8
0
def wildcard_revoke(cert_pem,account):

		#Check if registrar exists
		if account not in os.listdir(REG_DIRECTORY):
			print "This account does not exists, register it first with new_account.py"
			sys.exit(1)

		#Load files from disk
		with open(REG_DIRECTORY + "/" + account + "/private.key", "rb") as key_file:
			privkey = serialization.load_pem_private_key(
				key_file.read(),
				password=None,
				backend=default_backend()
			)
		with open(REG_DIRECTORY + "/" + account + "/reguri.txt", "r") as reguri_file:
			reg_uri = reguri_file.read()

		#Compose registration resource (regr)
		key = jose.JWKRSA(key=privkey)
		regr = messages.RegistrationResource(
			body=messages.Registration(
				key=key.public_key()),
			uri = reg_uri)

		#Init ACME
		net = ClientNetwork(key)
		directory = net.get(DIRECTORY_URL).json()

		acme = client.ClientV2(directory, net)


		#Check if registration is valid
		if acme.query_registration(regr).body.status == u'valid':
			print "Registration valid"
		else:
			print "Registration invalid"
			sys.exit(1)

		#Deserialize key from variable
		cert = jose.ComparableX509(OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert_pem))

		#Try to revoke cert, return false on error or revoked-already state
		try:
			revokation = acme.revoke(cert,1)
		except messages.Error,acme_exc:
			if str(acme_exc) == str("urn:ietf:params:acme:error:alreadyRevoked :: Certificate already revoked"):
				return ["Certificate already revoked",False]
			else:
				return [acme_exc, False]
예제 #9
0
    def setUp(self):
        super(AccountFileStorageTest, self).setUp()

        from certbot._internal.account import AccountFileStorage
        self.storage = AccountFileStorage(self.config)

        from certbot._internal.account import Account
        new_authzr_uri = "hi"
        self.acc = Account(regr=messages.RegistrationResource(
            uri=None,
            body=messages.Registration(),
            new_authzr_uri=new_authzr_uri),
                           key=KEY)
        self.mock_client = mock.MagicMock()
        self.mock_client.directory.new_authz = new_authzr_uri
예제 #10
0
def create_registration():
    global privkey, regr
    privkey = rsa.generate_private_key(public_exponent=65537,
                                       key_size=BITS,
                                       backend=default_backend())
    key = jose.JWKRSA(key=privkey)
    net = ClientNetwork(key)
    directory = net.get(DIRECTORY_URL).json()
    acme = client.ClientV2(directory, net)
    regbody = dict(
        messages.Registration(contact=('mailto:[email protected]', ),
                              terms_of_service_agreed=True,
                              key=key.public_key()))
    #NEED TO SAVE REGBODY VARIABLE TO FILE
    regr = acme.new_account(messages.NewRegistration(**regbody))
예제 #11
0
    def setUp(self):
        self.tmp = tempfile.mkdtemp()
        self.config = mock.MagicMock(
            accounts_dir=os.path.join(self.tmp, "accounts"))
        from certbot.account import AccountFileStorage
        self.storage = AccountFileStorage(self.config)

        from certbot.account import Account
        new_authzr_uri = "hi"
        self.acc = Account(
            regr=messages.RegistrationResource(
                uri=None, body=messages.Registration(),
                new_authzr_uri=new_authzr_uri),
            key=KEY)
        self.mock_client = mock.MagicMock()
        self.mock_client.directory.new_authz = new_authzr_uri
예제 #12
0
    def test_new_account_v2(self):
        directory = messages.Directory({
            "newAccount":
            'https://www.letsencrypt-demo.org/acme/new-account',
        })
        from acme.client import ClientV2
        client = ClientV2(directory, self.net)
        self.response.status_code = http_client.CREATED
        self.response.json.return_value = self.regr.body.to_json()
        self.response.headers['Location'] = self.regr.uri

        self.regr = messages.RegistrationResource(
            body=messages.Registration(contact=self.contact,
                                       key=KEY.public_key()),
            uri='https://www.letsencrypt-demo.org/acme/reg/1')

        self.assertEqual(self.regr, client.new_account(self.regr))
예제 #13
0
def get_acme_client(conf, domain_conf):
    """
    ACME Client
    """
    account_key = load_letsencrypt_account_key(conf,
                                               domain_conf['account_uri'])

    a_key = jose.JWKRSA(key=account_key)
    net = client.ClientNetwork(a_key)

    directory_acme = messages.Directory.from_json(
        net.get(domain_conf['directory']).json())
    client_acme = client.ClientV2(directory_acme, net)

    if not domain_conf['account_uri']:
        LOG.debug("Registering with ACME server with the new account key")
        new_reg = messages.NewRegistration.from_data(
            email=(', '.join(domain_conf['contact'])),
            terms_of_service_agreed=True)
        registration_resource = client_acme.new_account(new_reg)
        domain_conf['account_uri'] = registration_resource.uri

        LOG.debug("Write Account URI '%s' into Config file ",
                  domain_conf['account_uri'])
        new_domain_conf = yaml.dump(domain_conf, default_flow_style=False)
        save_to_s3(conf, conf['config_file'], new_domain_conf)
    else:
        registration = messages.Registration(key=a_key,
                                             contact=tuple(
                                                 domain_conf['contact']))
        registration_resource = messages.RegistrationResource(
            body=registration, uri=domain_conf['account_uri'])
        LOG.debug(
            "Update the regristration: {0}".format(registration_resource))

        registration_resource = client_acme.query_registration(
            registration_resource)

    net.account = registration_resource

    return client_acme
예제 #14
0
    def register(self,
                 contact=messages.Registration._fields['contact'].default):
        """Register.

        :param contact: Contact list, as accepted by `.Registration`
        :type contact: `tuple`

        :returns: Registration Resource.
        :rtype: `.RegistrationResource`

        :raises .UnexpectedUpdate:

        """
        new_reg = messages.Registration(contact=contact)

        response = self._post(self.new_reg_uri, new_reg)
        assert response.status_code == httplib.CREATED  # TODO: handle errors

        regr = self._regr_from_response(response)
        if regr.body.key != self.key.public() or regr.body.contact != contact:
            raise errors.UnexpectedUpdate(regr)

        return regr
예제 #15
0
    def setUp(self):
        super().setUp()

        from certbot._internal.account import AccountFileStorage
        self.storage = AccountFileStorage(self.config)

        from certbot._internal.account import Account
        new_authzr_uri = "hi"
        meta = Account.Meta(creation_host="test.example.org",
                            creation_dt=datetime.datetime(2021,
                                                          1,
                                                          5,
                                                          14,
                                                          4,
                                                          10,
                                                          tzinfo=pytz.UTC))
        self.acc = Account(regr=messages.RegistrationResource(
            uri=None,
            body=messages.Registration(),
            new_authzr_uri=new_authzr_uri),
                           key=KEY,
                           meta=meta)
        self.mock_client = mock.MagicMock()
        self.mock_client.directory.new_authz = new_authzr_uri
예제 #16
0
def wildcard_request(cn, account):
    def dns_check_ns1():
        recieved_data_dup = []
        recieved_data = []

        ns1_resolver = dns.resolver.Resolver()
        #ns1_resolver.nameservers = ['130.193.8.82','2a03:b780::1:1']
        ns1_resolver.nameservers = ['173.245.58.51']

        for data in validation_data:
            domainname = data[1]
            #challenge = data[0]
            answers = ns1_resolver.query(domainname, 'txt')
            for rdata in answers:
                recieved_data_dup.append(
                    [str(rdata).replace('"', ''), domainname])

        #Deduplication of ns records (in case of more cnames)
        for i in recieved_data_dup:
            if i not in recieved_data:
                recieved_data.append(i)

        # print sorted(recieved_data)
        # print sorted(validation_data)
        if sorted(validation_data) == sorted(recieved_data):
            return True
        else:
            return False

    #Check if CN is valid domain
    domain_regex = re.compile(
        "^([a-zA-Z0-9]([\-a-zA-Z0-9]{0,61}[a-zA-Z0-9])?\.)*([a-zA-Z0-9]([\-a-zA-Z0-9]{0,61}[a-zA-Z0-9])+\.)([a-zA-Z0-9]+([\-a-zA-Z0-9]{0,61}[a-zA-Z])+)$"
    )
    if not domain_regex.match(cn):
        print 'First argument is not valid CN'
        sys.exit(1)

    #Check if registrar exists
    if account not in os.listdir(REG_DIRECTORY):
        print "This account does not exists, register it first with new_account.py"
        sys.exit(1)

    #Load files from disk
    with open(REG_DIRECTORY + "/" + account + "/private.key",
              "rb") as key_file:
        privkey = serialization.load_pem_private_key(key_file.read(),
                                                     password=None,
                                                     backend=default_backend())
    with open(REG_DIRECTORY + "/" + account + "/reguri.txt",
              "r") as reguri_file:
        reg_uri = reguri_file.read()

    #Compose regr
    key = jose.JWKRSA(key=privkey)
    regr = messages.RegistrationResource(
        body=messages.Registration(key=key.public_key()), uri=reg_uri)

    #Init ACME
    net = ClientNetwork(key)
    directory = net.get(DIRECTORY_URL).json()

    acme = client.ClientV2(directory, net)

    #Check if registration is valid
    if acme.query_registration(regr).body.status == u'valid':
        print "Registration valid"
    else:
        print "Registration invalid"
        sys.exit(1)

    #Generate private key for certificate
    pkey = OpenSSL.crypto.PKey()
    pkey.generate_key(OpenSSL.crypto.TYPE_RSA, BITS)

    #Serialize key for output
    pkey_printable = OpenSSL.crypto.dump_privatekey(
        OpenSSL.crypto.FILETYPE_PEM, pkey, cipher=None, passphrase=None)

    #Compose request for acme
    req = crypto_util.make_csr(
        OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, pkey),
        [cn, '*.' + cn])

    #begin order
    orderr = acme.new_order(req)

    validation_data = []

    for authr in orderr.authorizations:
        for chalr in authr.body.challenges:
            if type(chalr.chall) == type(challenges.DNS01()):
                validation_data.append([
                    str(chalr.chall.validation(key)),
                    chalr.chall.validation_domain_name(cn)
                ])
    #print validation_data
    #Now, call DNS writing function to apply challenges
    dns_apply(cn, validation_data)

    #Check if DNS is valid on our server
    sys.stdin.readline()  #DEBUG: wait for manual DNS input
    limiter = 2
    while not dns_check_ns1():
        if limiter != 0:
            print "DNS records are not correct, trying again in few seconds"
            limiter = limiter - 1
            time.sleep(5)
        else:
            print "DNS are not correct even after several tries. Aborting"
            sys.exit(1)

    for authr in orderr.authorizations:
        for chalr in authr.body.challenges:
            if type(chalr.chall) == type(challenges.DNS01()):
                try:
                    acme.answer_challenge(chalr, challenges.DNS01Response())
                except:
                    print chalr.chall.encode(
                        'token'
                    ) + " already answered (challenge failed, you have to generate new one)"

    #After filling DNS and waiting for propagation, finalize order
    try:
        res = acme.poll_and_finalize(orderr)
    finally:
        dns_remove(cn)
    #logging.info(res)

    cert = x509.load_pem_x509_certificate(str(res.fullchain_pem),
                                          default_backend())

    output_data = {
        'wildcard': {
            'cn': cn,
            'private_key': str(pkey_printable),
            'certificate': str(res.fullchain_pem),
            'expiration': cert.not_valid_after.strftime(
                "%x %X"
            )  #Locale-specific time+date representation. Edit to your need
        }
    }

    print json.dumps(output_data)