Exemplo n.º 1
0
    def clean(self):
        """Let's veridfy the given passphrase"""

        cleaned_data = self.cleaned_data

        model = cleaned_data.get('_model')
        obj_id = cleaned_data.get('_id')
        pf_raw = cleaned_data.get('passphrase')

        if not pf_raw or pf_raw == '':
            pf_in = ''
        else:
            pf_in = md5_constructor(pf_raw).hexdigest()

        if model == "certificateauthority":
            obj = get_object_or_404(CertificateAuthority, pk=obj_id)

            if not pf_in or pf_in == "":
                self._errors["passphrase"] = ErrorList(
                    ['Passphrase is missing!'])
                return cleaned_data
        elif model == "certificate":
            obj = get_object_or_404(Certificate, pk=obj_id)

            if not obj.parent and not obj.passphrase:
                return cleaned_data
        else:
            raise Http404

        if obj.parent:
            pf_obj = obj.parent.passphrase
        else:
            pf_obj = obj.passphrase

        if pf_in != pf_obj:
            self._errors["passphrase"] = ErrorList(['Passphrase is wrong!'])

        return cleaned_data
Exemplo n.º 2
0
 def clean(self):
     """Let's veridfy the given passphrase"""
     
     cleaned_data = self.cleaned_data
     
     model = cleaned_data.get('_model')
     obj_id = cleaned_data.get('_id')
     pf_raw = cleaned_data.get('passphrase')
     
     if not pf_raw or pf_raw == '':
         pf_in = ''
     else:
         pf_in = md5_constructor(pf_raw).hexdigest()
     
     if model == "certificateauthority":
         obj = get_object_or_404(CertificateAuthority, pk=obj_id)
         
         if not pf_in or pf_in == "":
             self._errors["passphrase"] = ErrorList(
                 ['Passphrase is missing!'])
             return cleaned_data
     elif model == "certificate":
         obj = get_object_or_404(Certificate, pk=obj_id)
         
         if not obj.parent and not obj.passphrase:
             return cleaned_data
     else:
         raise Http404
         
     if obj.parent:
         pf_obj = obj.parent.passphrase
     else:
         pf_obj = obj.passphrase
     
     if pf_in != pf_obj:
         self._errors["passphrase"] = ErrorList(['Passphrase is wrong!'])
     
     return cleaned_data
Exemplo n.º 3
0
 def save(self):
     """Save the Certificate object"""
     
     if self.pk:
         if self.action in ('update', 'revoke', 'renew'):
             
             action = OpensslActions(self)
             prev   = Certificate.objects.get(pk=self.pk)
             
             if self.action == 'update':
                 
                 ## Create or remove DER certificate
                 if self.der_encoded:
                     action.generate_der_encoded()
                 else:
                     action.remove_der_encoded()
                 
                 ## Create or remove PKCS12 certificate
                 if self.pkcs12_encoded:
                     if prev.pkcs12_encoded and prev.pkcs12_passphrase == self.pkcs12_passphrase:
                         logger.debug( 'PKCS12 passphrase is unchanged. Nothing to do' )
                     else:
                         action.generate_pkcs12_encoded()
                 else:
                     action.remove_pkcs12_encoded()
                     self.pkcs12_passphrase = None
                     prev.pkcs12_passphrase = None
                 
                 if self.pkcs12_passphrase:
                     prev.pkcs12_passphrase = md5_constructor(self.pkcs12_passphrase).hexdigest()
                 else:
                     prev.pkcs12_passphrase = None
                 
                 prev.description    = self.description
                 prev.der_encoded    = self.der_encoded
                 prev.pkcs12_encoded = self.pkcs12_encoded
                 prev.pem_encoded    = True
                 
             elif self.action == 'revoke':
                 
                 ## Revoke and generate CRL
                 action.revoke_certificate(self.parent_passphrase)
                 action.generate_crl(self.parent.name, self.parent_passphrase)
                 
                 ## Modify fields
                 prev.parent_passphrase = None
                 prev.active            = False
                 prev.der_encoded       = False
                 prev.pem_encoded       = False
                 prev.pkcs12_encoded    = False
                 prev.revoked = datetime.datetime.now()
                 
             elif self.action == 'renew':
                 
                 ## Revoke if certificate is active
                 if not action.get_revoke_status_from_cert():
                     action.revoke_certificate(self.parent_passphrase)
                 
                 ## Renew and update CRL
                 action.renew_certificate()
                 action.generate_crl(self.parent.name, self.parent_passphrase)
                 
                 ## Modify fields
                 prev.created = datetime.datetime.now()
                 delta = datetime.timedelta(self.valid_days)
                 prev.expiry_date = datetime.datetime.now() + delta
                 
                 prev.parent_passphrase = None
                 prev.active            = True
                 prev.pem_encoded       = True
                 prev.der_encoded       = self.der_encoded
                 prev.pkcs12_encoded    = self.pkcs12_encoded
                 prev.revoked           = None
                 prev.valid_days = self.valid_days
                 
                 ## Get the new serial
                 prev.serial     = action.get_serial_from_cert()
                 #prev.passphrase = md5_constructor(self.passphrase).hexdigest()
             
             ## Save the data
             self = prev
             self.action = 'update'
             
             super(Certificate, self).save()
     else:
         ## Set creation data
         self.created = datetime.datetime.now()
         delta = datetime.timedelta(self.valid_days)
         self.expiry_date = datetime.datetime.now() + delta
         
         ## Force instance to be active
         self.active = True
         
         logger.info( "***** { New certificate generation: %s } *****" % self.name )
         
         ## Generate key and certificate
         action = OpensslActions(self)
         
         action.generate_key()
         action.generate_csr()
         action.sign_csr()
         
         ## Get the serial from certificate
         self.serial = action.get_serial_from_cert()
         
         self.ca_chain = self.parent.ca_chain
         if self.ca_chain == 'self-signed':
             self.ca_chain = self.parent.name
         
         self.pem_encoded = True
         
         ## Create or remove DER certificate
         if self.der_encoded:
             action.generate_der_encoded()
         else:
             action.remove_der_encoded()
         
         ## Create or remove PKCS12 certificate
         if self.pkcs12_encoded:
             action.generate_pkcs12_encoded()
         else:
             action.remove_pkcs12_encoded()
         
         if self.pkcs12_passphrase:
             self.pkcs12_passphrase = md5_constructor(self.pkcs12_passphrase).hexdigest()
         
         ## Encrypt passphrase and blank parent's passphrase
         if self.passphrase:
             self.passphrase = md5_constructor(self.passphrase).hexdigest()
         
         self.parent_passphrase = None
         
         ## Save the data
         super(Certificate, self).save()
