Package: django-x509
Simple reusable django app implementing x509 PKI certificates management.Want to help OpenWISP?Find out how to help us grow here.Table of Contents:Current featuresProject goalsDependenciesInstall stable version from pypiInstall development versionSetup (integrate in an existing django project)Installing for developmentInstall and run on dockerSettingsDJANGO_X509_DEFAULT_CERT_VALIDITYDJANGO_X509_DEFAULT_CA_VALIDITYDJANGO_X509_DEFAULT_KEY_LENGTHDJANGO_X509_DEFAULT_DIGEST_ALGORITHMDJANGO_X509_CA_BASIC_CONSTRAINTS_CRITICALDJANGO_X509_CA_BASIC_CONSTRAINTS_PATHLENDJANGO_X509_CA_KEYUSAGE_CRITICALDJANGO_X509_CA_KEYUSAGE_VALUEDJANGO_X509_CERT_KEYUSAGE_CRITICALDJANGO_X509_CERT_KEYUSAGE_VALUEDJANGO_X509_CRL_PROTECTEDExtending django-x5091. Initialize your custom module2. Installdjango-x509&openwisp-utils3. AddEXTENDED_APPS4. Addopenwisp_utils.staticfiles.DependencyFinder5. Addopenwisp_utils.loaders.DependencyLoader6. Inherit the AppConfig class7. Create your custom models8. Add swapper configurations9. Create database migrations10. Create the admin1. Monkey patching2. Inheriting admin classes11. Create root URL configuration12. Import the automated testsContributingSupportChangelogLicenseCurrent featuresCA generationImport existing CAsEnd entity certificate generationImport existing certificatesCertificate revocationCRL view (public or protected)Possibility to specify x509 extensions on each certificateRandom serial numbers based on uuid4 integers (seewhy is this a good idea)Possibility to generate and import passphrase protected x509 certificates/CAsPassphrase protected x509 content will be shown encrypted in the web UIProject goalsprovide a simple and reusable x509 PKI management django appprovide abstract models that can be imported and extended in larger django projectsDependenciesPython >= 3.7OpenSSLInstall stable version from pypiInstall from pypi:pipinstalldjango-x509Install development versionInstall tarball:pipinstallhttps://github.com/openwisp/django-x509/tarball/masterAlternatively you can install via pip using git:pipinstall-egit+git://github.com/openwisp/django-x509#egg=django-x509If you want to contribute, install your cloned fork:gitclonegit@github.com:<your_fork>/django-x509.gitcddjango-x509pythonsetup.pydevelopSetup (integrate in an existing django project)Adddjango_x509toINSTALLED_APPS:INSTALLED_APPS=[# other apps'django_x509',]Add the URLs to your mainurls.py:fromdjango.contribimportadminurlpatterns=[# ... other urls in your project ...url(r'admin/',admin.site.urls),]Then run:./manage.pymigrateInstalling for developmentInstall sqlite:sudoapt-getinstallsqlite3libsqlite3-devInstall your forked repo:gitclonegit://github.com/<your_fork>/django-x509cddjango-x509/pythonsetup.pydevelopInstall test requirements:pipinstall-rrequirements-test.txtCreate database:cdtests/./manage.pymigrate./manage.pycreatesuperuserLaunch development server:./manage.pyrunserverYou can access the admin interface athttp://127.0.0.1:8000/admin/.Run tests with:./runtests.pyInstall and run on dockerBuild from docker file:sudodockerbuild-topenwisp/djangox509.Run the docker container:sudodockerrun-it-p8000:8000openwisp/djangox509SettingsDJANGO_X509_DEFAULT_CERT_VALIDITYtype:intdefault:365Default validity period (in days) when creating new x509 certificates.DJANGO_X509_DEFAULT_CA_VALIDITYtype:intdefault:3650Default validity period (in days) when creating new Certification Authorities.DJANGO_X509_DEFAULT_KEY_LENGTHtype:intdefault:2048Default key length for new CAs and new certificates.Must be one of the following values:512102420484096DJANGO_X509_DEFAULT_DIGEST_ALGORITHMtype:strdefault:sha256Default digest algorithm for new CAs and new certificates.Must be one of the following values:sha1sha224sha256sha384sha512DJANGO_X509_CA_BASIC_CONSTRAINTS_CRITICALtype:booldefault:TrueWhether thebasicConstraintx509 extension must be flagged as critical when creating new CAs.DJANGO_X509_CA_BASIC_CONSTRAINTS_PATHLENtype:intorNonedefault:0Value of thepathLenConstraintofbasicConstraintx509 extension used when creating new CAs.When this value is a positiveintit represents the maximum number of non-self-issued
intermediate certificates that may follow the generated certificate in a valid certification path.Set this value toNoneto avoid imposing any limit.DJANGO_X509_CA_KEYUSAGE_CRITICALtype:booldefault:TrueWhether thekeyUsagex509 extension should be flagged as “critical” for new CAs.DJANGO_X509_CA_KEYUSAGE_VALUEtype:strdefault:cRLSign, keyCertSignValue of thekeyUsagex509 extension for new CAs.DJANGO_X509_CERT_KEYUSAGE_CRITICALtype:booldefault:FalseWhether thekeyUsagex509 extension should be flagged as “critical” for new
end-entity certificates.DJANGO_X509_CERT_KEYUSAGE_VALUEtype:strdefault:digitalSignature, keyEnciphermentValue of thekeyUsagex509 extension for new end-entity certificates.DJANGO_X509_CRL_PROTECTEDtype:booldefault:FalseWhether the view for downloading Certificate Revocation Lists should
be protected with authentication or not.Extending django-x509One of the core values of the OpenWISP project isSoftware Reusability,
for this reasondjango-x509provides a set of base classes
which can be imported, extended and reused to create derivative apps.In order to implement your custom version ofdjango-x509,
you need to perform the steps described in this section.When in doubt, the code in thetest projectand thesample appwill serve you as source of truth:
just replicate and adapt that code to get a basic derivative ofdjango-x509working.Premise: if you plan on using a customized version of this module,
we suggest to start with it since the beginning, because migrating your data
from the default module to your extended version may be time consuming.1. Initialize your custom moduleThe first thing you need to do is to create a new django app which will
contain your custom version ofdjango-x509.A django app is nothing more than apython package(a directory of python scripts), in the following examples we’ll call this django appmyx509, but you can name it how you want:django-admin startapp myx509Keep in mind that the command mentioned above must be called from a directory
which is available in yourPYTHON_PATHso that you can then import the result into your project.Now you need to addmyx509toINSTALLED_APPSin yoursettings.py,
ensuring also thatdjango_x509has been removed:INSTALLED_APPS=[# ... other apps ...# 'django_x509'  <-- comment out or delete this line'myx509']For more information about how to work with django projects and django apps,
please refer to thedjango documentation.2. Installdjango-x509&openwisp-utilsInstall (and add to the requirement of your project):pip install django-x509 openwisp-utils3. AddEXTENDED_APPSAdd the following to yoursettings.py:EXTENDED_APPS=['django_x509']4. Addopenwisp_utils.staticfiles.DependencyFinderAddopenwisp_utils.staticfiles.DependencyFindertoSTATICFILES_FINDERSin yoursettings.py:STATICFILES_FINDERS=['django.contrib.staticfiles.finders.FileSystemFinder','django.contrib.staticfiles.finders.AppDirectoriesFinder','openwisp_utils.staticfiles.DependencyFinder',]5. Addopenwisp_utils.loaders.DependencyLoaderAddopenwisp_utils.loaders.DependencyLoadertoTEMPLATESin yoursettings.py:TEMPLATES=[{'BACKEND':'django.template.backends.django.DjangoTemplates','OPTIONS':{'loaders':['django.template.loaders.filesystem.Loader','django.template.loaders.app_directories.Loader','openwisp_utils.loaders.DependencyLoader',],'context_processors':['django.template.context_processors.debug','django.template.context_processors.request','django.contrib.auth.context_processors.auth','django.contrib.messages.context_processors.messages',],},}]6. Inherit the AppConfig classPlease refer to the following files in the sample app of the test project:sample_x509/__init__.py.sample_x509/apps.py.You have to replicate and adapt that code in your project.For more information regarding the concept ofAppConfigplease refer to
the“Applications” section in the django documentation.7. Create your custom modelsHere we provide an example of how to extend the base models ofdjango-x509. We added a simple “details” field to the
models for demostration of modification:fromdjango.dbimportmodelsfromdjango_x509.base.modelsimportAbstractCa,AbstractCertclassDetailsModel(models.Model):details=models.CharField(max_length=64,blank=True,null=True)classMeta:abstract=TrueclassCa(DetailsModel,AbstractCa):"""
    Concrete Ca model
    """classMeta(AbstractCa.Meta):abstract=FalseclassCert(DetailsModel,AbstractCert):"""
    Concrete Cert model
    """classMeta(AbstractCert.Meta):abstract=FalseYou can add fields in a similar way in yourmodels.pyfile.Note: for doubts regarding how to use, extend or develop models please refer to
the“Models” section in the django documentation.8. Add swapper configurationsOnce you have created the models, add the following to yoursettings.py:# Setting models for swapper moduleDJANGO_X509_CA_MODEL='myx509.Ca'DJANGO_X509_CERT_MODEL='myx509.Cert'Substitutemyx509with the name you chose in step 1.9. Create database migrationsCreate and apply database migrations:./manage.py makemigrations
./manage.py migrateFor more information, refer to the“Migrations” section in the django documentation.10. Create the adminRefer to theadmin.py file of the sample app.To introduce changes to the admin, you can do it in two main ways which are described below.Note: for more information regarding how the django admin works, or how it can be customized,
please refer to“The django admin site” section in the django documentation.1. Monkey patchingIf the changes you need to add are relatively small, you can resort to monkey patching.For example:fromdjango_x509.adminimportCaAdmin,CertAdmin# CaAdmin.list_display.insert(1, 'my_custom_field') <-- your custom change example# CertAdmin.list_display.insert(1, 'my_custom_field') <-- your custom change example2. Inheriting admin classesIf you need to introduce significant changes and/or you don’t want to resort to
monkey patching, you can proceed as follows:fromdjango.contribimportadminfromswapperimportload_modelfromdjango_x509.base.adminimportAbstractCaAdmin,AbstractCertAdminCa=load_model('django_x509','Ca')Cert=load_model('django_x509','Cert')classCertAdmin(AbstractCertAdmin):# add your changes hereclassCaAdmin(AbstractCaAdmin):# add your changes hereadmin.site.register(Ca,CaAdmin)admin.site.register(Cert,CertAdmin)11. Create root URL configurationPlease refer to theurls.pyfile in the test project.For more information about URL configuration in django, please refer to the“URL dispatcher” section in the django documentation.12. Import the automated testsWhen developing a custom application based on this module, it’s a good
idea to import and run the base tests too, so that you can be sure the changes
you’re introducing are not breaking some of the existing features ofdjango-x509.In case you need to add breaking changes, you can overwrite the tests defined
in the base classes to test your own behavior.fromdjango.testimportTestCasefromdjango_x509.tests.baseimportTestX509Mixinfromdjango_x509.tests.test_adminimportModelAdminTestsasBaseModelAdminTestsfromdjango_x509.tests.test_caimportTestCaasBaseTestCafromdjango_x509.tests.test_certimportTestCertasBaseTestCertclassModelAdminTests(BaseModelAdminTests):app_label='myx509'classTestCert(BaseTestCert):passclassTestCa(BaseTestCa):passdelBaseModelAdminTestsdelBaseTestCadelBaseTestCertNow, you can then run tests with:# the --parallel flag is optional
./manage.py test --parallel myx509Substitutemyx509with the name you chose in step 1.For more information about automated tests in django, please refer to“Testing in Django”.ContributingPlease refer to theOpenWISP contributing guidelines.SupportSeeOpenWISP Support Channels.ChangelogSeeCHANGES.LicenseSeeLICENSE.