• Stars
    star
    338
  • Rank 124,568 (Top 3 %)
  • Language
    Python
  • License
    BSD 3-Clause "New...
  • Created about 8 years ago
  • Updated 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Reusable django app implementing x509 PKI certificates management

django-x509

CI build status Test Coverage Dependency monitoring chat Pypi Version downloads code style: black

demo


Simple reusable django app implementing x509 PKI certificates management.

Want to help OpenWISP? Find out how to help us grow here.



Current features

  • CA generation
  • Import existing CAs
  • End entity certificate generation
  • Import existing certificates
  • Certificate revocation
  • CRL view (public or protected)
  • Possibility to specify x509 extensions on each certificate
  • Random serial numbers based on uuid4 integers (see why is this a good idea)
  • Possibility to generate and import passphrase protected x509 certificates/CAs
  • Passphrase protected x509 content will be shown encrypted in the web UI

Project goals

  • provide a simple and reusable x509 PKI management django app
  • provide abstract models that can be imported and extended in larger django projects

Dependencies

  • Python >= 3.8
  • OpenSSL

Install stable version from pypi

Install from pypi:

pip install django-x509

Install development version

Install tarball:

pip install https://github.com/openwisp/django-x509/tarball/master

Alternatively you can install via pip using git:

pip install -e git+git://github.com/openwisp/django-x509#egg=django-x509

If you want to contribute, install your cloned fork:

git clone [email protected]:<your_fork>/django-x509.git
cd django-x509
python setup.py develop

Setup (integrate in an existing django project)

Add django_x509 to INSTALLED_APPS:

INSTALLED_APPS = [
    # other apps
    'django_x509',
]

Add the URLs to your main urls.py:

from django.contrib import admin

urlpatterns = [
    # ... other urls in your project ...

    url(r'admin/', admin.site.urls),
]

Then run:

./manage.py migrate

Installing for development

Install sqlite:

sudo apt-get install sqlite3 libsqlite3-dev

Install your forked repo:

git clone git://github.com/<your_fork>/django-x509
cd django-x509/
python setup.py develop

Install test requirements:

pip install -r requirements-test.txt

Create database:

cd tests/
./manage.py migrate
./manage.py createsuperuser

Launch development server:

./manage.py runserver

You can access the admin interface at http://127.0.0.1:8000/admin/.

Run tests with:

./runtests.py

Install and run on docker

Build from docker file:

sudo docker build -t openwisp/djangox509 .

Run the docker container:

sudo docker run -it -p 8000:8000 openwisp/djangox509

Settings

DJANGO_X509_DEFAULT_CERT_VALIDITY

type: int
default: 365

Default validity period (in days) when creating new x509 certificates.

DJANGO_X509_DEFAULT_CA_VALIDITY

type: int
default: 3650

Default validity period (in days) when creating new Certification Authorities.

DJANGO_X509_DEFAULT_KEY_LENGTH

type: int
default: 2048

Default key length for new CAs and new certificates.

Must be one of the following values:

  • 512
  • 1024
  • 2048
  • 4096

DJANGO_X509_DEFAULT_DIGEST_ALGORITHM

type: str
default: sha256

Default digest algorithm for new CAs and new certificates.

Must be one of the following values:

  • sha1
  • sha224
  • sha256
  • sha384
  • sha512

DJANGO_X509_CA_BASIC_CONSTRAINTS_CRITICAL

type: bool
default: True

Whether the basicConstraint x509 extension must be flagged as critical when creating new CAs.

DJANGO_X509_CA_BASIC_CONSTRAINTS_PATHLEN

type: int or None
default: 0

Value of the pathLenConstraint of basicConstraint x509 extension used when creating new CAs.

When this value is a positive int it represents the maximum number of non-self-issued intermediate certificates that may follow the generated certificate in a valid certification path.

Set this value to None to avoid imposing any limit.

DJANGO_X509_CA_KEYUSAGE_CRITICAL

type: bool
default: True

Whether the keyUsage x509 extension should be flagged as "critical" for new CAs.

DJANGO_X509_CA_KEYUSAGE_VALUE

type: str
default: cRLSign, keyCertSign

Value of the keyUsage x509 extension for new CAs.