Exemplo n.º 4
0
 def save(self, force_insert=False, force_update=False):
     """Save the CertificateAuthority object"""
     
     if self.pk:
         ### existing CA
         if self.action in ('update', 'revoke', 'renew'):
             
             action = OpensslActions(self)
             prev   = CertificateAuthority.objects.get(pk=self.pk)
             
             if self.action == 'update':
                 
                 ## Create or remove DER certificate
                 if self.der_encoded:
                     action.generate_der_encoded()
                 else:
                     action.remove_der_encoded()
                 
                 prev.description = self.description
                 prev.der_encoded = self.der_encoded
                 
             elif self.action == 'revoke':
                 
                 ## DB-revoke all related certs
                 garbage = []
                 id_dict = { 'cert': [], 'ca': [], }
                 
                 from pki.views import chain_recursion as r_chain_recursion
                 r_chain_recursion(self.id, garbage, id_dict)
                 
                 for i in id_dict['cert']:
                     x = Certificate.objects.get(pk=i)
                     x.active         = False
                     x.der_encoded    = False
                     x.pem_encoded    = False
                     x.pkcs12_encoded = False
                     x.revoked        = datetime.datetime.now()
                     
                     super(Certificate, x).save()
                 
                 for i in id_dict['ca']:
                     x = CertificateAuthority.objects.get(pk=i)
                     x.active       = False
                     x.der_encoded  = False
                     x.pem_encoded  = False
                     x.revoked      = datetime.datetime.now()
                     
                     super(CertificateAuthority, x).save()
                 
                 ## Revoke and generate CRL
                 action.revoke_certificate(self.parent_passphrase)
                 action.generate_crl(self.parent.name, self.parent_passphrase)
                 
                 ## Modify fields
                 prev.parent_passphrase = None
                 prev.active            = False
                 prev.der_encoded       = False
                 prev.pem_encoded       = False
                 prev.revoked = datetime.datetime.now()
                 
             elif self.action == 'renew':
                 
                 ## Revoke if certificate is active
                 if self.parent and not action.get_revoke_status_from_cert():
                     action.revoke_certificate(self.parent_passphrase)
                     action.generate_crl(self.parent.name, self.parent_passphrase)
                 
                 ## Rebuild the ca metadata
                 self.rebuild_ca_metadata(modify=True, task='replace')
                 
                 ## Renew certificate and update CRL
                 if self.parent == None:
                     action.generate_self_signed_cert()
                     action.generate_crl(self.name, self.passphrase)
                 else:
                     action.renew_certificate()
                     action.generate_crl(self.parent.name, self.parent_passphrase)
                 
                 action.update_ca_chain_file()
                 
                 ## Modify fields
                 prev.created = datetime.datetime.now()
                 delta = datetime.timedelta(self.valid_days)
                 prev.expiry_date = datetime.datetime.now() + delta
                 prev.valid_days = self.valid_days
                 
                 prev.parent_passphrase = None
                 prev.active            = True
                 prev.pem_encoded       = True
                 prev.der_encoded       = self.der_encoded
                 prev.revoked           = None
                 
                 ## Get the new serial
                 prev.serial     = action.get_serial_from_cert()
                 #prev.passphrase = md5_constructor(self.passphrase).hexdigest()
             
             ## Save the data
             self = prev
             self.action = 'update'
             
             super(CertificateAuthority, self).save()
         else:
             
             raise Exception( 'Invalid action %s supplied' % self.action )
     else:
         ## Set creation data
         self.created = datetime.datetime.now()
         delta = datetime.timedelta(self.valid_days)
         self.expiry_date = datetime.datetime.now() + delta
         
         ## Force instance to be active
         self.active = True
         
         ## Reset the action
         self.action = 'update'
         
         ## Rebuild the ca metadata
         self.rebuild_ca_metadata(modify=True, task='append')
         
         ## Generate keys and certificates
         action = OpensslActions(self)
         action.generate_key()
         
         if not self.parent:
             action.generate_self_signed_cert()
         else:
             action.generate_csr()
             action.sign_csr()
         
         if self.der_encoded:
             action.generate_der_encoded()
         
         ## Generate CRL
         action.generate_crl(self.name, self.passphrase)
         
         ## Always enable pem encoded flag
         self.pem_encoded = True
         
         ## Get the serial from certificate
         self.serial = action.get_serial_from_cert()
         
         ## Generate ca chain (db field and chain file)
         chain = []
         chain_str = ''
         
         p = self.parent
         
         if self.parent == None:
             chain.append('self-signed')
         else:
             chain.append( self.common_name )
             while p != None:
                 chain.append(p.common_name)
                 p = p.parent
         
         chain.reverse()
         
         ## Build chain string and file
         for i in chain:
             if chain_str == '':
                 chain_str += '%s' % i
             else:
                 chain_str += ' → %s' % i
         
         self.ca_chain = chain_str
         
         action.update_ca_chain_file()
         
         ## Encrypt passphrase and blank parent's passphrase
         self.passphrase = md5_constructor(self.passphrase).hexdigest()
         self.parent_passphrase = None
         
     ## Save the data
     super(CertificateAuthority, self).save()
