Files
freeipa/ipapython/dogtag.py
T

293 lines
9.3 KiB
Python
Raw Normal View History

2009-04-22 14:35:27 -04:00
# Authors: Rob Crittenden <rcritten@redhat.com>
#
# Copyright (C) 2009 Red Hat
# see file 'COPYING' for use and warranty information
#
2010-12-09 13:59:11 +01:00
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
2009-04-22 14:35:27 -04:00
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
2010-12-09 13:59:11 +01:00
# along with this program. If not, see <http://www.gnu.org/licenses/>.
2009-04-22 14:35:27 -04:00
#
2015-08-13 02:32:54 -04:00
import collections
2018-05-29 18:52:05 +10:00
import gzip
2018-05-30 10:56:46 +02:00
import io
2021-08-05 12:00:15 +01:00
import json
2017-05-24 14:35:07 +00:00
import logging
2018-09-27 07:47:07 +02:00
from urllib.parse import urlencode
2009-04-22 14:35:27 -04:00
import xml.dom.minidom
2018-05-29 18:52:05 +10:00
import zlib
2012-08-23 12:38:45 -04:00
2015-09-11 13:43:28 +02:00
import six
2012-07-04 08:52:47 -04:00
# pylint: disable=ipa-forbidden-import
2012-07-04 08:52:47 -04:00
from ipalib import api, errors
2016-12-20 10:23:47 +01:00
from ipalib.util import create_https_connection
2014-03-18 11:23:30 -04:00
from ipalib.errors import NetworkError
2012-07-04 08:52:47 -04:00
from ipalib.text import _
# pylint: enable=ipa-forbidden-import
2016-12-20 10:23:47 +01:00
from ipapython import ipautil
2012-08-23 12:38:45 -04:00
# Python 3 rename. The package is available in "six.moves.http_client", but
# pylint cannot handle classes from that alias
try:
import httplib
except ImportError:
2016-08-24 13:37:30 +02:00
# pylint: disable=import-error
import http.client as httplib
2015-09-11 13:43:28 +02:00
if six.PY3:
unicode = str
2017-05-24 14:35:07 +00:00
logger = logging.getLogger(__name__)
2015-08-13 02:32:54 -04:00
Profile = collections.namedtuple('Profile', ['profile_id', 'description', 'store_issued'])
INCLUDED_PROFILES = {
2015-08-13 02:32:54 -04:00
Profile(u'caIPAserviceCert', u'Standard profile for network services', True),
Profile(u'IECUserRoles', u'User profile that includes IECUserRoles extension from request', True),
Profile(u'KDCs_PKINIT_Certs',
u'Profile for PKINIT support by KDCs',
False),
Profile(u'acmeIPAServerCert',
u'ACME IPA service certificate profile',
2020-03-25 16:41:56 +11:00
False),
}
DEFAULT_PROFILE = u'caIPAserviceCert'
KDC_PROFILE = u'KDCs_PKINIT_Certs'
2009-04-22 14:35:27 -04:00
2018-05-30 10:56:46 +02:00
if six.PY3:
gzip_decompress = gzip.decompress # pylint: disable=no-member
else:
# note: gzip.decompress available in Python >= 3.2
def gzip_decompress(data):
with gzip.GzipFile(fileobj=io.BytesIO(data)) as f:
return f.read()
def error_from_xml(doc, message_template):
try:
item_node = doc.getElementsByTagName("Error")
reason = item_node[0].childNodes[0].data
return errors.RemoteRetrieveError(reason=reason)
2015-07-30 16:49:29 +02:00
except Exception as e:
return errors.RemoteRetrieveError(reason=message_template % e)
2015-11-09 18:28:47 +01:00
def get_ca_certchain(ca_host=None):
2009-04-22 14:35:27 -04:00
"""
Retrieve the CA Certificate chain from the configured Dogtag server.
"""
if ca_host is None:
ca_host = api.env.ca_host
2009-04-22 14:35:27 -04:00
chain = None
2014-03-18 11:23:30 -04:00
conn = httplib.HTTPConnection(
ca_host,
2015-11-09 18:28:47 +01:00
api.env.ca_install_port or 8080)
2009-04-22 14:35:27 -04:00
conn.request("GET", "/ca/ee/ca/getCertChain")
res = conn.getresponse()
doc = None
2009-04-22 14:35:27 -04:00
if res.status == 200:
data = res.read()
conn.close()
try:
2021-08-05 12:00:15 +01:00
doc = json.loads(data)
chain = doc['Response']['ChainBase64']
except (json.JSONDecodeError, KeyError):
logger.debug("Response is not valid JSON, try XML")
doc = xml.dom.minidom.parseString(data)
try:
item_node = doc.getElementsByTagName("ChainBase64")
chain = item_node[0].childNodes[0].data
except IndexError:
raise error_from_xml(
doc, _("Retrieving CA cert chain failed: %s"))
2021-08-05 12:00:15 +01:00
finally:
if doc:
doc.unlink()
else:
2012-07-04 08:52:47 -04:00
raise errors.RemoteRetrieveError(
reason=_("request failed with HTTP status %d") % res.status)
2009-04-22 14:35:27 -04:00
return chain
2014-11-18 19:49:15 +01:00
def _parse_ca_status(body):
try:
2021-08-05 12:00:15 +01:00
doc = json.loads(body)
return doc['Response']['Status']
except (json.JSONDecodeError, KeyError):
logger.debug("Response is not valid JSON, try XML")
doc = xml.dom.minidom.parseString(body)
try:
item_node = doc.getElementsByTagName("XMLResponse")[0]
item_node = item_node.getElementsByTagName("Status")[0]
return item_node.childNodes[0].data
except IndexError:
raise error_from_xml(doc, _("Retrieving CA status failed: %s"))
2014-11-18 19:49:15 +01:00
2016-01-20 18:35:15 +11:00
def ca_status(ca_host=None):
"""Return the status of the CA, and the httpd proxy in front of it
The returned status can be:
- running
- starting
- Service Temporarily Unavailable
"""
if ca_host is None:
ca_host = api.env.ca_host
2016-09-26 14:08:17 +02:00
status, _headers, body = http_request(
2017-05-02 19:52:13 +02:00
ca_host, 8080, '/ca/admin/ca/getStatus',
# timeout: CA sometimes forgot to answer, we have to try again
timeout=api.env.http_timeout)
if status == 503:
# Service temporarily unavailable
return status
elif status != 200:
raise errors.RemoteRetrieveError(
reason=_("Retrieving CA status failed with status %d") % status)
2014-11-18 19:49:15 +01:00
return _parse_ca_status(body)
2020-10-14 13:20:16 -04:00
def acme_status(ca_host=None):
"""Return the status of ACME
Returns a boolean.
If the proxy is not working or the CA is not running then this could
return a false negative.
"""
if ca_host is None:
ca_host = api.env.ca_host
status, _headers, _body = https_request(
ca_host, 443,
url='/acme/directory',
cafile=api.env.tls_ca_cert,
client_certfile=None,
client_keyfile=None,
method='GET',
timeout=api.env.http_timeout)
if status == 200:
return True
elif status == 503:
# This is what it should return when disabled
return False
else:
# Unexpected status code, log and return False
logger.error('ACME status request returned %d', status)
return False
2017-01-13 09:08:42 +01:00
def https_request(
host, port, url, cafile, client_certfile, client_keyfile,
method='POST', headers=None, body=None, **kw):
"""
2015-04-30 04:55:29 -04:00
:param method: HTTP request method (defalut: 'POST')
:param url: The path (not complete URL!) to post to.
2015-04-30 04:55:29 -04:00
:param body: The request body (encodes kw if None)
:param kw: Keyword arguments to encode into POST body.
:return: (http_status, http_headers, http_body)
as (integer, dict, str)
Perform a client authenticated HTTPS request
"""
def connection_factory(host, port):
2016-12-20 10:23:47 +01:00
return create_https_connection(
host, port,
cafile=cafile,
client_certfile=client_certfile,
2017-01-13 09:08:42 +01:00
client_keyfile=client_keyfile,
2016-12-20 10:23:47 +01:00
tls_version_min=api.env.tls_version_min,
tls_version_max=api.env.tls_version_max)
2015-04-30 04:55:29 -04:00
if body is None:
body = urlencode(kw)
return _httplib_request(
2015-04-30 04:55:29 -04:00
'https', host, port, url, connection_factory, body,
method=method, headers=headers)
2017-05-02 19:24:16 +02:00
def http_request(host, port, url, timeout=None, **kw):
"""
:param url: The path (not complete URL!) to post to.
2017-05-02 19:24:16 +02:00
:param timeout: Timeout in seconds for waiting for reply.
:param kw: Keyword arguments to encode into POST body.
:return: (http_status, http_headers, http_body)
as (integer, dict, str)
Perform an HTTP request.
"""
body = urlencode(kw)
2017-05-02 19:24:16 +02:00
if timeout is None:
conn_opt = {}
else:
conn_opt = {"timeout": timeout}
return _httplib_request(
2017-05-02 19:24:16 +02:00
'http', host, port, url, httplib.HTTPConnection, body,
connection_options=conn_opt)
def _httplib_request(
2015-04-30 04:55:29 -04:00
protocol, host, port, path, connection_factory, request_body,
2017-05-02 19:24:16 +02:00
method='POST', headers=None, connection_options=None):
"""
:param request_body: Request body
:param connection_factory: Connection class to use. Will be called
with the host and port arguments.
2015-04-30 04:55:29 -04:00
:param method: HTTP request method (default: 'POST')
2017-05-02 19:24:16 +02:00
:param connection_options: a dictionary that will be passed to
connection_factory as keyword arguments.
Perform a HTTP(s) request.
"""
2017-05-02 19:24:16 +02:00
if connection_options is None:
connection_options = {}
uri = u'%s://%s%s' % (protocol, ipautil.format_netloc(host, port), path)
2017-05-24 14:35:07 +00:00
logger.debug('request %s %s', method, uri)
logger.debug('request body %r', request_body)
2015-04-30 04:55:29 -04:00
headers = headers or {}
if (
method == 'POST'
2015-08-11 13:51:14 +02:00
and 'content-type' not in (str(k).lower() for k in headers)
2015-04-30 04:55:29 -04:00
):
headers['content-type'] = 'application/x-www-form-urlencoded'
try:
2017-05-02 19:24:16 +02:00
conn = connection_factory(host, port, **connection_options)
conn.request(method, path, body=request_body, headers=headers)
res = conn.getresponse()
http_status = res.status
http_headers = res.msg
http_body = res.read()
conn.close()
2015-07-30 16:49:29 +02:00
except Exception as e:
2017-05-24 14:35:07 +00:00
logger.debug("httplib request failed:", exc_info=True)
raise NetworkError(uri=uri, error=str(e))
2018-05-29 18:52:05 +10:00
encoding = res.getheader('Content-Encoding')
if encoding == 'gzip':
2018-05-30 10:56:46 +02:00
http_body = gzip_decompress(http_body)
2018-05-29 18:52:05 +10:00
elif encoding == 'deflate':
http_body = zlib.decompress(http_body)
2017-05-24 14:35:07 +00:00
logger.debug('response status %d', http_status)
logger.debug('response headers %s', http_headers)
2018-05-29 18:52:05 +10:00
logger.debug('response body (decoded): %r', http_body)
return http_status, http_headers, http_body