Add support for adding Client Certificates to access-lists

Client certificate support is added as a new separate type of option for
access-lists.

This commit is the support code to enable access-lists to contain
Client Certificate references.
This commit is contained in:
Will Rouesnel
2023-05-27 01:43:15 +10:00
parent d5b3e53140
commit e5bb50c164
15 changed files with 374 additions and 41 deletions

View File

@ -1,15 +1,16 @@
const _ = require('lodash'); const _ = require('lodash');
const fs = require('fs'); const fs = require('fs');
const batchflow = require('batchflow'); const batchflow = require('batchflow');
const logger = require('../logger').access; const logger = require('../logger').access;
const error = require('../lib/error'); const error = require('../lib/error');
const utils = require('../lib/utils'); const utils = require('../lib/utils');
const accessListModel = require('../models/access_list'); const accessListModel = require('../models/access_list');
const accessListAuthModel = require('../models/access_list_auth'); const accessListAuthModel = require('../models/access_list_auth');
const accessListClientModel = require('../models/access_list_client'); const accessListClientModel = require('../models/access_list_client');
const proxyHostModel = require('../models/proxy_host'); const accessListClientCAsModel = require('../models/access_list_clientcas');
const internalAuditLog = require('./audit-log'); const proxyHostModel = require('../models/proxy_host');
const internalNginx = require('./nginx'); const internalAuditLog = require('./audit-log');
const internalNginx = require('./nginx');
function omissions () { function omissions () {
return ['is_deleted']; return ['is_deleted'];
@ -66,13 +67,26 @@ const internalAccessList = {
}); });
} }
// Now add the client certificate references
if (typeof data.clientcas !== 'undefined' && data.clientcas) {
data.clientcas.map((certificate_id) => {
promises.push(accessListClientCAsModel
.query()
.insert({
access_list_id: row.id,
certificate_id: certificate_id
})
);
});
}
return Promise.all(promises); return Promise.all(promises);
}) })
.then(() => { .then(() => {
// re-fetch with expansions // re-fetch with expansions
return internalAccessList.get(access, { return internalAccessList.get(access, {
id: data.id, id: data.id,
expand: ['owner', 'items', 'clients', 'proxy_hosts.access_list.[clients,items]'] expand: ['owner', 'items', 'clients', 'clientcas', 'proxy_hosts.access_list.[clientcas.certificate,clients,items]']
}, true /* <- skip masking */); }, true /* <- skip masking */);
}) })
.then((row) => { .then((row) => {
@ -204,6 +218,35 @@ const internalAccessList = {
}); });
} }
}) })
.then(() => {
// Check for client certificates and add/update/remove them
if (typeof data.clientcas !== 'undefined' && data.clientcas) {
let promises = [];
data.clientcas.map(function (certificate_id) {
promises.push(accessListClientCAsModel
.query()
.insert({
access_list_id: data.id,
certificate_id: certificate_id
})
);
});
let query = accessListClientCAsModel
.query()
.delete()
.where('access_list_id', data.id);
return query
.then(() => {
// Add new items
if (promises.length) {
return Promise.all(promises);
}
});
}
})
.then(internalNginx.reload) .then(internalNginx.reload)
.then(() => { .then(() => {
// Add to audit log // Add to audit log
@ -218,7 +261,7 @@ const internalAccessList = {
// re-fetch with expansions // re-fetch with expansions
return internalAccessList.get(access, { return internalAccessList.get(access, {
id: data.id, id: data.id,
expand: ['owner', 'items', 'clients', 'proxy_hosts.[certificate,access_list.[clients,items]]'] expand: ['owner', 'items', 'clients', 'clientcas', 'proxy_hosts.[certificate,access_list.[clientcas.certificate,clients,items]]']
}, true /* <- skip masking */); }, true /* <- skip masking */);
}) })
.then((row) => { .then((row) => {
@ -256,7 +299,7 @@ const internalAccessList = {
.joinRaw('LEFT JOIN `proxy_host` ON `proxy_host`.`access_list_id` = `access_list`.`id` AND `proxy_host`.`is_deleted` = 0') .joinRaw('LEFT JOIN `proxy_host` ON `proxy_host`.`access_list_id` = `access_list`.`id` AND `proxy_host`.`is_deleted` = 0')
.where('access_list.is_deleted', 0) .where('access_list.is_deleted', 0)
.andWhere('access_list.id', data.id) .andWhere('access_list.id', data.id)
.allowGraph('[owner,items,clients,proxy_hosts.[certificate,access_list.[clients,items]]]') .withGraphFetched('[owner,items,clients,clientcas,proxy_hosts.[certificate,access_list.[clientcas.certificate,clients,items]]]')
.first(); .first();
if (access_data.permission_visibility !== 'all') { if (access_data.permission_visibility !== 'all') {
@ -294,7 +337,7 @@ const internalAccessList = {
delete: (access, data) => { delete: (access, data) => {
return access.can('access_lists:delete', data.id) return access.can('access_lists:delete', data.id)
.then(() => { .then(() => {
return internalAccessList.get(access, {id: data.id, expand: ['proxy_hosts', 'items', 'clients']}); return internalAccessList.get(access, {id: data.id, expand: ['proxy_hosts', 'items', 'clients', 'clientcas']});
}) })
.then((row) => { .then((row) => {
if (!row) { if (!row) {
@ -377,7 +420,7 @@ const internalAccessList = {
.joinRaw('LEFT JOIN `proxy_host` ON `proxy_host`.`access_list_id` = `access_list`.`id` AND `proxy_host`.`is_deleted` = 0') .joinRaw('LEFT JOIN `proxy_host` ON `proxy_host`.`access_list_id` = `access_list`.`id` AND `proxy_host`.`is_deleted` = 0')
.where('access_list.is_deleted', 0) .where('access_list.is_deleted', 0)
.groupBy('access_list.id') .groupBy('access_list.id')
.allowGraph('[owner,items,clients]') .withGraphFetched('[owner,items,clients,clientcas.certificate]')
.orderBy('access_list.name', 'ASC'); .orderBy('access_list.name', 'ASC');
if (access_data.permission_visibility !== 'all') { if (access_data.permission_visibility !== 'all') {

View File

@ -0,0 +1,50 @@
const migrate_name = 'client_certificates';
const logger = require('../logger').migrate;
/**
* Migrate
*
* @see http://knexjs.org/#Schema
*
* @param {Object} knex
* @param {Promise} Promise
* @returns {Promise}
*/
exports.up = function (knex/*, Promise*/) {
logger.info('[' + migrate_name + '] Migrating Up...');
return knex.schema.createTable('access_list_clientcas', (table) => {
table.increments().primary();
table.dateTime('created_on').notNull();
table.dateTime('modified_on').notNull();
table.integer('access_list_id').notNull().unsigned();
table.integer('certificate_id').notNull().unsigned();
table.json('meta').notNull();
})
.then(function () {
logger.info('[' + migrate_name + '] access_list_clientcas Table created');
})
.then(() => {
logger.info('[' + migrate_name + '] Migrating Up Complete');
});
};
/**
* Undo Migrate
*
* @param {Object} knex
* @param {Promise} Promise
* @returns {Promise}
*/
exports.down = function (knex/*, Promise*/) {
logger.info('[' + migrate_name + '] Migrating Down...');
return knex.schema.dropTable('access_list_clientcas')
.then(() => {
logger.info('[' + migrate_name + '] access_list_clientcas Table dropped');
})
.then(() => {
logger.info('[' + migrate_name + '] Migrating Down Complete');
});
};

View File

@ -1,12 +1,13 @@
// Objection Docs: // Objection Docs:
// http://vincit.github.io/objection.js/ // http://vincit.github.io/objection.js/
const db = require('../db'); const db = require('../db');
const Model = require('objection').Model; const Model = require('objection').Model;
const User = require('./user'); const User = require('./user');
const AccessListAuth = require('./access_list_auth'); const AccessListAuth = require('./access_list_auth');
const AccessListClient = require('./access_list_client'); const AccessListClient = require('./access_list_client');
const now = require('./now_helper'); const AccessListClientCAs = require('./access_list_clientcas');
const now = require('./now_helper');
Model.knex(db); Model.knex(db);
@ -68,6 +69,14 @@ class AccessList extends Model {
to: 'access_list_client.access_list_id' to: 'access_list_client.access_list_id'
} }
}, },
clientcas: {
relation: Model.HasManyRelation,
modelClass: AccessListClientCAs,
join: {
from: 'access_list.id',
to: 'access_list_clientcas.access_list_id'
}
},
proxy_hosts: { proxy_hosts: {
relation: Model.HasManyRelation, relation: Model.HasManyRelation,
modelClass: ProxyHost, modelClass: ProxyHost,

View File

@ -0,0 +1,62 @@
// Objection Docs:
// http://vincit.github.io/objection.js/
const db = require('../db');
const Model = require('objection').Model;
const now = require('./now_helper');
Model.knex(db);
class AccessListClientCAs extends Model {
$beforeInsert () {
this.created_on = now();
this.modified_on = now();
// Default for meta
if (typeof this.meta === 'undefined') {
this.meta = {};
}
}
$beforeUpdate () {
this.modified_on = now();
}
static get name () {
return 'AccessListClientCAs';
}
static get tableName () {
return 'access_list_clientcas';
}
static get jsonAttributes () {
return ['meta'];
}
static get relationMappings () {
return {
access_list: {
relation: Model.HasOneRelation,
modelClass: require('./access_list'),
join: {
from: 'access_list_clientcas.access_list_id',
to: 'access_list.id'
},
modify: function (qb) {
qb.where('access_list.is_deleted', 0);
}
},
certificate: {
relation: Model.HasOneRelation,
modelClass: require('./certificate'),
join: {
from: 'access_list_clientcas.certificate_id',
to: 'certificate.id'
}
}
};
}
}
module.exports = AccessListClientCAs;

View File

@ -142,6 +142,13 @@
} }
} }
}, },
"clientcas": {
"type": "array",
"minItems": 0,
"items": {
"type": "integer"
}
},
"meta": { "meta": {
"$ref": "#/definitions/meta" "$ref": "#/definitions/meta"
} }
@ -209,6 +216,13 @@
} }
} }
} }
},
"clientcas": {
"type": "array",
"minItems": 0,
"items": {
"type": "integer"
}
} }
} }
}, },

View File

@ -8,6 +8,7 @@
<ul class="nav nav-tabs" role="tablist"> <ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="nav-item"><a href="#details" aria-controls="tab1" role="tab" data-toggle="tab" class="nav-link active show" aria-selected="true"><i class="fe fe-zap"></i> <%- i18n('access-lists', 'details') %></a></li> <li role="presentation" class="nav-item"><a href="#details" aria-controls="tab1" role="tab" data-toggle="tab" class="nav-link active show" aria-selected="true"><i class="fe fe-zap"></i> <%- i18n('access-lists', 'details') %></a></li>
<li role="presentation" class="nav-item"><a href="#auth" aria-controls="tab4" role="tab" data-toggle="tab" class="nav-link" aria-selected="false"><i class="fe fe-users"></i> <%- i18n('access-lists', 'authorization') %></a></li> <li role="presentation" class="nav-item"><a href="#auth" aria-controls="tab4" role="tab" data-toggle="tab" class="nav-link" aria-selected="false"><i class="fe fe-users"></i> <%- i18n('access-lists', 'authorization') %></a></li>
<li role="presentation" class="nav-item"><a href="#clientca" aria-controls="tab4" role="tab" data-toggle="tab" class="nav-link" aria-selected="false"><i class="fe fe-lock"></i> <%- i18n('access-lists', 'client-certificates') %></a></li>
<li role="presentation" class="nav-item"><a href="#access" aria-controls="tab2" role="tab" data-toggle="tab" class="nav-link" aria-selected="false"><i class="fe fe-radio"></i> <%- i18n('access-lists', 'access') %></a></li> <li role="presentation" class="nav-item"><a href="#access" aria-controls="tab2" role="tab" data-toggle="tab" class="nav-link" aria-selected="false"><i class="fe fe-radio"></i> <%- i18n('access-lists', 'access') %></a></li>
</ul> </ul>
@ -71,6 +72,34 @@
</div> </div>
</div> </div>
<!-- Client Certificates -->
<div class="tab-pane" id="clientca">
<p>
Client Certificate Authorization via
<a target="_blank" href="http://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_client_certificate">
Nginx HTTP SSL
</a>
</p>
<div class="row">
<div class="col-sm-10 col-md-10">
<select id="certificate_search" class="form-control custom-select" placeholder="<%- i18n('ssl', 'clientca') %>">
</select>
</div>
<div class="col-sm-2 col-md-2">
<div class="btn-list justify-content-end">
<button type="button" class="btn btn-teal clientca_add"><%- i18n('access-lists', 'clientca-add') %></button>
</div>
</div>
</div>
<label class="form-label">Authorized Client Certificate Authorities</label>
<div class="clientcas">
<!-- clientcas -->
</div>
</div>
<!-- Access --> <!-- Access -->
<div class="tab-pane" id="access"> <div class="tab-pane" id="access">
<p> <p>

View File

@ -4,8 +4,13 @@ const AccessListModel = require('../../../models/access-list');
const template = require('./form.ejs'); const template = require('./form.ejs');
const ItemView = require('./form/item'); const ItemView = require('./form/item');
const ClientView = require('./form/client'); const ClientView = require('./form/client');
const ClientCAView = require('./form/clientca');
require('jquery-serializejson'); require('jquery-serializejson');
require('selectize');
const Helpers = require("../../../lib/helpers");
const certListItemTemplate = require("../certificates-list-item.ejs");
const ItemsView = Mn.CollectionView.extend({ const ItemsView = Mn.CollectionView.extend({
childView: ItemView childView: ItemView
@ -15,39 +20,52 @@ const ClientsView = Mn.CollectionView.extend({
childView: ClientView childView: ClientView
}); });
const ClientCAsView = Mn.CollectionView.extend({
childView: ClientCAView
});
module.exports = Mn.View.extend({ module.exports = Mn.View.extend({
template: template, template: template,
className: 'modal-dialog', className: 'modal-dialog',
ui: { ui: {
items_region: '.items', items_region: '.items',
clients_region: '.clients', clients_region: '.clients',
form: 'form', clientcas_region: '.clientcas',
buttons: '.modal-footer button', certificate_select: 'select[id="certificate_search"]',
cancel: 'button.cancel', form: 'form',
save: 'button.save', buttons: '.modal-footer button',
access_add: 'button.access_add', cancel: 'button.cancel',
auth_add: 'button.auth_add' save: 'button.save',
access_add: 'button.access_add',
auth_add: 'button.auth_add',
clientca_add: 'button.clientca_add',
clientca_del: 'button.clientca_del'
}, },
regions: { regions: {
items_region: '@ui.items_region', items_region: '@ui.items_region',
clients_region: '@ui.clients_region' clients_region: '@ui.clients_region',
clientcas_region: '@ui.clientcas_region'
}, },
events: { events: {
'click @ui.save': function (e) { 'click @ui.save': function (e) {
e.preventDefault(); e.preventDefault();
console.log(this.ui.form); // FIXME
if (!this.ui.form[0].checkValidity()) { if (!this.ui.form[0].checkValidity()) {
$('<input type="submit">').hide().appendTo(this.ui.form).click().remove(); $('<input type="submit">').hide().appendTo(this.ui.form).click().remove();
return; return;
} }
let view = this; let view = this;
let form_data = this.ui.form.serializeJSON();
let items_data = []; let items_data = [];
let clients_data = []; let clients_data = [];
let clientcas_data = [];
let form_data = this.ui.form.serializeJSON();
form_data.username.map(function (val, idx) { form_data.username.map(function (val, idx) {
if (val.trim().length) { if (val.trim().length) {
@ -67,7 +85,13 @@ module.exports = Mn.View.extend({
} }
}); });
if (!items_data.length && !clients_data.length) { if (form_data.certificate_id !== undefined) {
form_data.certificate_id.map(function (val, idx) {
clientcas_data.push(parseInt(val, 10))
});
}
if (!items_data.length && !clients_data.length && !clientcas_data.length) {
alert('You must specify at least 1 Authorization or Access rule'); alert('You must specify at least 1 Authorization or Access rule');
return; return;
} }
@ -77,11 +101,10 @@ module.exports = Mn.View.extend({
satisfy_any: !!form_data.satisfy_any, satisfy_any: !!form_data.satisfy_any,
pass_auth: !!form_data.pass_auth, pass_auth: !!form_data.pass_auth,
items: items_data, items: items_data,
clients: clients_data clients: clients_data,
clientcas: clientcas_data
}; };
console.log(data);
let method = App.Api.Nginx.AccessLists.create; let method = App.Api.Nginx.AccessLists.create;
let is_new = true; let is_new = true;
@ -125,16 +148,55 @@ module.exports = Mn.View.extend({
this.showChildView('items_region', new ItemsView({ this.showChildView('items_region', new ItemsView({
collection: new Backbone.Collection(items) collection: new Backbone.Collection(items)
})); }));
},
'click @ui.clientca_add': function (e) {
e.preventDefault();
App.Api.Nginx.Certificates.getAllClientCertificates().then((certificates) => {
let value = this.ui.certificate_select[0].value;
if (value === undefined || value === '') {
return;
}
let certificate_id = parseInt(this.ui.certificate_select[0].value, 10);
let cert = certificates.filter((cert) => { return cert.id === certificate_id })[0];
let clientcas = this.model.get('clientcas');
clientcas.push({
certificate: cert
});
this.ui.certificate_select[0].selectize.clear();
this.showChildView('clientcas_region', new ClientCAsView({
collection: new Backbone.Collection(clientcas)
}));
})
},
'click @ui.clientca_del': function (e) {
e.preventDefault();
let certificate_id = parseInt(e.currentTarget.dataset.value, 10);
let clientcas = this.model.get('clientcas');
this.model.set('clientcas', clientcas.filter((e) => { return e.certificate.id !== certificate_id }));
clientcas = this.model.get('clientcas');
this.showChildView('clientcas_region', new ClientCAsView({
collection: new Backbone.Collection(clientcas)
}));
} }
}, },
onRender: function () { onRender: function () {
let items = this.model.get('items'); let items = this.model.get('items');
let clients = this.model.get('clients'); let clients = this.model.get('clients');
let clientcas = this.model.get('clientcas');
// Ensure at least one field is shown initally // Ensure at least one field is shown initally
if (!items.length) items.push({}); if (!items.length) items.push({});
if (!clients.length) clients.push({}); if (!clients.length) clients.push({});
if (!clientcas.length) clients.push({});
this.showChildView('items_region', new ItemsView({ this.showChildView('items_region', new ItemsView({
collection: new Backbone.Collection(items) collection: new Backbone.Collection(items)
@ -143,6 +205,37 @@ module.exports = Mn.View.extend({
this.showChildView('clients_region', new ClientsView({ this.showChildView('clients_region', new ClientsView({
collection: new Backbone.Collection(clients) collection: new Backbone.Collection(clients)
})); }));
this.showChildView('clientcas_region', new ClientCAsView({
collection: new Backbone.Collection(clientcas)
}));
this.ui.certificate_select.selectize({
valueField: 'id',
labelField: 'nice_name',
searchField: ['nice_name', 'domain_names'],
create: false,
preload: true,
allowEmptyOption: true,
render: {
option: function (item) {
item.i18n = App.i18n;
item.formatDbDate = Helpers.formatDbDate;
return certListItemTemplate(item);
}
},
load: function (query, callback) {
App.Api.Nginx.Certificates.getAllClientCertificates()
.then(rows => {
callback(rows);
})
.catch(err => {
console.error(err);
callback();
});
},
onLoad: function () {}
});
}, },
initialize: function (options) { initialize: function (options) {

View File

@ -0,0 +1,18 @@
<input id="cacert-<%=certificate.id%>" class="form-selectgroup-input" name="certificate_id[]" value="<%= certificate.id %>" type="checkbox" checked hidden/>
<div class="col-auto">
<i class="fe fe-shield text-green"></i>
</div>
<div class="col flex-fill">
<div class="text-truncate">
<strong><%= certificate.nice_name %></strong>
<div class="text-muted">Expires: <%- formatDbDate(certificate.expires_on, 'Do MMMM YYYY, h:mm a') %></div>
</div>
</div>
<div class="col-auto align-self-center <% if (certificate.is_deleted == 1) { %>text-danger<% } %>">
<% if (certificate.is_deleted == 1) { %><i>Deleted</i><% } %>
</div>
<div class="col-auto align-self-center">
<button class="btn btn-sm btn-outline-danger btn-icon clientca_del" data-value="<%=certificate.id%>">
<i class="fe fe-trash-2"></i>
</button>
</div>

View File

@ -0,0 +1,7 @@
const Mn = require('backbone.marionette');
const template = require('./clientca.ejs');
module.exports = Mn.View.extend({
template: template,
className: 'row'
});

View File

@ -14,6 +14,9 @@
<td> <td>
<%- i18n('access-lists', 'item-count', {count: items.length || 0}) %> <%- i18n('access-lists', 'item-count', {count: items.length || 0}) %>
</td> </td>
<td>
<%- i18n('access-lists', 'clientca-count', {count: clientcas.length || 0}) %>
</td>
<td> <td>
<%- i18n('access-lists', 'client-count', {count: clients.length || 0}) %> <%- i18n('access-lists', 'client-count', {count: clients.length || 0}) %>
</td> </td>

View File

@ -2,6 +2,7 @@
<th width="30">&nbsp;</th> <th width="30">&nbsp;</th>
<th><%- i18n('str', 'name') %></th> <th><%- i18n('str', 'name') %></th>
<th><%- i18n('access-lists', 'authorization') %></th> <th><%- i18n('access-lists', 'authorization') %></th>
<th><%- i18n('access-lists', 'client-certificates') %></th>
<th><%- i18n('access-lists', 'access') %></th> <th><%- i18n('access-lists', 'access') %></th>
<th><%- i18n('access-lists', 'satisfy') %></th> <th><%- i18n('access-lists', 'satisfy') %></th>
<th><%- i18n('proxy-hosts', 'title') %></th> <th><%- i18n('proxy-hosts', 'title') %></th>

View File

@ -73,7 +73,7 @@ module.exports = Mn.View.extend({
e.preventDefault(); e.preventDefault();
let query = this.ui.query.val(); let query = this.ui.query.val();
this.fetch(['owner', 'items', 'clients'], query) this.fetch(['owner', 'items', 'clients', 'clientcas'], query)
.then(response => this.showData(response)) .then(response => this.showData(response))
.catch(err => { .catch(err => {
this.showError(err); this.showError(err);
@ -88,7 +88,7 @@ module.exports = Mn.View.extend({
onRender: function () { onRender: function () {
let view = this; let view = this;
view.fetch(['owner', 'items', 'clients']) view.fetch(['owner', 'items', 'clients', 'clientcas'])
.then(response => { .then(response => {
if (!view.isDestroyed()) { if (!view.isDestroyed()) {
if (response && response.length) { if (response && response.length) {

View File

@ -297,7 +297,7 @@ module.exports = Mn.View.extend({
} }
}, },
load: function (query, callback) { load: function (query, callback) {
App.Api.Nginx.AccessLists.getAll(['items', 'clients']) App.Api.Nginx.AccessLists.getAll(['items', 'clients', 'clientcas'])
.then(rows => { .then(rows => {
callback(rows); callback(rows);
}) })

View File

@ -234,7 +234,10 @@
"access-add": "Add", "access-add": "Add",
"auth-add": "Add", "auth-add": "Add",
"search": "Search Access…", "search": "Search Access…",
"client-certificates": "Client Certificates" "client-certificates": "Client Certificates",
"clientca-add": "Add",
"clientca-del": "Del",
"clientca-count": "{count} {count, select, 1{Authority} other{Authorities}}"
}, },
"users": { "users": {
"title": "Users", "title": "Users",

View File

@ -11,6 +11,7 @@ const model = Backbone.Model.extend({
name: '', name: '',
items: [], items: [],
clients: [], clients: [],
clientcas: [],
// The following are expansions: // The following are expansions:
owner: null owner: null
}; };