Exemplo n.º 5
0
 def clean(self):
     """Verify fields"""
     
     cleaned_data = self.cleaned_data
     
     name = cleaned_data.get('name')
     action = cleaned_data.get('action')
     parent = cleaned_data.get('parent')
     pf = cleaned_data.get('passphrase')
     pf_v = cleaned_data.get('passphrase_verify')
     p_pf = cleaned_data.get('parent_passphrase')
     extension = cleaned_data.get('extension')
     crl_dpoints = cleaned_data.get('crl_dpoints')
     
     enc_p_pf = None
     
     if name in PKI_CA_NAME_BLACKLIST:
         self._errors['name'] = ErrorList(['Name "%s" is blacklisted!' %
                                           name])
         return cleaned_data
     
     if action in ('create', 'renew'):
         if action == 'create':
             if not pf_v or pf != pf_v:
                 self.errors['passphrase_verify'] = ErrorList(
                     ['Passphrase mismtach!'])
             
             ## Verify that we're not creating a certificate
             # that already exists
             if name and os.path.isdir(os.path.join(PKI_DIR, name)):
                 self._errors['name'] = ErrorList(
                     ['Name "%s" is already in use!' % name])
         
         ## Take care that parent is active when action is revoke
         if action == 'renew':
             ca = CertificateAuthority.objects.get(name='%s' % name)
             
             ## Prevent renewal when parent is disabled
             if ca.parent is not None and ca.parent.active is not True:
                 self._errors['action'] = ErrorList(
                     ['Cannot renew CA certificate when parent "%s" isn\'t \
                      active!' % ca.parent.name])
                 return cleaned_data
             
             ## Compare passphrase
             if not pf or (ca.passphrase !=
                           md5_constructor(pf).hexdigest()):
                 self._errors['passphrase'] = ErrorList(
                     ['Passphrase is wrong. Enter correct passphrase for \
                      CA "%s"' % cleaned_data.get('common_name')])
         
         if parent:
             ca = CertificateAuthority.objects.get(name='%s' % parent.name)
             if p_pf:
                 enc_p_pf = md5_constructor(p_pf).hexdigest()
             
             ## Check if parent allows sub CA
             if ca.is_edge_ca():
                 self._errors['parent'] = ErrorList(
                     ['Parent\'s x509 extension doesn\'t allow a sub CA. \
                      Only non CA certificates can be created'])
                 
             ## Check parent passphrase if not RootCA
             if ca.passphrase != enc_p_pf:
                 self._errors['parent_passphrase'] = ErrorList(
                     ['Passphrase is wrong. Enter correct passphrase for \
                      CA "%s"' % parent])
         
         ## Verify CRL distribution settings
         x509 = get_object_or_404(x509Extension, name=extension)
         if x509.crl_distribution_point and not crl_dpoints:
             self._errors['crl_dpoints'] = ErrorList(
                 ['CRL Distribution Points are required by x509 extension \
                  "%s"' % extension])
     elif action == 'revoke':
         if parent:
             ca = CertificateAuthority.objects.get(name='%s' % parent.name)
             enc_p_pf = md5_constructor(cleaned_data.get(
                 'parent_passphrase')).hexdigest()
             
             ## Check parent passphrase
             if ca.passphrase != enc_p_pf:
                 self._errors['parent_passphrase'] = ErrorList(
                     ['Passphrase is wrong. Enter correct passphrase for \
                      CA "%s"' % parent])
         else:
             self._errors['action'] = ErrorList(
                 ['You cannot revoke a self-signed root certificate as \
                  there\'s no CA to revoke against. Delete it instead!'])
     
     return cleaned_data
Exemplo n.º 6
0
 def clean(self):
     """Verify crucial fields"""
     
     cleaned_data = self.cleaned_data
     
     name = cleaned_data.get('name')
     action = cleaned_data.get('action')
     parent = cleaned_data.get('parent')
     pf = cleaned_data.get('passphrase')
     pf_v = cleaned_data.get('passphrase_verify')
     p_pf = cleaned_data.get('parent_passphrase')
     extension = cleaned_data.get('extension')
     crl_dpoints = cleaned_data.get('crl_dpoints')
     
     enc_p_pf = None
     
     if action in ('create', 'renew'):
         if action == 'create':
             if (pf and not pf_v) or pf != pf_v:
                 self.errors['passphrase_verify'] = ErrorList(
                     ['Passphrase mismtach detected'])
             
             ## Verify that we're not creating a certificate
             ## that already exists
             if parent:
                 if os.path.exists(os.path.join(PKI_DIR,
                                                parent.name, 'certs',
                                                '%s.key.pem' % name)):
                     self._errors['name'] = ErrorList(
                         ['Name "%s" is already in use!' % name])
             else:
                 if os.path.exists(os.path.join(PKI_DIR,
                                                '_SELF_SIGNED_CERTIFICATES',
                                                'certs', '%s.key.pem' %
                                                name)):
                     self._errors['name'] = ErrorList(
                         ['Name "%s" is already in use!' % name])
         
         ## Take care that parent is active when action is revoke
         if action == 'renew':
             cert = Certificate.objects.get(name='%s' % name)
             
             if cert.parent is not None and cert.parent.active is not True:
                 self._errors['action'] = ErrorList(
                     ['Cannot renew certificate when parent CA "%s" isn\'t \
                      active!' % cert.parent])
                 return cleaned_data
         
         if parent:
             ca = CertificateAuthority.objects.get(name='%s' % parent.name)
             if p_pf:
                 enc_p_pf = md5_constructor(p_pf).hexdigest()
             
             ## Check parent passphrase
             if ca.passphrase != enc_p_pf:
                 self._errors['parent_passphrase'] = ErrorList(
                     ['Passphrase is wrong. Enter correct passphrase for \
                      CA "%s"' % parent])
         
         ## Verify CRL distribution settings
         x509 = get_object_or_404(x509Extension, name=extension)
         if x509.crl_distribution_point and not crl_dpoints:
             self._errors['crl_dpoints'] = ErrorList(
                 ['CRL Distribution Points are required by x509 extension \
                  "%s"' % extension])
     elif action == 'revoke':
         if parent:
             ca = CertificateAuthority.objects.get(name='%s' % parent.name)
             if p_pf:
                 enc_p_pf = md5_constructor(p_pf).hexdigest()
             
             ## Check parent passphrase
             if ca.passphrase != enc_p_pf:
                 self._errors['parent_passphrase'] = ErrorList(
                     ['Passphrase is wrong. Enter correct passphrase for CA\
                      "%s"' % parent])
         else:
             self._errors['action'] = ErrorList(
                 ['You cannot revoke a self-signed certificate as there\'s \
                  no CA to revoke against. Delete it instead!'])
     
     return cleaned_data