DJANGO_X509_CERT_KEYUSAGE_CRITICAL

type: bool
default: False

Whether the keyUsage x509 extension should be flagged as "critical" for new end-entity certificates.

DJANGO_X509_CERT_KEYUSAGE_VALUE

type: str
default: digitalSignature, keyEncipherment

Value of the keyUsage x509 extension for new end-entity certificates.

DJANGO_X509_CRL_PROTECTED

type: bool
default: False

Whether the view for downloading Certificate Revocation Lists should be protected with authentication or not.

Extending django-x509

One of the core values of the OpenWISP project is Software Reusability, for this reason django-x509 provides a set of base classes which can be imported, extended and reused to create derivative apps.

In order to implement your custom version of django-x509, you need to perform the steps described in this section.

When in doubt, the code in the test project and the sample app will serve you as source of truth: just replicate and adapt that code to get a basic derivative of django-x509 working.

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 module

The first thing you need to do is to create a new django app which will contain your custom version of django-x509.

A django app is nothing more than a python package (a directory of python scripts), in the following examples we'll call this django app myx509, but you can name it how you want:

django-admin startapp myx509

Keep in mind that the command mentioned above must be called from a directory which is available in your PYTHON_PATH so that you can then import the result into your project.

Now you need to add myx509 to INSTALLED_APPS in your settings.py, ensuring also that django_x509 has 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 the django documentation.

2. Install django-x509 & openwisp-utils

Install (and add to the requirement of your project):

pip install django-x509 openwisp-utils

3. Add EXTENDED_APPS

Add the following to your settings.py:

EXTENDED_APPS = ['django_x509']

4. Add openwisp_utils.staticfiles.DependencyFinder

Add openwisp_utils.staticfiles.DependencyFinder to STATICFILES_FINDERS in your settings.py:

STATICFILES_FINDERS = [
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'openwisp_utils.staticfiles.DependencyFinder',
]

5. Add openwisp_utils.loaders.DependencyLoader

Add openwisp_utils.loaders.DependencyLoader to TEMPLATES in your settings.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 class

Please refer to the following files in the sample app of the test project:

You have to replicate and adapt that code in your project.

For more information regarding the concept of AppConfig please refer to the "Applications" section in the django documentation.

7. Create your custom models

Here we provide an example of how to extend the base models of django-x509. We added a simple "details" field to the models for demostration of modification:

from django.db import models
from django_x509.base.models import AbstractCa, AbstractCert

class DetailsModel(models.Model):
    details = models.CharField(max_length=64, blank=True, null=True)

    class Meta:
        abstract = True

class Ca(DetailsModel, AbstractCa):
    """
    Concrete Ca model
    """
    class Meta(AbstractCa.Meta):
        abstract = False

class Cert(DetailsModel, AbstractCert):
    """
    Concrete Cert model
    """
    class Meta(AbstractCert.Meta):
        abstract = False

You can add fields in a similar way in your models.py file.

Note: for doubts regarding how to use, extend or develop models please refer to the "Models" section in the django documentation.

8. Add swapper configurations

Once you have created the models, add the following to your settings.py:

# Setting models for swapper module
DJANGO_X509_CA_MODEL = 'myx509.Ca'
DJANGO_X509_CERT_MODEL = 'myx509.Cert'

Substitute myx509 with the name you chose in step 1.

9. Create database migrations

Create and apply database migrations:

./manage.py makemigrations
./manage.py migrate

For more information, refer to the "Migrations" section in the django documentation.

10. Create the admin

Refer to the admin.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 patching

If the changes you need to add are relatively small, you can resort to monkey patching.

For example:

from django_x509.admin import CaAdmin, CertAdmin

# CaAdmin.list_display.insert(1, 'my_custom_field') <-- your custom change example
# CertAdmin.list_display.insert(1, 'my_custom_field') <-- your custom change example

2. Inheriting admin classes

If you need to introduce significant changes and/or you don't want to resort to monkey patching, you can proceed as follows:

from django.contrib import admin
from swapper import load_model

from django_x509.base.admin import AbstractCaAdmin, AbstractCertAdmin

Ca = load_model('django_x509', 'Ca')
Cert = load_model('django_x509', 'Cert')

class CertAdmin(AbstractCertAdmin):
    # add your changes here

