mirror of
https://github.com/laurivosandi/certidude
synced 2025-10-30 08:59:13 +00:00
Several updates #3
* Move SessionResource and CertificateAuthorityResource to api/session.py * Log browser user agent for logins * Remove static sink from backend, nginx always serves static now * Don't emit 'attribute-update' event if no attributes were changed * Better CN extraction from DN during lease update * Log user who deleted request * Remove long polling CRL fetch API call and relevant test * Merge auth decorators ldap_authenticate, kerberos_authenticate, pam_authenticate * Add 'kerberos subnets' to distinguish authentication method * Add 'admin subnets' to filter traffic to administrative API calls * Highlight recent log events * Links to switch between 2, 3 and 4 column layouts in the dashboard * Restored certidude client snippets in request dialog * Various bugfixes, improved log messages
This commit is contained in:
@@ -1,218 +1,19 @@
|
||||
# encoding: utf-8
|
||||
|
||||
import falcon
|
||||
import mimetypes
|
||||
import logging
|
||||
import os
|
||||
import hashlib
|
||||
from datetime import datetime
|
||||
from xattr import listxattr, getxattr
|
||||
from certidude.common import cert_to_dn
|
||||
from certidude.user import User
|
||||
from certidude.decorators import serialize, csrf_protection
|
||||
from certidude import const, config, authority
|
||||
from .utils import AuthorityHandler
|
||||
from .utils.firewall import login_required, authorize_admin
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class CertificateAuthorityResource(object):
|
||||
def on_get(self, req, resp):
|
||||
logger.info("Served CA certificate to %s", req.context.get("remote_addr"))
|
||||
resp.stream = open(config.AUTHORITY_CERTIFICATE_PATH, "rb")
|
||||
resp.append_header("Content-Type", "application/x-x509-ca-cert")
|
||||
resp.append_header("Content-Disposition", "attachment; filename=%s.crt" %
|
||||
const.HOSTNAME.encode("ascii"))
|
||||
|
||||
|
||||
class SessionResource(AuthorityHandler):
|
||||
@csrf_protection
|
||||
@serialize
|
||||
@login_required
|
||||
@authorize_admin
|
||||
def on_get(self, req, resp):
|
||||
|
||||
def serialize_requests(g):
|
||||
for common_name, path, buf, req, submitted, server in g():
|
||||
try:
|
||||
submission_address = getxattr(path, "user.request.address").decode("ascii") # TODO: move to authority.py
|
||||
except IOError:
|
||||
submission_address = None
|
||||
try:
|
||||
submission_hostname = getxattr(path, "user.request.hostname").decode("ascii") # TODO: move to authority.py
|
||||
except IOError:
|
||||
submission_hostname = None
|
||||
yield dict(
|
||||
submitted = submitted,
|
||||
common_name = common_name,
|
||||
address = submission_address,
|
||||
hostname = submission_hostname if submission_hostname != submission_address else None,
|
||||
md5sum = hashlib.md5(buf).hexdigest(),
|
||||
sha1sum = hashlib.sha1(buf).hexdigest(),
|
||||
sha256sum = hashlib.sha256(buf).hexdigest(),
|
||||
sha512sum = hashlib.sha512(buf).hexdigest()
|
||||
)
|
||||
|
||||
def serialize_revoked(g):
|
||||
for common_name, path, buf, cert, signed, expired, revoked, reason in g(limit=5):
|
||||
yield dict(
|
||||
serial = "%x" % cert.serial_number,
|
||||
common_name = common_name,
|
||||
# TODO: key type, key length, key exponent, key modulo
|
||||
signed = signed,
|
||||
expired = expired,
|
||||
revoked = revoked,
|
||||
reason = reason,
|
||||
sha256sum = hashlib.sha256(buf).hexdigest())
|
||||
|
||||
def serialize_certificates(g):
|
||||
for common_name, path, buf, cert, signed, expires in g():
|
||||
# Extract certificate tags from filesystem
|
||||
try:
|
||||
tags = []
|
||||
for tag in getxattr(path, "user.xdg.tags").decode("utf-8").split(","):
|
||||
if "=" in tag:
|
||||
k, v = tag.split("=", 1)
|
||||
else:
|
||||
k, v = "other", tag
|
||||
tags.append(dict(id=tag, key=k, value=v))
|
||||
except IOError: # No such attribute(s)
|
||||
tags = None
|
||||
|
||||
attributes = {}
|
||||
for key in listxattr(path):
|
||||
if key.startswith(b"user.machine."):
|
||||
attributes[key[13:].decode("ascii")] = getxattr(path, key).decode("ascii")
|
||||
|
||||
# Extract lease information from filesystem
|
||||
try:
|
||||
last_seen = datetime.strptime(getxattr(path, "user.lease.last_seen").decode("ascii"), "%Y-%m-%dT%H:%M:%S.%fZ")
|
||||
lease = dict(
|
||||
inner_address = getxattr(path, "user.lease.inner_address").decode("ascii"),
|
||||
outer_address = getxattr(path, "user.lease.outer_address").decode("ascii"),
|
||||
last_seen = last_seen,
|
||||
age = datetime.utcnow() - last_seen
|
||||
)
|
||||
except IOError: # No such attribute(s)
|
||||
lease = None
|
||||
|
||||
try:
|
||||
signer_username = getxattr(path, "user.signature.username").decode("ascii")
|
||||
except IOError:
|
||||
signer_username = None
|
||||
|
||||
# TODO: dedup
|
||||
yield dict(
|
||||
serial = "%x" % cert.serial_number,
|
||||
organizational_unit = cert.subject.native.get("organizational_unit_name"),
|
||||
common_name = common_name,
|
||||
# TODO: key type, key length, key exponent, key modulo
|
||||
signed = signed,
|
||||
expires = expires,
|
||||
sha256sum = hashlib.sha256(buf).hexdigest(),
|
||||
signer = signer_username,
|
||||
lease = lease,
|
||||
tags = tags,
|
||||
attributes = attributes or None,
|
||||
extensions = dict([
|
||||
(e["extn_id"].native, e["extn_value"].native)
|
||||
for e in cert["tbs_certificate"]["extensions"]
|
||||
if e["extn_id"].native in ("extended_key_usage",)])
|
||||
)
|
||||
|
||||
logger.info("Logged in authority administrator %s from %s" % (req.context.get("user"), req.context.get("remote_addr")))
|
||||
return dict(
|
||||
user = dict(
|
||||
name=req.context.get("user").name,
|
||||
gn=req.context.get("user").given_name,
|
||||
sn=req.context.get("user").surname,
|
||||
mail=req.context.get("user").mail
|
||||
),
|
||||
request_submission_allowed = config.REQUEST_SUBMISSION_ALLOWED,
|
||||
service = dict(
|
||||
protocols = config.SERVICE_PROTOCOLS,
|
||||
routers = [j[0] for j in authority.list_signed(
|
||||
common_name=config.SERVICE_ROUTERS)]
|
||||
),
|
||||
authority = dict(
|
||||
builder = dict(
|
||||
profiles = config.IMAGE_BUILDER_PROFILES
|
||||
),
|
||||
tagging = [dict(name=t[0], type=t[1], title=t[2]) for t in config.TAG_TYPES],
|
||||
lease = dict(
|
||||
offline = 600, # Seconds from last seen activity to consider lease offline, OpenVPN reneg-sec option
|
||||
dead = 604800 # Seconds from last activity to consider lease dead, X509 chain broken or machine discarded
|
||||
),
|
||||
certificate = dict(
|
||||
algorithm = authority.public_key.algorithm,
|
||||
common_name = self.authority.certificate.subject.native["common_name"],
|
||||
distinguished_name = cert_to_dn(self.authority.certificate),
|
||||
md5sum = hashlib.md5(self.authority.certificate_buf).hexdigest(),
|
||||
blob = self.authority.certificate_buf.decode("ascii"),
|
||||
),
|
||||
mailer = dict(
|
||||
name = config.MAILER_NAME,
|
||||
address = config.MAILER_ADDRESS
|
||||
) if config.MAILER_ADDRESS else None,
|
||||
machine_enrollment_subnets=config.MACHINE_ENROLLMENT_SUBNETS,
|
||||
user_enrollment_allowed=config.USER_ENROLLMENT_ALLOWED,
|
||||
user_multiple_certificates=config.USER_MULTIPLE_CERTIFICATES,
|
||||
events = config.EVENT_SOURCE_SUBSCRIBE % config.EVENT_SOURCE_TOKEN,
|
||||
requests=serialize_requests(self.authority.list_requests),
|
||||
signed=serialize_certificates(self.authority.list_signed),
|
||||
revoked=serialize_revoked(self.authority.list_revoked),
|
||||
admin_users = User.objects.filter_admins(),
|
||||
user_subnets = config.USER_SUBNETS or None,
|
||||
autosign_subnets = config.AUTOSIGN_SUBNETS or None,
|
||||
request_subnets = config.REQUEST_SUBNETS or None,
|
||||
admin_subnets=config.ADMIN_SUBNETS or None,
|
||||
signature = dict(
|
||||
revocation_list_lifetime=config.REVOCATION_LIST_LIFETIME,
|
||||
profiles = sorted([p.serialize() for p in config.PROFILES.values()], key=lambda p:p.get("slug")),
|
||||
|
||||
)
|
||||
),
|
||||
features=dict(
|
||||
ocsp=bool(config.OCSP_SUBNETS),
|
||||
crl=bool(config.CRL_SUBNETS),
|
||||
token=bool(config.TOKEN_URL),
|
||||
tagging=True,
|
||||
leases=True,
|
||||
logging=config.LOGGING_BACKEND)
|
||||
)
|
||||
|
||||
|
||||
class StaticResource(object):
|
||||
def __init__(self, root):
|
||||
self.root = os.path.realpath(root)
|
||||
|
||||
def __call__(self, req, resp):
|
||||
path = os.path.realpath(os.path.join(self.root, req.path[1:]))
|
||||
if not path.startswith(self.root):
|
||||
raise falcon.HTTPBadRequest()
|
||||
|
||||
if os.path.isdir(path):
|
||||
path = os.path.join(path, "index.html")
|
||||
|
||||
if os.path.exists(path):
|
||||
content_type, content_encoding = mimetypes.guess_type(path)
|
||||
if content_type:
|
||||
resp.append_header("Content-Type", content_type)
|
||||
if content_encoding:
|
||||
resp.append_header("Content-Encoding", content_encoding)
|
||||
resp.stream = open(path, "rb")
|
||||
logger.debug("Serving '%s' from '%s'", req.path, path)
|
||||
else:
|
||||
resp.status = falcon.HTTP_404
|
||||
resp.body = "File '%s' not found" % req.path
|
||||
logger.info("File '%s' not found, path resolved to '%s'", req.path, path)
|
||||
import ipaddress
|
||||
import os
|
||||
from certidude import config
|
||||
from user_agents import parse
|
||||
|
||||
|
||||
class NormalizeMiddleware(object):
|
||||
def process_request(self, req, resp, *args):
|
||||
assert not req.get_param("unicode") or req.get_param("unicode") == u"✓", "Unicode sanity check failed"
|
||||
req.context["remote_addr"] = ipaddress.ip_address(req.access_route[0])
|
||||
if req.user_agent:
|
||||
req.context["user_agent"] = parse(req.user_agent)
|
||||
else:
|
||||
req.context["user_agent"] = "Unknown user agent"
|
||||
|
||||
def certidude_app(log_handlers=[]):
|
||||
from certidude import authority, config
|
||||
@@ -225,10 +26,10 @@ def certidude_app(log_handlers=[]):
|
||||
from .bootstrap import BootstrapResource
|
||||
from .token import TokenResource
|
||||
from .builder import ImageBuilderResource
|
||||
from .session import SessionResource, CertificateAuthorityResource
|
||||
|
||||
app = falcon.API(middleware=NormalizeMiddleware())
|
||||
app.req_options.auto_parse_form_urlencoded = True
|
||||
#app.req_options.strip_url_path_trailing_slash = False
|
||||
|
||||
# Certificate authority API calls
|
||||
app.add_route("/api/certificate/", CertificateAuthorityResource())
|
||||
@@ -270,9 +71,6 @@ def certidude_app(log_handlers=[]):
|
||||
from .scep import SCEPResource
|
||||
app.add_route("/api/scep/", SCEPResource(authority))
|
||||
|
||||
# Add sink for serving static files
|
||||
app.add_sink(StaticResource(os.path.join(__file__, "..", "..", "static")))
|
||||
|
||||
if config.OCSP_SUBNETS:
|
||||
from .ocsp import OCSPResource
|
||||
app.add_sink(OCSPResource(authority), prefix="/api/ocsp")
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import falcon
|
||||
import logging
|
||||
import re
|
||||
from xattr import setxattr, listxattr, removexattr
|
||||
from xattr import setxattr, listxattr, removexattr, getxattr
|
||||
from certidude import push
|
||||
from certidude.decorators import serialize, csrf_protection
|
||||
from .utils.firewall import login_required, authorize_admin, whitelist_subject
|
||||
@@ -21,7 +21,6 @@ class AttributeResource(object):
|
||||
Return extended attributes stored on the server.
|
||||
This not only contains tags and lease information,
|
||||
but might also contain some other sensitive information.
|
||||
Results made available only to lease IP address.
|
||||
"""
|
||||
try:
|
||||
path, buf, cert, attribs = self.authority.get_attributes(cn,
|
||||
@@ -44,14 +43,22 @@ class AttributeResource(object):
|
||||
if not re.match("[a-z0-9_\.]+$", key):
|
||||
raise falcon.HTTPBadRequest("Invalid key %s" % key)
|
||||
valid = set()
|
||||
modified = False
|
||||
for key, value in req.params.items():
|
||||
identifier = ("user.%s.%s" % (self.namespace, key)).encode("ascii")
|
||||
try:
|
||||
if getxattr(path, identifier).decode("utf-8") != value:
|
||||
modified = True
|
||||
except OSError: # no such attribute
|
||||
pass
|
||||
setxattr(path, identifier, value.encode("utf-8"))
|
||||
valid.add(identifier)
|
||||
for key in listxattr(path):
|
||||
if not key.startswith(namespace):
|
||||
continue
|
||||
if key not in valid:
|
||||
modified = True
|
||||
removexattr(path, key)
|
||||
push.publish("attribute-update", cn)
|
||||
if modified:
|
||||
push.publish("attribute-update", cn)
|
||||
|
||||
|
||||
@@ -33,9 +33,9 @@ class LeaseResource(AuthorityHandler):
|
||||
@authorize_server
|
||||
def on_post(self, req, resp):
|
||||
client_common_name = req.get_param("client", required=True)
|
||||
m = re.match("CN=(.+?),", client_common_name) # It's actually DN, resolve it to CN
|
||||
m = re.match("^(.*, )*CN=(.+?)(, .*)*$", client_common_name) # It's actually DN, resolve it to CN
|
||||
if m:
|
||||
client_common_name, = m.groups()
|
||||
_, client_common_name, _ = m.groups()
|
||||
|
||||
path, buf, cert, signed, expires = self.authority.get_signed(client_common_name) # TODO: catch exceptions
|
||||
if req.get_param("serial") and cert.serial_number != req.get_param_as_int("serial"): # OCSP-ish solution for OpenVPN, not exposed for StrongSwan
|
||||
|
||||
@@ -140,7 +140,7 @@ class RequestListResource(AuthorityHandler):
|
||||
resp.set_header("Content-Type", "application/x-pem-file")
|
||||
_, resp.body = self.authority._sign(csr, body,
|
||||
overwrite=overwrite_allowed, profile=config.PROFILES["rw"])
|
||||
logger.info("Autosigned %s as %s is whitelisted", common_name, req.context.get("remote_addr"))
|
||||
logger.info("Signed %s as %s is whitelisted for autosign", common_name, req.context.get("remote_addr"))
|
||||
return
|
||||
except EnvironmentError:
|
||||
logger.info("Autosign for %s from %s failed, signed certificate already exists",
|
||||
@@ -148,7 +148,7 @@ class RequestListResource(AuthorityHandler):
|
||||
reasons.append("autosign failed, signed certificate already exists")
|
||||
break
|
||||
else:
|
||||
reasons.append("autosign failed, IP address not whitelisted")
|
||||
reasons.append("IP address not whitelisted for autosign")
|
||||
else:
|
||||
reasons.append("autosign not requested")
|
||||
|
||||
@@ -170,7 +170,7 @@ class RequestListResource(AuthorityHandler):
|
||||
push.publish("request-submitted", common_name)
|
||||
|
||||
# Wait the certificate to be signed if waiting is requested
|
||||
logger.info("Stored signing request %s from %s, reasons: %s", common_name, req.context.get("remote_addr"), reasons)
|
||||
logger.info("Signing request %s from %s put on hold, %s", common_name, req.context.get("remote_addr"), ", ".join(reasons))
|
||||
|
||||
if req.get_param("wait"):
|
||||
# Redirect to nginx pub/sub
|
||||
@@ -178,7 +178,6 @@ class RequestListResource(AuthorityHandler):
|
||||
click.echo("Redirecting to: %s" % url)
|
||||
resp.status = falcon.HTTP_SEE_OTHER
|
||||
resp.set_header("Location", url)
|
||||
logger.debug("Redirecting signing request from %s to %s, reasons: %s", req.context.get("remote_addr"), url, ", ".join(reasons))
|
||||
else:
|
||||
# Request was accepted, but not processed
|
||||
resp.status = falcon.HTTP_202
|
||||
@@ -256,7 +255,7 @@ class RequestDetailResource(AuthorityHandler):
|
||||
@authorize_admin
|
||||
def on_delete(self, req, resp, cn):
|
||||
try:
|
||||
self.authority.delete_request(cn)
|
||||
self.authority.delete_request(cn, user=req.context.get("user"))
|
||||
# Logging implemented in the function above
|
||||
except errors.RequestDoesNotExist as e:
|
||||
resp.body = "No certificate signing request for %s found" % cn
|
||||
|
||||
@@ -20,19 +20,12 @@ class RevocationListResource(AuthorityHandler):
|
||||
logger.debug("Serving revocation list (DER) to %s", req.context.get("remote_addr"))
|
||||
resp.body = self.authority.export_crl(pem=False)
|
||||
elif req.client_accepts("application/x-pem-file"):
|
||||
if req.get_param_as_bool("wait"):
|
||||
url = config.LONG_POLL_SUBSCRIBE % "crl"
|
||||
resp.status = falcon.HTTP_SEE_OTHER
|
||||
resp.set_header("Location", url)
|
||||
logger.debug("Redirecting to CRL request to %s", url)
|
||||
resp.body = "Redirecting to %s" % url
|
||||
else:
|
||||
resp.set_header("Content-Type", "application/x-pem-file")
|
||||
resp.append_header(
|
||||
"Content-Disposition",
|
||||
("attachment; filename=%s-crl.pem" % const.HOSTNAME))
|
||||
logger.debug("Serving revocation list (PEM) to %s", req.context.get("remote_addr"))
|
||||
resp.body = self.authority.export_crl()
|
||||
resp.set_header("Content-Type", "application/x-pem-file")
|
||||
resp.append_header(
|
||||
"Content-Disposition",
|
||||
("attachment; filename=%s-crl.pem" % const.HOSTNAME))
|
||||
logger.debug("Serving revocation list (PEM) to %s", req.context.get("remote_addr"))
|
||||
resp.body = self.authority.export_crl()
|
||||
else:
|
||||
logger.debug("Client %s asked revocation list in unsupported format" % req.context.get("remote_addr"))
|
||||
raise falcon.HTTPUnsupportedMediaType(
|
||||
|
||||
178
certidude/api/session.py
Normal file
178
certidude/api/session.py
Normal file
@@ -0,0 +1,178 @@
|
||||
from datetime import datetime
|
||||
from xattr import listxattr, getxattr
|
||||
import falcon
|
||||
import hashlib
|
||||
import logging
|
||||
from certidude import const, config
|
||||
from certidude.common import cert_to_dn
|
||||
from certidude.decorators import serialize, csrf_protection
|
||||
from certidude.user import User
|
||||
from .utils import AuthorityHandler
|
||||
from .utils.firewall import login_required, authorize_admin
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class CertificateAuthorityResource(object):
|
||||
def on_get(self, req, resp):
|
||||
logger.info("Served CA certificate to %s", req.context.get("remote_addr"))
|
||||
resp.stream = open(config.AUTHORITY_CERTIFICATE_PATH, "rb")
|
||||
resp.append_header("Content-Type", "application/x-x509-ca-cert")
|
||||
resp.append_header("Content-Disposition", "attachment; filename=%s.crt" %
|
||||
const.HOSTNAME.encode("ascii"))
|
||||
|
||||
class SessionResource(AuthorityHandler):
|
||||
@csrf_protection
|
||||
@serialize
|
||||
@login_required
|
||||
@authorize_admin
|
||||
def on_get(self, req, resp):
|
||||
|
||||
def serialize_requests(g):
|
||||
for common_name, path, buf, req, submitted, server in g():
|
||||
try:
|
||||
submission_address = getxattr(path, "user.request.address").decode("ascii") # TODO: move to authority.py
|
||||
except IOError:
|
||||
submission_address = None
|
||||
try:
|
||||
submission_hostname = getxattr(path, "user.request.hostname").decode("ascii") # TODO: move to authority.py
|
||||
except IOError:
|
||||
submission_hostname = None
|
||||
yield dict(
|
||||
submitted = submitted,
|
||||
common_name = common_name,
|
||||
address = submission_address,
|
||||
hostname = submission_hostname if submission_hostname != submission_address else None,
|
||||
md5sum = hashlib.md5(buf).hexdigest(),
|
||||
sha1sum = hashlib.sha1(buf).hexdigest(),
|
||||
sha256sum = hashlib.sha256(buf).hexdigest(),
|
||||
sha512sum = hashlib.sha512(buf).hexdigest()
|
||||
)
|
||||
|
||||
def serialize_revoked(g):
|
||||
for common_name, path, buf, cert, signed, expired, revoked, reason in g(limit=5):
|
||||
yield dict(
|
||||
serial = "%x" % cert.serial_number,
|
||||
common_name = common_name,
|
||||
# TODO: key type, key length, key exponent, key modulo
|
||||
signed = signed,
|
||||
expired = expired,
|
||||
revoked = revoked,
|
||||
reason = reason,
|
||||
sha256sum = hashlib.sha256(buf).hexdigest())
|
||||
|
||||
def serialize_certificates(g):
|
||||
for common_name, path, buf, cert, signed, expires in g():
|
||||
# Extract certificate tags from filesystem
|
||||
try:
|
||||
tags = []
|
||||
for tag in getxattr(path, "user.xdg.tags").decode("utf-8").split(","):
|
||||
if "=" in tag:
|
||||
k, v = tag.split("=", 1)
|
||||
else:
|
||||
k, v = "other", tag
|
||||
tags.append(dict(id=tag, key=k, value=v))
|
||||
except IOError: # No such attribute(s)
|
||||
tags = None
|
||||
|
||||
attributes = {}
|
||||
for key in listxattr(path):
|
||||
if key.startswith(b"user.machine."):
|
||||
attributes[key[13:].decode("ascii")] = getxattr(path, key).decode("ascii")
|
||||
|
||||
# Extract lease information from filesystem
|
||||
try:
|
||||
last_seen = datetime.strptime(getxattr(path, "user.lease.last_seen").decode("ascii"), "%Y-%m-%dT%H:%M:%S.%fZ")
|
||||
lease = dict(
|
||||
inner_address = getxattr(path, "user.lease.inner_address").decode("ascii"),
|
||||
outer_address = getxattr(path, "user.lease.outer_address").decode("ascii"),
|
||||
last_seen = last_seen,
|
||||
age = datetime.utcnow() - last_seen
|
||||
)
|
||||
except IOError: # No such attribute(s)
|
||||
lease = None
|
||||
|
||||
try:
|
||||
signer_username = getxattr(path, "user.signature.username").decode("ascii")
|
||||
except IOError:
|
||||
signer_username = None
|
||||
|
||||
# TODO: dedup
|
||||
yield dict(
|
||||
serial = "%x" % cert.serial_number,
|
||||
organizational_unit = cert.subject.native.get("organizational_unit_name"),
|
||||
common_name = common_name,
|
||||
# TODO: key type, key length, key exponent, key modulo
|
||||
signed = signed,
|
||||
expires = expires,
|
||||
sha256sum = hashlib.sha256(buf).hexdigest(),
|
||||
signer = signer_username,
|
||||
lease = lease,
|
||||
tags = tags,
|
||||
attributes = attributes or None,
|
||||
extensions = dict([
|
||||
(e["extn_id"].native, e["extn_value"].native)
|
||||
for e in cert["tbs_certificate"]["extensions"]
|
||||
if e["extn_id"].native in ("extended_key_usage",)])
|
||||
)
|
||||
|
||||
logger.info("Logged in authority administrator %s from %s with %s" % (
|
||||
req.context.get("user"), req.context.get("remote_addr"), req.context.get("user_agent")))
|
||||
return dict(
|
||||
user = dict(
|
||||
name=req.context.get("user").name,
|
||||
gn=req.context.get("user").given_name,
|
||||
sn=req.context.get("user").surname,
|
||||
mail=req.context.get("user").mail
|
||||
),
|
||||
request_submission_allowed = config.REQUEST_SUBMISSION_ALLOWED,
|
||||
service = dict(
|
||||
protocols = config.SERVICE_PROTOCOLS,
|
||||
routers = [j[0] for j in self.authority.list_signed(
|
||||
common_name=config.SERVICE_ROUTERS)]
|
||||
),
|
||||
authority = dict(
|
||||
builder = dict(
|
||||
profiles = config.IMAGE_BUILDER_PROFILES
|
||||
),
|
||||
tagging = [dict(name=t[0], type=t[1], title=t[2]) for t in config.TAG_TYPES],
|
||||
lease = dict(
|
||||
offline = 600, # Seconds from last seen activity to consider lease offline, OpenVPN reneg-sec option
|
||||
dead = 604800 # Seconds from last activity to consider lease dead, X509 chain broken or machine discarded
|
||||
),
|
||||
certificate = dict(
|
||||
algorithm = self.authority.public_key.algorithm,
|
||||
common_name = self.authority.certificate.subject.native["common_name"],
|
||||
distinguished_name = cert_to_dn(self.authority.certificate),
|
||||
md5sum = hashlib.md5(self.authority.certificate_buf).hexdigest(),
|
||||
blob = self.authority.certificate_buf.decode("ascii"),
|
||||
),
|
||||
mailer = dict(
|
||||
name = config.MAILER_NAME,
|
||||
address = config.MAILER_ADDRESS
|
||||
) if config.MAILER_ADDRESS else None,
|
||||
machine_enrollment_subnets=config.MACHINE_ENROLLMENT_SUBNETS,
|
||||
user_enrollment_allowed=config.USER_ENROLLMENT_ALLOWED,
|
||||
user_multiple_certificates=config.USER_MULTIPLE_CERTIFICATES,
|
||||
events = config.EVENT_SOURCE_SUBSCRIBE % config.EVENT_SOURCE_TOKEN,
|
||||
requests=serialize_requests(self.authority.list_requests),
|
||||
signed=serialize_certificates(self.authority.list_signed),
|
||||
revoked=serialize_revoked(self.authority.list_revoked),
|
||||
admin_users = User.objects.filter_admins(),
|
||||
user_subnets = config.USER_SUBNETS or None,
|
||||
autosign_subnets = config.AUTOSIGN_SUBNETS or None,
|
||||
request_subnets = config.REQUEST_SUBNETS or None,
|
||||
admin_subnets=config.ADMIN_SUBNETS or None,
|
||||
signature = dict(
|
||||
revocation_list_lifetime=config.REVOCATION_LIST_LIFETIME,
|
||||
profiles = sorted([p.serialize() for p in config.PROFILES.values()], key=lambda p:p.get("slug")),
|
||||
|
||||
)
|
||||
),
|
||||
features=dict(
|
||||
ocsp=bool(config.OCSP_SUBNETS),
|
||||
crl=bool(config.CRL_SUBNETS),
|
||||
token=bool(config.TOKEN_URL),
|
||||
tagging=True,
|
||||
leases=True,
|
||||
logging=config.LOGGING_BACKEND)
|
||||
)
|
||||
@@ -68,8 +68,8 @@ class SignedCertificateDetailResource(AuthorityHandler):
|
||||
@login_required
|
||||
@authorize_admin
|
||||
def on_delete(self, req, resp, cn):
|
||||
logger.info("Revoked certificate %s by %s from %s",
|
||||
cn, req.context.get("user"), req.context.get("remote_addr"))
|
||||
self.authority.revoke(cn,
|
||||
reason=req.get_param("reason", default="key_compromise"))
|
||||
reason=req.get_param("reason", default="key_compromise"),
|
||||
user=req.context.get("user")
|
||||
)
|
||||
|
||||
|
||||
@@ -41,7 +41,7 @@ class TagResource(AuthorityHandler):
|
||||
else:
|
||||
tags.add("%s=%s" % (key,value))
|
||||
setxattr(path, "user.xdg.tags", ",".join(tags).encode("utf-8"))
|
||||
logger.debug("Tag %s=%s set for %s" % (key, value, cn))
|
||||
logger.info("Tag %s=%s set for %s by %s" % (key, value, cn, req.context.get("user")))
|
||||
push.publish("tag-update", cn)
|
||||
|
||||
|
||||
@@ -68,7 +68,7 @@ class TagDetailResource(object):
|
||||
else:
|
||||
tags.add(value)
|
||||
setxattr(path, "user.xdg.tags", ",".join(tags).encode("utf-8"))
|
||||
logger.debug("Tag %s set to %s for %s" % (tag, value, cn))
|
||||
logger.info("Tag %s set to %s for %s by %s" % (tag, value, cn, req.context.get("user")))
|
||||
push.publish("tag-update", cn)
|
||||
|
||||
@csrf_protection
|
||||
@@ -82,5 +82,5 @@ class TagDetailResource(object):
|
||||
removexattr(path, "user.xdg.tags")
|
||||
else:
|
||||
setxattr(path, "user.xdg.tags", ",".join(tags))
|
||||
logger.debug("Tag %s removed for %s" % (tag, cn))
|
||||
logger.info("Tag %s removed for %s by %s" % (tag, cn, req.context.get("user")))
|
||||
push.publish("tag-update", cn)
|
||||
|
||||
@@ -4,15 +4,17 @@ import logging
|
||||
import binascii
|
||||
import click
|
||||
import gssapi
|
||||
import ldap
|
||||
import os
|
||||
import re
|
||||
import simplepam
|
||||
import socket
|
||||
from asn1crypto import pem, x509
|
||||
from base64 import b64decode
|
||||
from certidude.user import User
|
||||
from certidude import config, const
|
||||
|
||||
logger = logging.getLogger("api")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def whitelist_subnets(subnets):
|
||||
"""
|
||||
@@ -81,158 +83,127 @@ def whitelist_subject(func):
|
||||
|
||||
def authenticate(optional=False):
|
||||
def wrapper(func):
|
||||
def kerberos_authenticate(resource, req, resp, *args, **kwargs):
|
||||
# Try pre-emptive authentication
|
||||
if not req.auth:
|
||||
if optional:
|
||||
def wrapped(resource, req, resp, *args, **kwargs):
|
||||
kerberized = False
|
||||
|
||||
if "kerberos" in config.AUTHENTICATION_BACKENDS:
|
||||
for subnet in config.KERBEROS_SUBNETS:
|
||||
if req.context.get("remote_addr") in subnet:
|
||||
kerberized = True
|
||||
|
||||
if not req.auth: # no credentials provided
|
||||
if optional: # optional allowed
|
||||
req.context["user"] = None
|
||||
return func(resource, req, resp, *args, **kwargs)
|
||||
|
||||
logger.debug("No Kerberos ticket offered while attempting to access %s from %s",
|
||||
req.env["PATH_INFO"], req.context.get("remote_addr"))
|
||||
raise falcon.HTTPUnauthorized("Unauthorized",
|
||||
"No Kerberos ticket offered, are you sure you've logged in with domain user account?",
|
||||
["Negotiate"])
|
||||
if kerberized:
|
||||
logger.debug("No Kerberos ticket offered while attempting to access %s from %s",
|
||||
req.env["PATH_INFO"], req.context.get("remote_addr"))
|
||||
raise falcon.HTTPUnauthorized("Unauthorized",
|
||||
"No Kerberos ticket offered, are you sure you've logged in with domain user account?",
|
||||
["Negotiate"])
|
||||
else:
|
||||
logger.debug("No credentials offered while attempting to access %s from %s",
|
||||
req.env["PATH_INFO"], req.context.get("remote_addr"))
|
||||
raise falcon.HTTPUnauthorized("Unauthorized", "Please authenticate", ("Basic",))
|
||||
|
||||
os.environ["KRB5_KTNAME"] = config.KERBEROS_KEYTAB
|
||||
if kerberized:
|
||||
if not req.auth.startswith("Negotiate "):
|
||||
raise falcon.HTTPBadRequest("Bad request",
|
||||
"Bad header, expected Negotiate: %s" % req.auth)
|
||||
|
||||
try:
|
||||
server_creds = gssapi.creds.Credentials(
|
||||
usage='accept',
|
||||
name=gssapi.names.Name('HTTP/%s'% const.FQDN))
|
||||
except gssapi.raw.exceptions.BadNameError:
|
||||
logger.error("Failed initialize HTTP service principal, possibly bad permissions for %s or /etc/krb5.conf" %
|
||||
config.KERBEROS_KEYTAB)
|
||||
raise
|
||||
os.environ["KRB5_KTNAME"] = config.KERBEROS_KEYTAB
|
||||
|
||||
context = gssapi.sec_contexts.SecurityContext(creds=server_creds)
|
||||
try:
|
||||
server_creds = gssapi.creds.Credentials(
|
||||
usage='accept',
|
||||
name=gssapi.names.Name('HTTP/%s'% const.FQDN))
|
||||
except gssapi.raw.exceptions.BadNameError:
|
||||
logger.error("Failed initialize HTTP service principal, possibly bad permissions for %s or /etc/krb5.conf" %
|
||||
config.KERBEROS_KEYTAB)
|
||||
raise
|
||||
|
||||
if not req.auth.startswith("Negotiate "):
|
||||
raise falcon.HTTPBadRequest("Bad request", "Bad header, expected Negotiate: %s" % req.auth)
|
||||
context = gssapi.sec_contexts.SecurityContext(creds=server_creds)
|
||||
|
||||
token = ''.join(req.auth.split()[1:])
|
||||
token = ''.join(req.auth.split()[1:])
|
||||
|
||||
try:
|
||||
context.step(b64decode(token))
|
||||
except binascii.Error: # base64 errors
|
||||
raise falcon.HTTPBadRequest("Bad request", "Malformed token")
|
||||
except gssapi.raw.exceptions.BadMechanismError:
|
||||
raise falcon.HTTPBadRequest("Bad request", "Unsupported authentication mechanism (NTLM?) was offered. Please make sure you've logged into the computer with domain user account. The web interface should not prompt for username or password.")
|
||||
try:
|
||||
context.step(b64decode(token))
|
||||
except binascii.Error: # base64 errors
|
||||
raise falcon.HTTPBadRequest("Bad request", "Malformed token")
|
||||
except gssapi.raw.exceptions.BadMechanismError:
|
||||
raise falcon.HTTPBadRequest("Bad request", "Unsupported authentication mechanism (NTLM?) was offered. Please make sure you've logged into the computer with domain user account. The web interface should not prompt for username or password.")
|
||||
|
||||
try:
|
||||
username, realm = str(context.initiator_name).split("@")
|
||||
except AttributeError: # TODO: Better exception
|
||||
raise falcon.HTTPForbidden("Failed to determine username, are you trying to log in with correct domain account?")
|
||||
try:
|
||||
username, realm = str(context.initiator_name).split("@")
|
||||
except AttributeError: # TODO: Better exception
|
||||
raise falcon.HTTPForbidden("Failed to determine username, are you trying to log in with correct domain account?")
|
||||
|
||||
if realm != config.KERBEROS_REALM:
|
||||
raise falcon.HTTPForbidden("Forbidden",
|
||||
"Cross-realm trust not supported")
|
||||
if realm != config.KERBEROS_REALM:
|
||||
raise falcon.HTTPForbidden("Forbidden",
|
||||
"Cross-realm trust not supported")
|
||||
|
||||
if username.endswith("$") and optional:
|
||||
# Extract machine hostname
|
||||
# TODO: Assert LDAP group membership
|
||||
req.context["machine"] = username[:-1].lower()
|
||||
req.context["user"] = None
|
||||
else:
|
||||
# Attempt to look up real user
|
||||
req.context["user"] = User.objects.get(username)
|
||||
if username.endswith("$") and optional:
|
||||
# Extract machine hostname
|
||||
# TODO: Assert LDAP group membership
|
||||
req.context["machine"] = username[:-1].lower()
|
||||
req.context["user"] = None
|
||||
else:
|
||||
# Attempt to look up real user
|
||||
req.context["user"] = User.objects.get(username)
|
||||
|
||||
logger.debug("Succesfully authenticated user %s for %s from %s",
|
||||
req.context["user"], req.env["PATH_INFO"], req.context["remote_addr"])
|
||||
return func(resource, req, resp, *args, **kwargs)
|
||||
|
||||
|
||||
def ldap_authenticate(resource, req, resp, *args, **kwargs):
|
||||
"""
|
||||
Authenticate against LDAP with WWW Basic Auth credentials
|
||||
"""
|
||||
|
||||
if optional and not req.get_param_as_bool("authenticate"):
|
||||
logger.debug("Succesfully authenticated user %s for %s from %s",
|
||||
req.context["user"], req.env["PATH_INFO"], req.context["remote_addr"])
|
||||
return func(resource, req, resp, *args, **kwargs)
|
||||
|
||||
import ldap
|
||||
else:
|
||||
if not req.auth.startswith("Basic "):
|
||||
raise falcon.HTTPBadRequest("Bad request", "Bad header, expected Basic: %s" % req.auth)
|
||||
basic, token = req.auth.split(" ", 1)
|
||||
user, passwd = b64decode(token).decode("ascii").split(":", 1)
|
||||
|
||||
if not req.auth:
|
||||
raise falcon.HTTPUnauthorized("Unauthorized",
|
||||
"No authentication header provided",
|
||||
("Basic",))
|
||||
if config.AUTHENTICATION_BACKENDS == {"pam"}:
|
||||
if not simplepam.authenticate(user, passwd, "sshd"):
|
||||
logger.critical("Basic authentication failed for user %s from %s, "
|
||||
"are you sure server process has read access to /etc/shadow?",
|
||||
repr(user), req.context.get("remote_addr"))
|
||||
raise falcon.HTTPUnauthorized("Forbidden", "Invalid password", ("Basic",))
|
||||
conn = None
|
||||
elif "ldap" in config.AUTHENTICATION_BACKENDS:
|
||||
upn = "%s@%s" % (user, config.KERBEROS_REALM)
|
||||
click.echo("Connecting to %s as %s" % (config.LDAP_AUTHENTICATION_URI, upn))
|
||||
conn = ldap.initialize(config.LDAP_AUTHENTICATION_URI, bytes_mode=False)
|
||||
conn.set_option(ldap.OPT_REFERRALS, 0)
|
||||
|
||||
if not req.auth.startswith("Basic "):
|
||||
raise falcon.HTTPBadRequest("Bad request", "Bad header, expected Basic: %s" % req.auth)
|
||||
try:
|
||||
conn.simple_bind_s(upn, passwd)
|
||||
except ldap.STRONG_AUTH_REQUIRED:
|
||||
logger.critical("LDAP server demands encryption, use ldaps:// instead of ldaps://")
|
||||
raise
|
||||
except ldap.SERVER_DOWN:
|
||||
logger.critical("Failed to connect LDAP server at %s, are you sure LDAP server's CA certificate has been copied to this machine?",
|
||||
config.LDAP_AUTHENTICATION_URI)
|
||||
raise
|
||||
except ldap.INVALID_CREDENTIALS:
|
||||
logger.critical("LDAP bind authentication failed for user %s from %s",
|
||||
repr(user), req.context.get("remote_addr"))
|
||||
raise falcon.HTTPUnauthorized("Forbidden",
|
||||
"Please authenticate with %s domain account username" % const.DOMAIN,
|
||||
("Basic",))
|
||||
|
||||
from base64 import b64decode
|
||||
basic, token = req.auth.split(" ", 1)
|
||||
user, passwd = b64decode(token).decode("ascii").split(":", 1)
|
||||
|
||||
upn = "%s@%s" % (user, const.DOMAIN)
|
||||
click.echo("Connecting to %s as %s" % (config.LDAP_AUTHENTICATION_URI, upn))
|
||||
conn = ldap.initialize(config.LDAP_AUTHENTICATION_URI, bytes_mode=False)
|
||||
conn.set_option(ldap.OPT_REFERRALS, 0)
|
||||
req.context["ldap_conn"] = conn
|
||||
else:
|
||||
raise NotImplementedError("No suitable authentication method configured")
|
||||
|
||||
try:
|
||||
conn.simple_bind_s(upn, passwd)
|
||||
except ldap.STRONG_AUTH_REQUIRED:
|
||||
logger.critical("LDAP server demands encryption, use ldaps:// instead of ldaps://")
|
||||
raise
|
||||
except ldap.SERVER_DOWN:
|
||||
logger.critical("Failed to connect LDAP server at %s, are you sure LDAP server's CA certificate has been copied to this machine?",
|
||||
config.LDAP_AUTHENTICATION_URI)
|
||||
raise
|
||||
except ldap.INVALID_CREDENTIALS:
|
||||
logger.critical("LDAP bind authentication failed for user %s from %s",
|
||||
repr(user), req.context.get("remote_addr"))
|
||||
raise falcon.HTTPUnauthorized("Forbidden",
|
||||
"Please authenticate with %s domain account username" % const.DOMAIN,
|
||||
("Basic",))
|
||||
req.context["user"] = User.objects.get(user)
|
||||
except User.DoesNotExist:
|
||||
raise falcon.HTTPUnauthorized("Unauthorized", "Invalid credentials", ("Basic",))
|
||||
|
||||
req.context["ldap_conn"] = conn
|
||||
req.context["user"] = User.objects.get(user)
|
||||
retval = func(resource, req, resp, *args, **kwargs)
|
||||
conn.unbind_s()
|
||||
if conn:
|
||||
conn.unbind_s()
|
||||
return retval
|
||||
|
||||
|
||||
def pam_authenticate(resource, req, resp, *args, **kwargs):
|
||||
"""
|
||||
Authenticate against PAM with WWW Basic Auth credentials
|
||||
"""
|
||||
|
||||
if optional and not req.get_param_as_bool("authenticate"):
|
||||
return func(resource, req, resp, *args, **kwargs)
|
||||
|
||||
if not req.auth:
|
||||
raise falcon.HTTPUnauthorized("Forbidden", "Please authenticate", ("Basic",))
|
||||
|
||||
if not req.auth.startswith("Basic "):
|
||||
raise falcon.HTTPBadRequest("Bad request", "Bad header: %s" % req.auth)
|
||||
|
||||
basic, token = req.auth.split(" ", 1)
|
||||
user, passwd = b64decode(token).decode("ascii").split(":", 1)
|
||||
|
||||
import simplepam
|
||||
if not simplepam.authenticate(user, passwd, "sshd"):
|
||||
logger.critical("Basic authentication failed for user %s from %s, "
|
||||
"are you sure server process has read access to /etc/shadow?",
|
||||
repr(user), req.context.get("remote_addr"))
|
||||
raise falcon.HTTPUnauthorized("Forbidden", "Invalid password", ("Basic",))
|
||||
|
||||
req.context["user"] = User.objects.get(user)
|
||||
return func(resource, req, resp, *args, **kwargs)
|
||||
|
||||
def wrapped(resource, req, resp, *args, **kwargs):
|
||||
# If LDAP enabled and device is not Kerberos capable fall
|
||||
# back to LDAP bind authentication
|
||||
if "ldap" in config.AUTHENTICATION_BACKENDS:
|
||||
if "Android" in req.user_agent or "iPhone" in req.user_agent:
|
||||
return ldap_authenticate(resource, req, resp, *args, **kwargs)
|
||||
if "kerberos" in config.AUTHENTICATION_BACKENDS:
|
||||
return kerberos_authenticate(resource, req, resp, *args, **kwargs)
|
||||
elif config.AUTHENTICATION_BACKENDS == {"pam"}:
|
||||
return pam_authenticate(resource, req, resp, *args, **kwargs)
|
||||
elif config.AUTHENTICATION_BACKENDS == {"ldap"}:
|
||||
return ldap_authenticate(resource, req, resp, *args, **kwargs)
|
||||
else:
|
||||
raise NotImplementedError("Authentication backend %s not supported" % config.AUTHENTICATION_BACKENDS)
|
||||
return wrapped
|
||||
return wrapper
|
||||
|
||||
@@ -247,7 +218,6 @@ def authorize_admin(func):
|
||||
@whitelist_subnets(config.ADMIN_SUBNETS)
|
||||
def wrapped(resource, req, resp, *args, **kwargs):
|
||||
if req.context.get("user").is_admin():
|
||||
req.context["admin_authorized"] = True
|
||||
return func(resource, req, resp, *args, **kwargs)
|
||||
logger.info("User '%s' not authorized to access administrative API", req.context.get("user").name)
|
||||
raise falcon.HTTPForbidden("Forbidden", "User not authorized to perform administrative operations")
|
||||
|
||||
Reference in New Issue
Block a user