Exemplo n.º 7
0
    def clean(self):
        """Verify fields"""

        cleaned_data = self.cleaned_data

        name = cleaned_data.get('name')
        action = cleaned_data.get('action')
        parent = cleaned_data.get('parent')
        pf = cleaned_data.get('passphrase')
        pf_v = cleaned_data.get('passphrase_verify')
        p_pf = cleaned_data.get('parent_passphrase')
        extension = cleaned_data.get('extension')
        crl_dpoints = cleaned_data.get('crl_dpoints')

        enc_p_pf = None

        if name in PKI_CA_NAME_BLACKLIST:
            self._errors['name'] = ErrorList(
                ['Name "%s" is blacklisted!' % name])
            return cleaned_data

        if action in ('create', 'renew'):
            if action == 'create':
                if not pf_v or pf != pf_v:
                    self.errors['passphrase_verify'] = ErrorList(
                        ['Passphrase mismtach!'])

                ## Verify that we're not creating a certificate that already exists
                if name and os.path.isdir(os.path.join(PKI_DIR, name)):
                    self._errors['name'] = ErrorList(
                        ['Name "%s" is already in use!' % name])

            ## Take care that parent is active when action is revoke
            if action == 'renew':
                ca = CertificateAuthority.objects.get(name='%s' % name)

                ## Prevent renewal when parent is disabled
                if ca.parent is not None and ca.parent.active is not True:
                    self._errors['action'] = ErrorList([
                        'Cannot renew CA certificate when parent "%s" isn\'t active!'
                        % ca.parent.name
                    ])
                    return cleaned_data

                ## Compare passphrase
                if not pf or (ca.passphrase !=
                              md5_constructor(pf).hexdigest()):
                    self._errors['passphrase'] = ErrorList([
                        'Passphrase is wrong. Enter correct passphrase for CA "%s"'
                        % cleaned_data.get('common_name')
                    ])

            if parent:
                ca = CertificateAuthority.objects.get(name='%s' % parent.name)
                if p_pf:
                    enc_p_pf = md5_constructor(p_pf).hexdigest()

                ## Check if parent allows sub CA
                if ca.is_edge_ca():
                    self._errors['parent'] = ErrorList([
                        'Parent\'s x509 extension doesn\'t allow a sub CA. Only non CA certificates can be created'
                    ])

                ## Check parent passphrase if not RootCA
                if ca.passphrase != enc_p_pf:
                    self._errors['parent_passphrase'] = ErrorList([
                        'Passphrase is wrong. Enter correct passphrase for CA "%s"'
                        % parent
                    ])

            ## Verify CRL distribution settings
            x509 = get_object_or_404(x509Extension, name=extension)
            if x509.crl_distribution_point and not crl_dpoints:
                self._errors['crl_dpoints'] = ErrorList([
                    'CRL Distribution Points are required by x509 extension "%s"'
                    % extension
                ])
        elif action == 'revoke':
            if parent:
                ca = CertificateAuthority.objects.get(name='%s' % parent.name)
                enc_p_pf = md5_constructor(
                    cleaned_data.get('parent_passphrase')).hexdigest()

                ## Check parent passphrase
                if ca.passphrase != enc_p_pf:
                    self._errors['parent_passphrase'] = ErrorList([
                        'Passphrase is wrong. Enter correct passphrase for CA "%s"'
                        % parent
                    ])
            else:
                self._errors['action'] = ErrorList([
                    'You cannot revoke a self-signed root certificate as there\'s no CA to revoke against. Delete it instead!'
                ])

        return cleaned_data
Exemplo n.º 8
0
    def clean(self):
        """Verify crucial fields"""

        cleaned_data = self.cleaned_data

        name = cleaned_data.get('name')
        action = cleaned_data.get('action')
        parent = cleaned_data.get('parent')
        pf = cleaned_data.get('passphrase')
        pf_v = cleaned_data.get('passphrase_verify')
        p_pf = cleaned_data.get('parent_passphrase')
        extension = cleaned_data.get('extension')
        crl_dpoints = cleaned_data.get('crl_dpoints')

        enc_p_pf = None

        if action in ('create', 'renew'):
            if action == 'create':
                if (pf and not pf_v) or pf != pf_v:
                    self.errors['passphrase_verify'] = ErrorList(
                        ['Passphrase mismtach detected'])

                ## Verify that we're not creating a certificate that already exists
                if parent:
                    if os.path.exists(
                            os.path.join(PKI_DIR, parent.name, 'certs',
                                         '%s.key.pem' % name)):
                        self._errors['name'] = ErrorList(
                            ['Name "%s" is already in use!' % name])
                else:
                    if os.path.exists(
                            os.path.join(PKI_DIR, '_SELF_SIGNED_CERTIFICATES',
                                         'certs', '%s.key.pem' % name)):
                        self._errors['name'] = ErrorList(
                            ['Name "%s" is already in use!' % name])

            ## Take care that parent is active when action is revoke
            if action == 'renew':
                cert = Certificate.objects.get(name='%s' % name)

                if cert.parent is not None and cert.parent.active is not True:
                    self._errors['action'] = ErrorList([
                        'Cannot renew certificate when parent CA "%s" isn\'t active!'
                        % cert.parent
                    ])
                    return cleaned_data

            if parent:
                ca = CertificateAuthority.objects.get(name='%s' % parent.name)
                if p_pf: enc_p_pf = md5_constructor(p_pf).hexdigest()

                ## Check parent passphrase
                if ca.passphrase != enc_p_pf:
                    self._errors['parent_passphrase'] = ErrorList([
                        'Passphrase is wrong. Enter correct passphrase for CA "%s"'
                        % parent
                    ])

            ## Verify CRL distribution settings
            x509 = get_object_or_404(x509Extension, name=extension)
            if x509.crl_distribution_point and not crl_dpoints:
                self._errors['crl_dpoints'] = ErrorList([
                    'CRL Distribution Points are required by x509 extension "%s"'
                    % extension
                ])
        elif action == 'revoke':
            if parent:
                ca = CertificateAuthority.objects.get(name='%s' % parent.name)
                if p_pf: enc_p_pf = md5_constructor(p_pf).hexdigest()

                ## Check parent passphrase
                if ca.passphrase != enc_p_pf:
                    self._errors['parent_passphrase'] = ErrorList([
                        'Passphrase is wrong. Enter correct passphrase for CA "%s"'
                        % parent
                    ])
            else:
                self._errors['action'] = ErrorList([
                    'You cannot revoke a self-signed certificate as there\'s no CA to revoke against. Delete it instead!'
                ])

        return cleaned_data