class CaAdmin(AbstractCaAdmin):
    # add your changes here

admin.site.register(Ca, CaAdmin)
admin.site.register(Cert, CertAdmin)

11. Create root URL configuration

Please refer to the urls.py file 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 tests

When 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 of django-x509.

In case you need to add breaking changes, you can overwrite the tests defined in the base classes to test your own behavior.

from django.test import TestCase
from django_x509.tests.base import TestX509Mixin
from django_x509.tests.test_admin import ModelAdminTests as BaseModelAdminTests
from django_x509.tests.test_ca import TestCa as BaseTestCa
from django_x509.tests.test_cert import TestCert as BaseTestCert

class ModelAdminTests(BaseModelAdminTests):
    app_label = 'myx509'

class TestCert(BaseTestCert):
    pass

class TestCa(BaseTestCa):
    pass

del BaseModelAdminTests
del BaseTestCa
del BaseTestCert

Now, you can then run tests with:

# the --parallel flag is optional
./manage.py test --parallel myx509

Substitute myx509 with the name you chose in step 1.

For more information about automated tests in django, please refer to "Testing in Django".

Contributing

Please refer to the OpenWISP contributing guidelines.

Support

See OpenWISP Support Channels.

Changelog

See CHANGES.

License

See LICENSE.

More Repositories

1

django-rest-framework-gis

Geographic add-ons for Django REST Framework. Maintained by the OpenWISP Project.
Python
1,070
star
2

openwisp-controller

Network and WiFi controller: provisioning, configuration management and updates, (pull via openwisp-config or push via SSH), x509 PKI management and more. Mainly OpenWRT, but designed to work also on other systems.
Python
545
star
3

ansible-openwisp2

Ansible role that installs and upgrades OpenWISP.
Python
472
star
4

openwisp-config

OpenWRT configuration agent for OpenWISP Controller
Lua
372
star
5

django-freeradius

Administration web interface and REST API for freeradius 3 build in django & python, development has moved to openwisp-radius
Python
367
star
6

netjsonconfig

Network configuration management library based on NetJSON DeviceConfiguration
Python
360
star
7

openwisp-radius

Administration web interface and REST API for freeradius 3 build in django & python. Supports captive portal authentication, WPA Enerprise (802.1x), freeradius rlm_rest, social login, Hotspot 2.0 / 802.11u, importing users from CSV, registration of new users and more.
Python
356
star
8

netjsongraph.js

NetJSON NetworkGraph visualizer.
JavaScript
270
star
9

django-swappable-models

Swapper - The unofficial Django swappable models API. Maintained by the OpenWISP project.
Python
229
star
10

django-netjsonconfig

Configuration manager for embedded devices, implemented as a reusable django-app
JavaScript
196
star
11

django-loci

Reusable Django app for storing geographic and indoor coordinates. Maintained by the OpenWISP Project.
Python
180
star
12

openwisp-users

Implementation of user management and multi-tenancy for OpenWISP
Python
163
star
13

openwisp-network-topology

Network topology collector and visualizer. Collects network topology data from dynamic mesh routing protocols or other popular networking software like OpenVPN, allows to visualize the network graph, save daily snapshots that can be viewed in the future and more.
Python
158
star
14

openwisp-monitoring

Network monitoring system written in Python and Django, designed to be extensible, programmable, scalable and easy to use by end users: once the system is configured, monitoring checks, alerts and metric collection happens automatically.
Python
157
star
15

docker-openwisp

OpenWISP in docker. For production usage we recommend using the ansible-openwisp2 role.
Python
149
star
16

django-netjsongraph

Network Topology Visualizer & Network Topology Collector
Python
139
star
17

openwisp-wifi-login-pages

Configurable captive page for public/private WiFi services providing login, sign up, social login, SMS verification, change password, reset password, change phone number and more.
JavaScript
120
star
18

ansible-openwisp2-imagegenerator

Automatically build several openwisp2 firmware images for different organizations while keeping track of their differences
Shell
120
star
19

openwisp-ipam

IP address space administration module of OpenWISP
Python
101
star
20

OpenWISP-Firmware

An OpenWRT based firmware to be used with OpenWISP Manager
Shell
86
star
21

django-ipam