Exemplo n.º 9
0
 def save(self, *args, **kwargs):
     """Save the Certificate object"""
     
     ## Set user to None if it's missing
     c_user = getattr(self, 'user', None)
     
     ## Variables to track changes
     c_action = self.action
     c_list   = []
     
     if self.pk:
         if self.action in ('update', 'revoke', 'renew'):
             action = Openssl(self)
             prev   = Certificate.objects.get(pk=self.pk)
             
             if self.action == 'revoke':
                 if not self.parent:
                     raise Exception( "You cannot revoke a self-signed certificate! No parent => No revoke" )
                 
                 ## Revoke and generate CRL
                 action.revoke_certificate(self.parent_passphrase)
                 action.generate_crl(self.parent.name, self.parent_passphrase)
                 
                 ## Modify fields
                 prev.active            = False
                 prev.der_encoded       = False
                 prev.pkcs12_encoded    = False
                 prev.revoked           = datetime.datetime.now()
                 c_list.append('Revoked certificate "%s"' % self.common_name)
             elif self.action == 'renew':
                 c_list.append('Renewed certificate "%s"' % self.common_name)
                 
                 ## Revoke if certificate is active
                 if self.parent and not action.get_revoke_status_from_cert():
                     action.revoke_certificate(self.parent_passphrase)
                     action.generate_crl(self.parent.name, self.parent_passphrase)
                 
                 ## Renew certificate and update CRL
                 if self.parent == None:
                     action.generate_self_signed_cert()
                 else:
                     action.generate_csr()
                     action.sign_csr()
                     action.generate_crl(self.parent.name, self.parent_passphrase)
                 
                 ## Modify fields
                 prev.created     = datetime.datetime.now()
                 delta            = datetime.timedelta(self.valid_days)
                 prev.expiry_date = datetime.datetime.now() + delta
                 
                 if prev.valid_days != self.valid_days:
                     c_list.append("Changed valid days to %d" % (prev.valid_days, self.valid_days))
                 
                 prev.valid_days  = self.valid_days
                 prev.active      = True
                 prev.revoked     = None
                 
                 ## Make sure possibly updated fields are saved to DB
                 if prev.country != self.country: c_list.append('Updated country to "%s"' % self.country)
                 if prev.locality != self.locality: c_list.append('Updated locality to "%s"' % self.locality)
                 if prev.organization != self.organization: c_list.append('Updated organization to "%s"' % self.organization)
                 if prev.email != self.email: c_list.append('Updated email to "%s"' % self.email)
                 if prev.OU != self.OU: c_list.append('Updated OU to "%s"' % self.OU)
                 
                 prev.country      = self.country
                 prev.locality     = self.locality
                 prev.organization = self.organization
                 prev.email        = self.email
                 prev.OU           = self.OU
                 
                 ## Get the new serial
                 prev.serial = action.get_serial_from_cert()
                 c_list.append("Serial number changed to %s" % prev.serial)
             
             if self.action != 'revoke':
                 if prev.pkcs12_encoded != self.pkcs12_encoded:
                     c_list.append("PKCS12 encoding set to %s" % self.der_encoded)
                 
                 if self.pkcs12_encoded:
                     if prev.pkcs12_encoded and prev.pkcs12_passphrase == self.pkcs12_passphrase:
                         logger.debug( 'PKCS12 passphrase is unchanged. Nothing to do' )
                     else:
                         action.generate_pkcs12_encoded()
                 else:
                     action.remove_pkcs12_encoded()
                     self.pkcs12_passphrase = prev.pkcs12_passphrase = None
                 
                 if self.pkcs12_passphrase:
                     prev.pkcs12_passphrase = md5_constructor(self.pkcs12_passphrase).hexdigest()
                 else:
                     prev.pkcs12_passphrase = None
                 
                 if prev.der_encoded is not self.der_encoded:
                     c_list.append("DER encoding set to %s" % self.der_encoded)
                 
                 if self.der_encoded:
                     action.generate_der_encoded()
                 else:
                     action.remove_der_encoded()
                 
             ## Update description. This is always allowed
             if prev.description != self.description:
                 c_list.append('Updated description to "%s"' % self.description)
                 prev.description = self.description
             
             ## Save the data
             self = prev
             self.action = 'update'
         else:
             raise Exception( 'Invalid action %s supplied' % self.action )
     else:
         ## Set creation data
         self.created = datetime.datetime.now()
         delta = datetime.timedelta(self.valid_days)
         self.expiry_date = datetime.datetime.now() + delta
         
         ## Force instance to be active
         self.active = True
         
         logger.info( "***** { New certificate generation: %s } *****" % self.name )
         
         ## Generate key and certificate
         action = Openssl(self)
         action.generate_key()
         
         if self.parent:
             action.generate_csr()
             action.sign_csr()
             self.ca_chain = self.parent.ca_chain
             if self.ca_chain == 'self-signed':
                 self.ca_chain = self.parent.name
         else:
             action.generate_self_signed_cert()
             self.ca_chain = "self-signed"
         
         ## Get the serial from certificate
         self.serial = action.get_serial_from_cert()
         
         ## Encoding
         if self.der_encoded:
             action.generate_der_encoded()
         
         if self.pkcs12_encoded:
             action.generate_pkcs12_encoded()
         
         ## Encrypt passphrase and blank parent's passphrase
         if self.passphrase:
             self.passphrase = md5_constructor(self.passphrase).hexdigest()
         
         ## Set change text to fixed value
         c_list.append('Created certificate "%s"' % action.subj)
     
     ## Blank parent passphrase
     self.parent_passphrase = None
     
     ## Save the data
     super(Certificate, self).save(*args, **kwargs)
     
     ## Update changelog
     self.Update_Changelog(obj=self, user=c_user, action=c_action, changes=c_list)
Exemplo n.º 10
0
 def save(self, *args, **kwargs):
     """Save the CertificateAuthority object"""
     
     ## Set user to None if it's missing
     c_user = getattr(self, 'user', None)
     
     ## Variables to track changes
     c_action = self.action
     c_list   = []
     
     if self.pk:
         if self.action in ('update', 'revoke', 'renew'):
             action = Openssl(self)
             prev   = CertificateAuthority.objects.get(pk=self.pk)
             
             if self.action in ('revoke', 'renew'):
                 if self.action == 'revoke':
                     if not self.parent:
                         raise Exception( "You cannot revoke a self-signed certificate! No parent => No revoke" )
                     
                     ## Revoke and generate CRL
                     action.revoke_certificate(self.parent_passphrase)
                     action.generate_crl(self.parent.name, self.parent_passphrase)
                     
                     ## Modify fields
                     prev.active            = False
                     prev.der_encoded       = False
                     prev.revoked           = datetime.datetime.now()
                     
                     c_list.append('Revoked certificate "%s"' % self.common_name)
                 elif self.action == 'renew':
                     c_list.append('Renewed certificate "%s"' % self.common_name)
                     
                     ## Revoke if certificate is active
                     if self.parent and not action.get_revoke_status_from_cert():
                         action.revoke_certificate(self.parent_passphrase)
                         action.generate_crl(self.parent.name, self.parent_passphrase)
                     
                     ## Rebuild the ca metadata
                     self.rebuild_ca_metadata(modify=True, task='replace')
                     
                     ## Renew certificate and update CRL
                     if self.parent == None:
                         action.generate_self_signed_cert()
                         action.generate_crl(self.name, self.passphrase)
                     else:
                         action.generate_csr()
                         action.sign_csr()
                         action.generate_crl(self.parent.name, self.parent_passphrase)
                     
                     action.update_ca_chain_file()
                     
                     ## Modify fields
                     prev.created = datetime.datetime.now()
                     delta = datetime.timedelta(self.valid_days)
                     prev.expiry_date = datetime.datetime.now() + delta
                     
                     if prev.valid_days != self.valid_days:
                         c_list.append("Changed valid days to %d" % (prev.valid_days, self.valid_days))
                     
                     prev.valid_days  = self.valid_days
                     prev.active      = True
                     prev.revoked     = None
                     
                     ## Make sure possibly updated fields are saved to DB
                     if prev.country != self.country: c_list.append('Updated country to "%s"' % self.country)
                     if prev.locality != self.locality: c_list.append('Updated locality to "%s"' % self.locality)
                     if prev.organization != self.organization: c_list.append('Updated organization to "%s"' % self.organization)
                     if prev.email != self.email: c_list.append('Updated email to "%s"' % self.email)
                     if prev.OU != self.OU: c_list.append('Updated OU to "%s"' % self.OU)
                     
                     prev.country      = self.country
                     prev.locality     = self.locality
                     prev.organization = self.organization
                     prev.email        = self.email
                     prev.OU           = self.OU
                     
                     ## Get the new serial
                     prev.serial = action.get_serial_from_cert()
                     c_list.append("Serial number changed to %s" % prev.serial)
                     
                 ## DB-revoke all related certs
                 garbage = []
                 id_dict = { 'cert': [], 'ca': [], }
                 
                 from pki.views import chain_recursion as r_chain_recursion
                 r_chain_recursion(self.id, garbage, id_dict)
                 
                 for i in id_dict['cert']:
                     x = Certificate.objects.get(pk=i)
                     x.active         = False
                     x.der_encoded    = False
                     x.pkcs12_encoded = False
                     x.revoked        = datetime.datetime.now()
                     
                     super(Certificate, x).save(*args, **kwargs)
                     self.Update_Changelog(obj=x, user=c_user, action='broken', changes=(['Broken by %s of CA "%s"' % (c_action, self.common_name),]))
                 
                 for i in id_dict['ca']:
                     x = CertificateAuthority.objects.get(pk=i)
                     x.active      = False
                     x.der_encoded = False
                     x.revoked     = datetime.datetime.now()
                     
                     super(CertificateAuthority, x).save(*args, **kwargs)
                     if x.pk != self.pk:
                         self.Update_Changelog(obj=x, user=c_user, action='broken', changes=(['Broken by %s of CA "%s"' % (c_action, self.common_name),]))
             
             ## Update description. This is always allowed
             if prev.description != self.description:
                 c_list.append('Updated description to "%s"' % self.description)
                 prev.description = self.description
             
             if prev.der_encoded is not self.der_encoded:
                 c_list.append("DER encoding set to %s" % self.der_encoded)
             
             if self.der_encoded and self.action != "revoke":
                 action.generate_der_encoded()
             else:
                 action.remove_der_encoded()
             
             self = prev
             self.action = 'update'
         else:
             raise Exception( 'Invalid action %s supplied' % self.action )
     else:
         ## Set creation data
         self.created = datetime.datetime.now()
         delta = datetime.timedelta(self.valid_days)
         self.expiry_date = datetime.datetime.now() + delta
         
         ## Force instance to be active
         self.active = True
         
         ## Reset the action
         self.action = 'update'
         
         ## Rebuild the ca metadata
         self.rebuild_ca_metadata(modify=True, task='append')
         
         ## Generate keys and certificates
         action = Openssl(self)
         action.generate_key()
         
         if not self.parent:
             action.generate_self_signed_cert()
         else:
             action.generate_csr()
             action.sign_csr()
         
         if self.der_encoded:
             action.generate_der_encoded()
         
         ## Generate CRL
         action.generate_crl(self.name, self.passphrase)
         
         ## Get the serial from certificate
         self.serial = action.get_serial_from_cert()
         
         ## Generate ca chain (db field and chain file)
         chain = []
         chain_str = ''
         
         p = self.parent
         
         if self.parent == None:
             chain.append('self-signed')
         else:
             chain.append( self.common_name )
             while p != None:
                 chain.append(p.common_name)
                 p = p.parent
         
         chain.reverse()
         
         ## Build chain string and file
         for i in chain:
             if chain_str == '':
                 chain_str += '%s' % i
             else:
                 chain_str += ' → %s' % i
         
         self.ca_chain = chain_str
         action.update_ca_chain_file()
         
         ## Encrypt passphrase and blank parent's passphrase
         self.passphrase = md5_constructor(self.passphrase).hexdigest()
         
         ## Set change text to fixed value
         c_list.append('Created certificate "%s"' % self.common_name)
     
     ## Blank parent passphrase
     self.parent_passphrase = None
     
     ## Save the data
     super(CertificateAuthority, self).save(*args, **kwargs)
     
     ## Update changelog
     self.Update_Changelog(obj=self, user=c_user, action=c_action, changes=c_list)