The development of this project has moved to openwisp-ipam
Python
78
star
22

netdiff

Python library for parsing network topology data (eg: dynamic routing protocols, OpenVPN, NetJSON, CNML) and detect changes.
Python
78
star
23

openwisp-utils

Python and Django utilities shared between different openwisp modules
Python
74
star
24

django-flat-json-widget

Flat JSON widget for django, used and maintained by the OpenWISP project.
Python
63
star
25

OpenWISP-Captive-Portals-Manager

OWCPM is a captive portal written from scratch with Ruby on Rails.
Ruby
58
star
26

openwisp-firmware-upgrader

Firmware upgrade solution for OpenWRT with possibility to add support for other embedded OSes. Provides features like automatic retry for network failures, mass upgrades, REST API and more.
Python
50
star
27

openwisp-docs

OpenWISP Documentation.
Python
48
star
28

vagrant-openwisp2

Ansible Vagrant profile to install an OpenWISP 2 server
44
star
29

OpenWISP-User-Management-System

OpenWISP User Management System (OWUMS) is a Ruby on Rails application, capable of managing a WISP's user base.
Ruby
40
star
30

openwisp-notifications

Notifications module of OpenWISP
Python
39
star
31

netengine

Python abstraction layer for extracting information from network devices.
Python
39
star
32

OpenWISP-Website

OpenWISP Project's website
HTML
37
star
33

OpenWISP-Manager

The OpenWISP Manager is a RoR web GUI for configuring OpenWISP firmware-based access points.
Ruby
36
star
34

openwrt-openwisp-monitoring

OpenWRT monitoring agent for openwisp-monitoring
Lua
21
star
35

luci-openwisp

OpenWISP configuration interface implemented as LuCI extensions
HTML
20
star
36

django-owm-legacy

OpenWISP Manager backward compatible legacy features implemented in django
Python
17
star
37

OpenWISP-Geographic-Monitoring

A Rails application for managing a wISP's access points
Ruby
15
star
38

openwrt-zabbixd

Ucified Zabbix Packages
Makefile
13
star
39

coova-chilli-openwrt

Makefile
12
star
40

netjsonconfig-editor.js

[GSOC 2017] This project has stalled.
JavaScript
12
star
41

django-jsonschema-widget

JavaScript
11
star
42

OpenWISP-Middle-Ware

A Sinatra application for interconnecting OpenWISP applications via a RESTful API
Ruby
11
star
43

OpenWISP-Puppet-Modules

A set of modules and hacks for the https://openwisp.caspur.it project
HTML
10
star
44

AdaLoveBot-intents

Helping bot of the OpenWISP Chat
JavaScript
9
star
45

openwisp-netcheck

Shell
9
star
46

openwisp-template-library-backend

Python
8
star
47

ansible-freeitaliawifi-login-page

Standard login page for Free ItaliaWifi federated networks
JavaScript
7
star
48

netjson-templates

CSS
6
star
49

ansible-wireguard-openwisp

Python
6
star
50

openwisp-template-library-frontend

GSOC 19
JavaScript
6
star
51

OpenWISP-ETL

Extract Transform Load Module developed with pentaho pdi ce-5.0.1.A
6
star
52

openVPNServer

Ruby
5
star
53

openwrt-feed

DEPRECATED, work moved on OpenWisp-Firmware repo
Shell
5
star
54

lxdock-openwisp2

This repository is only a mirror. If you want to work on it, make a fork on https://gitlab.com/openwisp/lxdock-openwisp2
5
star
55

packet-legacy

packet-legacy
Ruby
4
star
56

ansible-ow-influxdb

4
star
57

OpenWISP-BI

Business Intelligence module developed with pentaho biserver ce-4.8.0
4
star
58

ansible-openwisp-wifi-login-pages

Ansible role to deploy and manage OpenWISP WiFi Login Pages
Jinja
4
star
59

openwisp-sphinx-theme

OpenWISP Sphinx Theme
CSS
3
star
60

openwisp-dev-env

Automated development environment for OpenWISP, work in progress.
3
star
61

openwisp-sentry-utils

Python
2
star
62

ansible-openwisp2-iptables

ansible role containing iptables rules to protect an openwisp2 instance
Shell
2
star