Exemplo n.º 11
0
 def save(self, *args, **kwargs):
     """Save the Certificate object"""
     
     ## Set user to None if it's missing
     c_user = getattr(self, 'user', None)
     
     ## Variables to track changes
     c_action = self.action
     c_list   = []
     
     if self.pk:
         if self.action in ('update', 'revoke', 'renew'):
             action = Openssl(self)
             prev   = Certificate.objects.get(pk=self.pk)
             
             if self.action == 'revoke':
                 if not self.parent:
                     raise Exception( "You cannot revoke a self-signed certificate! No parent => No revoke" )
                 
                 ## Revoke and generate CRL
                 action.revoke_certificate(self.parent_passphrase)
                 action.generate_crl(self.parent.name, self.parent_passphrase)
                 
                 ## Modify fields
                 prev.active            = False
                 prev.der_encoded       = False
                 prev.pkcs12_encoded    = False
                 prev.revoked           = datetime.datetime.now()
                 c_list.append('Revoked certificate "%s"' % self.common_name)
             elif self.action == 'renew':
                 c_list.append('Renewed certificate "%s"' % self.common_name)
                 
                 ## Revoke if certificate is active
                 if self.parent and not action.get_revoke_status_from_cert():
                     action.revoke_certificate(self.parent_passphrase)
                     action.generate_crl(self.parent.name, self.parent_passphrase)
                 
                 ## Renew certificate and update CRL
                 if self.parent == None:
                     action.generate_self_signed_cert()
                 else:
                     action.generate_csr()
                     action.sign_csr()
                     action.generate_crl(self.parent.name, self.parent_passphrase)
                 
                 ## Modify fields
                 prev.created     = datetime.datetime.now()
                 delta            = datetime.timedelta(self.valid_days)
                 prev.expiry_date = datetime.datetime.now() + delta
                 
                 if prev.valid_days != self.valid_days:
                     c_list.append("Changed valid days to %d" % (prev.valid_days, self.valid_days))
                 
                 prev.valid_days  = self.valid_days
                 prev.active      = True
                 prev.revoked     = None
                 
                 ## Make sure possibly updated fields are saved to DB
                 if prev.country != self.country: c_list.append('Updated country to "%s"' % self.country)
                 if prev.locality != self.locality: c_list.append('Updated locality to "%s"' % self.locality)
                 if prev.organization != self.organization: c_list.append('Updated organization to "%s"' % self.organization)
                 if prev.email != self.email: c_list.append('Updated email to "%s"' % self.email)
                 if prev.OU != self.OU: c_list.append('Updated OU to "%s"' % self.OU)
                 
                 prev.country      = self.country
                 prev.locality     = self.locality
                 prev.organization = self.organization
                 prev.email        = self.email
                 prev.OU           = self.OU
                 
                 ## Get the new serial
                 prev.serial = action.get_serial_from_cert()
                 c_list.append("Serial number changed to %s" % prev.serial)
             
             if self.action != 'revoke':
                 if prev.pkcs12_encoded != self.pkcs12_encoded:
                     c_list.append("PKCS12 encoding set to %s" % self.der_encoded)
                 
                 if self.pkcs12_encoded:
                     if prev.pkcs12_encoded and prev.pkcs12_passphrase == self.pkcs12_passphrase:
                         logger.debug( 'PKCS12 passphrase is unchanged. Nothing to do' )
                     else:
                         action.generate_pkcs12_encoded()
                 else:
                     action.remove_pkcs12_encoded()
                     self.pkcs12_passphrase = prev.pkcs12_passphrase = None
                 
                 if self.pkcs12_passphrase:
                     prev.pkcs12_passphrase = md5_constructor(self.pkcs12_passphrase).hexdigest()
                 else:
                     prev.pkcs12_passphrase = None
                 
                 if prev.der_encoded is not self.der_encoded:
                     c_list.append("DER encoding set to %s" % self.der_encoded)
                 
                 if self.der_encoded:
                     action.generate_der_encoded()
                 else:
                     action.remove_der_encoded()
                 
             ## Update description. This is always allowed
             if prev.description != self.description:
                 c_list.append('Updated description to "%s"' % self.description)
                 prev.description = self.description
             
             ## Save the data
             self = prev
             self.action = 'update'
         else:
             raise Exception( 'Invalid action %s supplied' % self.action )
     else:
         ## Set creation data
         self.created = datetime.datetime.now()
         delta = datetime.timedelta(self.valid_days)
         self.expiry_date = datetime.datetime.now() + delta
         
         ## Force instance to be active
         self.active = True
         
         logger.info( "***** { New certificate generation: %s } *****" % self.name )
         
         ## Generate key and certificate
         action = Openssl(self)
         action.generate_key()
         
         if self.parent:
             action.generate_csr()
             action.sign_csr()
             self.ca_chain = self.parent.ca_chain
             if self.ca_chain == 'self-signed':
                 self.ca_chain = self.parent.name
         else:
             action.generate_self_signed_cert()
             self.ca_chain = "self-signed"
         
         ## Get the serial from certificate
         self.serial = action.get_serial_from_cert()
         
         ## Encoding
         if self.der_encoded:
             action.generate_der_encoded()
         
         if self.pkcs12_encoded:
             action.generate_pkcs12_encoded()
         
         ## Encrypt passphrase and blank parent's passphrase
         if self.passphrase:
             self.passphrase = md5_constructor(self.passphrase).hexdigest()
         
         ## Set change text to fixed value
         c_list.append('Created certificate "%s"' % action.subj)
     
     ## Blank parent passphrase
     self.parent_passphrase = None
     
     ## Save the data
     super(Certificate, self).save(*args, **kwargs)
     
     ## Update changelog
     self.Update_Changelog(obj=self, user=c_user, action=c_action, changes=c_list)
Exemplo n.º 12
0
 def save(self, *args, **kwargs):
     """Save the CertificateAuthority object"""
     
     ## Set user to None if it's missing
     c_user = getattr(self, 'user', None)
     
     ## Variables to track changes
     c_action = self.action
     c_list   = []
     
     if self.pk:
         if self.action in ('update', 'revoke', 'renew'):
             action = Openssl(self)
             prev   = CertificateAuthority.objects.get(pk=self.pk)
             
             if self.action in ('revoke', 'renew'):
                 if self.action == 'revoke':
                     if not self.parent:
                         raise Exception( "You cannot revoke a self-signed certificate! No parent => No revoke" )
                     
                     ## Revoke and generate CRL
                     action.revoke_certificate(self.parent_passphrase)
                     action.generate_crl(self.parent.name, self.parent_passphrase)
                     
                     ## Modify fields
                     prev.active            = False
                     prev.der_encoded       = False
                     prev.revoked           = datetime.datetime.now()
                     
                     c_list.append('Revoked certificate "%s"' % self.common_name)
                 elif self.action == 'renew':
                     c_list.append('Renewed certificate "%s"' % self.common_name)
                     
                     ## Revoke if certificate is active
                     if self.parent and not action.get_revoke_status_from_cert():
                         action.revoke_certificate(self.parent_passphrase)
                         action.generate_crl(self.parent.name, self.parent_passphrase)
                     
                     ## Rebuild the ca metadata
                     self.rebuild_ca_metadata(modify=True, task='replace')
                     
                     ## Renew certificate and update CRL
                     if self.parent == None:
                         action.generate_self_signed_cert()
                         action.generate_crl(self.name, self.passphrase)
                     else:
                         action.generate_csr()
                         action.sign_csr()
                         action.generate_crl(self.parent.name, self.parent_passphrase)
                     
                     action.update_ca_chain_file()
                     
                     ## Modify fields
                     prev.created = datetime.datetime.now()
                     delta = datetime.timedelta(self.valid_days)
                     prev.expiry_date = datetime.datetime.now() + delta
                     
                     if prev.valid_days != self.valid_days:
                         c_list.append("Changed valid days to %d" % (prev.valid_days, self.valid_days))
                     
                     prev.valid_days  = self.valid_days
                     prev.active      = True
                     prev.revoked     = None
                     
                     ## Make sure possibly updated fields are saved to DB
                     if prev.country != self.country: c_list.append('Updated country to "%s"' % self.country)
                     if prev.locality != self.locality: c_list.append('Updated locality to "%s"' % self.locality)
                     if prev.organization != self.organization: c_list.append('Updated organization to "%s"' % self.organization)
                     if prev.email != self.email: c_list.append('Updated email to "%s"' % self.email)
                     if prev.OU != self.OU: c_list.append('Updated OU to "%s"' % self.OU)
                     
                     prev.country      = self.country
                     prev.locality     = self.locality
                     prev.organization = self.organization
                     prev.email        = self.email
                     prev.OU           = self.OU
                     
                     ## Get the new serial
                     prev.serial = action.get_serial_from_cert()
                     c_list.append("Serial number changed to %s" % prev.serial)
                     
                 ## DB-revoke all related certs
                 garbage = []
                 id_dict = { 'cert': [], 'ca': [], }
                 
                 from pki.views import chain_recursion as r_chain_recursion
                 r_chain_recursion(self.id, garbage, id_dict)
                 
                 for i in id_dict['cert']:
                     x = Certificate.objects.get(pk=i)
                     x.active         = False
                     x.der_encoded    = False
                     x.pkcs12_encoded = False
                     x.revoked        = datetime.datetime.now()
                     
                     super(Certificate, x).save(*args, **kwargs)
                     self.Update_Changelog(obj=x, user=c_user, action='broken', changes=(['Broken by %s of CA "%s"' % (c_action, self.common_name),]))
                 
                 for i in id_dict['ca']:
                     x = CertificateAuthority.objects.get(pk=i)
                     x.active      = False
                     x.der_encoded = False
                     x.revoked     = datetime.datetime.now()
                     
                     super(CertificateAuthority, x).save(*args, **kwargs)
                     if x.pk != self.pk:
                         self.Update_Changelog(obj=x, user=c_user, action='broken', changes=(['Broken by %s of CA "%s"' % (c_action, self.common_name),]))
             
             ## Update description. This is always allowed
             if prev.description != self.description:
                 c_list.append('Updated description to "%s"' % self.description)
                 prev.description = self.description
             
             if prev.der_encoded is not self.der_encoded:
                 c_list.append("DER encoding set to %s" % self.der_encoded)
             
             if self.der_encoded and self.action != "revoke":
                 action.generate_der_encoded()
             else:
                 action.remove_der_encoded()
             
             self = prev
             self.action = 'update'
         else:
             raise Exception( 'Invalid action %s supplied' % self.action )
     else:
         ## Set creation data
         self.created = datetime.datetime.now()
         delta = datetime.timedelta(self.valid_days)
         self.expiry_date = datetime.datetime.now() + delta
         
         ## Force instance to be active
         self.active = True
         
         ## Reset the action
         self.action = 'update'
         
         ## Rebuild the ca metadata
         self.rebuild_ca_metadata(modify=True, task='append')
         
         ## Generate keys and certificates
         action = Openssl(self)
         action.generate_key()
         
         if not self.parent:
             action.generate_self_signed_cert()
         else:
             action.generate_csr()
             action.sign_csr()
         
         if self.der_encoded:
             action.generate_der_encoded()
         
         ## Generate CRL
         action.generate_crl(self.name, self.passphrase)
         
         ## Get the serial from certificate
         self.serial = action.get_serial_from_cert()
         
         ## Generate ca chain (db field and chain file)
         chain = []
         chain_str = ''
         
         p = self.parent
         
         if self.parent == None:
             chain.append('self-signed')
         else:
             chain.append( self.common_name )
             while p != None:
                 chain.append(p.common_name)
                 p = p.parent
         
         chain.reverse()
         
         ## Build chain string and file
         for i in chain:
             if chain_str == '':
                 chain_str += '%s' % i
             else:
                 chain_str += ' → %s' % i
         
         self.ca_chain = chain_str
         action.update_ca_chain_file()
         
         ## Encrypt passphrase and blank parent's passphrase
         self.passphrase = md5_constructor(self.passphrase).hexdigest()
         
         ## Set change text to fixed value
         c_list.append('Created certificate "%s"' % self.common_name)
     
     ## Blank parent passphrase
     self.parent_passphrase = None
     
     ## Save the data
     super(CertificateAuthority, self).save(*args, **kwargs)
     
     ## Update changelog
     self.Update_Changelog(obj=self, user=c_user, action=c_action, changes=c_list)