| 1 |
# Authors: Rob Crittenden <[email protected]> |
| 2 |
# |
| 3 |
# Copyright (C) 2009 Red Hat |
| 4 |
# see file 'COPYING' for use and warranty information |
| 5 |
# |
| 6 |
# This program is free software; you can redistribute it and/or modify |
| 7 |
# it under the terms of the GNU General Public License as published by |
| 8 |
# the Free Software Foundation, either version 3 of the License, or |
| 9 |
# (at your option) any later version. |
| 10 |
# |
| 11 |
# This program is distributed in the hope that it will be useful, |
| 12 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 14 |
# GNU General Public License for more details. |
| 15 |
# |
| 16 |
# You should have received a copy of the GNU General Public License |
| 17 |
# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 18 |
# |
| 19 |
|
| 20 |
import collections |
| 21 |
import gzip |
| 22 |
import io |
| 23 |
import json |
| 24 |
import logging |
| 25 |
from urllib.parse import urlencode |
| 26 |
import xml.dom.minidom |
| 27 |
import zlib |
| 28 |
|
| 29 |
import six |
| 30 |
|
| 31 |
# pylint: disable=ipa-forbidden-import |
| 32 |
from ipalib import api, errors |
| 33 |
from ipalib.util import create_https_connection |
| 34 |
from ipalib.errors import NetworkError |
| 35 |
from ipalib.text import _ |
| 36 |
# pylint: enable=ipa-forbidden-import |
| 37 |
from ipapython import ipautil |
| 38 |
|
| 39 |
# Python 3 rename. The package is available in "six.moves.http_client", but |
| 40 |
# pylint cannot handle classes from that alias |
| 41 |
try: |
| 42 |
import httplib |
| 43 |
except ImportError: |
| 44 |
import http.client as httplib |
| 45 |
|
| 46 |
if six.PY3: |
| 47 |
unicode = str |
| 48 |
|
| 49 |
logger = logging.getLogger(__name__) |
| 50 |
|
| 51 |
Profile = collections.namedtuple('Profile', ['profile_id', 'description', 'store_issued']) |
| 52 |
|
| 53 |
INCLUDED_PROFILES = { |
| 54 |
Profile(u'caIPAserviceCert', u'Standard profile for network services', True), |
| 55 |
Profile(u'IECUserRoles', u'User profile that includes IECUserRoles extension from request', True), |
| 56 |
Profile(u'KDCs_PKINIT_Certs', |
| 57 |
u'Profile for PKINIT support by KDCs', |
| 58 |
False), |
| 59 |
Profile(u'acmeIPAServerCert', |
| 60 |
u'ACME IPA service certificate profile', |
| 61 |
False), |
| 62 |
} |
| 63 |
|
| 64 |
DEFAULT_PROFILE = u'caIPAserviceCert' |
| 65 |
KDC_PROFILE = u'KDCs_PKINIT_Certs' |
| 66 |
OCSP_PROFILE = 'caOCSPCert' |
| 67 |
SUBSYSTEM_PROFILE = 'caSubsystemCert' |
| 68 |
AUDIT_PROFILE = 'caSignedLogCert' |
| 69 |
CACERT_PROFILE = 'caCACert' |
| 70 |
CASERVER_PROFILE = 'caServerCert' |
| 71 |
KRA_AUDIT_PROFILE = 'caAuditSigningCert' |
| 72 |
KRA_STORAGE_PROFILE = 'caStorageCert' |
| 73 |
KRA_TRANSPORT_PROFILE = 'caTransportCert' |
| 74 |
|
| 75 |
|
| 76 |
if six.PY3: |
| 77 |
gzip_decompress = gzip.decompress |
| 78 |
else: |
| 79 |
# note: gzip.decompress available in Python >= 3.2 |
| 80 |
def gzip_decompress(data): |
| 81 |
with gzip.GzipFile(fileobj=io.BytesIO(data)) as f: |
| 82 |
return f.read() |
| 83 |
|
| 84 |
|
| 85 |
def error_from_xml(doc, message_template): |
| 86 |
try: |
| 87 |
item_node = doc.getElementsByTagName("Error") |
| 88 |
reason = item_node[0].childNodes[0].data |
| 89 |
return errors.RemoteRetrieveError(reason=reason) |
| 90 |
except Exception as e: |
| 91 |
return errors.RemoteRetrieveError(reason=message_template % e) |
| 92 |
|
| 93 |
|
| 94 |
def get_ca_certchain(ca_host=None): |
| 95 |
""" |
| 96 |
Retrieve the CA Certificate chain from the configured Dogtag server. |
| 97 |
""" |
| 98 |
if ca_host is None: |
| 99 |
ca_host = api.env.ca_host |
| 100 |
chain = None |
| 101 |
conn = httplib.HTTPConnection( |
| 102 |
ca_host, |
| 103 |
api.env.ca_install_port or 8080) |
| 104 |
conn.request("GET", "/ca/ee/ca/getCertChain") |
| 105 |
res = conn.getresponse() |
| 106 |
doc = None |
| 107 |
if res.status == 200: |
| 108 |
data = res.read() |
| 109 |
conn.close() |
| 110 |
try: |
| 111 |
doc = json.loads(data) |
| 112 |
chain = doc['Response']['ChainBase64'] |
| 113 |
except (json.JSONDecodeError, KeyError): |
| 114 |
logger.debug("Response is not valid JSON, try XML") |
| 115 |
doc = xml.dom.minidom.parseString(data) |
| 116 |
try: |
| 117 |
item_node = doc.getElementsByTagName("ChainBase64") |
| 118 |
chain = item_node[0].childNodes[0].data |
| 119 |
except IndexError: |
| 120 |
raise error_from_xml( |
| 121 |
doc, _("Retrieving CA cert chain failed: %s")) |
| 122 |
finally: |
| 123 |
if doc: |
| 124 |
doc.unlink() |
| 125 |
else: |
| 126 |
raise errors.RemoteRetrieveError( |
| 127 |
reason=_("request failed with HTTP status %d") % res.status) |
| 128 |
|
| 129 |
return chain |
| 130 |
|
| 131 |
|
| 132 |
def _parse_ca_status(body): |
| 133 |
try: |
| 134 |
doc = json.loads(body) |
| 135 |
return doc['Response']['Status'] |
| 136 |
except (json.JSONDecodeError, KeyError): |
| 137 |
logger.debug("Response is not valid JSON, try XML") |
| 138 |
doc = xml.dom.minidom.parseString(body) |
| 139 |
try: |
| 140 |
item_node = doc.getElementsByTagName("XMLResponse")[0] |
| 141 |
item_node = item_node.getElementsByTagName("Status")[0] |
| 142 |
return item_node.childNodes[0].data |
| 143 |
except IndexError: |
| 144 |
raise error_from_xml(doc, _("Retrieving CA status failed: %s")) |
| 145 |
|
| 146 |
|
| 147 |
def ca_status(ca_host=None): |
| 148 |
"""Return the status of the CA, and the httpd proxy in front of it |
| 149 |
|
| 150 |
The returned status can be: |
| 151 |
- running |
| 152 |
- starting |
| 153 |
- Service Temporarily Unavailable |
| 154 |
""" |
| 155 |
if ca_host is None: |
| 156 |
ca_host = api.env.ca_host |
| 157 |
status, _headers, body = http_request( |
| 158 |
ca_host, 8080, '/ca/admin/ca/getStatus', |
| 159 |
# timeout: CA sometimes forgot to answer, we have to try again |
| 160 |
timeout=api.env.http_timeout) |
| 161 |
if status == 503: |
| 162 |
# Service temporarily unavailable |
| 163 |
return status |
| 164 |
elif status != 200: |
| 165 |
raise errors.RemoteRetrieveError( |
| 166 |
reason=_("Retrieving CA status failed with status %d") % status) |
| 167 |
return _parse_ca_status(body) |
| 168 |
|
| 169 |
|
| 170 |
def acme_status(ca_host=None): |
| 171 |
"""Return the status of ACME |
| 172 |
|
| 173 |
Returns a boolean. |
| 174 |
|
| 175 |
If the proxy is not working or the CA is not running then this could |
| 176 |
return a false negative. |
| 177 |
""" |
| 178 |
if ca_host is None: |
| 179 |
ca_host = api.env.ca_host |
| 180 |
status, _headers, _body = https_request( |
| 181 |
ca_host, 443, |
| 182 |
url='/acme/directory', |
| 183 |
cafile=api.env.tls_ca_cert, |
| 184 |
client_certfile=None, |
| 185 |
client_keyfile=None, |
| 186 |
method='GET', |
| 187 |
timeout=api.env.http_timeout) |
| 188 |
if status == 200: |
| 189 |
return True |
| 190 |
elif status == 503: |
| 191 |
# This is what it should return when disabled |
| 192 |
return False |
| 193 |
else: |
| 194 |
# Unexpected status code, log and return False |
| 195 |
logger.error('ACME status request returned %d', status) |
| 196 |
return False |
| 197 |
|
| 198 |
|
| 199 |
def https_request( |
| 200 |
host, port, url, cafile, client_certfile, client_keyfile, |
| 201 |
method='POST', headers=None, body=None, **kw): |
| 202 |
""" |
| 203 |
:param method: HTTP request method (defalut: 'POST') |
| 204 |
:param url: The path (not complete URL!) to post to. |
| 205 |
:param body: The request body (encodes kw if None) |
| 206 |
:param kw: Keyword arguments to encode into POST body. |
| 207 |
:return: (http_status, http_headers, http_body) |
| 208 |
as (integer, dict, str) |
| 209 |
|
| 210 |
Perform a client authenticated HTTPS request |
| 211 |
""" |
| 212 |
|
| 213 |
def connection_factory(host, port): |
| 214 |
return create_https_connection( |
| 215 |
host, port, |
| 216 |
cafile=cafile, |
| 217 |
client_certfile=client_certfile, |
| 218 |
client_keyfile=client_keyfile, |
| 219 |
tls_version_min=api.env.tls_version_min, |
| 220 |
tls_version_max=api.env.tls_version_max) |
| 221 |
|
| 222 |
if body is None: |
| 223 |
body = urlencode(kw) |
| 224 |
return _httplib_request( |
| 225 |
'https', host, port, url, connection_factory, body, |
| 226 |
method=method, headers=headers) |
| 227 |
|
| 228 |
|
| 229 |
def http_request(host, port, url, timeout=None, **kw): |
| 230 |
""" |
| 231 |
:param url: The path (not complete URL!) to post to. |
| 232 |
:param timeout: Timeout in seconds for waiting for reply. |
| 233 |
:param kw: Keyword arguments to encode into POST body. |
| 234 |
:return: (http_status, http_headers, http_body) |
| 235 |
as (integer, dict, str) |
| 236 |
|
| 237 |
Perform an HTTP request. |
| 238 |
""" |
| 239 |
body = urlencode(kw) |
| 240 |
if timeout is None: |
| 241 |
conn_opt = {} |
| 242 |
else: |
| 243 |
conn_opt = {"timeout": timeout} |
| 244 |
|
| 245 |
return _httplib_request( |
| 246 |
'http', host, port, url, httplib.HTTPConnection, body, |
| 247 |
connection_options=conn_opt) |
| 248 |
|
| 249 |
|
| 250 |
def _httplib_request( |
| 251 |
protocol, host, port, path, connection_factory, request_body, |
| 252 |
method='POST', headers=None, connection_options=None): |
| 253 |
""" |
| 254 |
:param request_body: Request body |
| 255 |
:param connection_factory: Connection class to use. Will be called |
| 256 |
with the host and port arguments. |
| 257 |
:param method: HTTP request method (default: 'POST') |
| 258 |
:param connection_options: a dictionary that will be passed to |
| 259 |
connection_factory as keyword arguments. |
| 260 |
|
| 261 |
Perform a HTTP(s) request. |
| 262 |
""" |
| 263 |
if connection_options is None: |
| 264 |
connection_options = {} |
| 265 |
|
| 266 |
uri = u'%s://%s%s' % (protocol, ipautil.format_netloc(host, port), path) |
| 267 |
logger.debug('request %s %s', method, uri) |
| 268 |
logger.debug('request body %r', request_body) |
| 269 |
|
| 270 |
headers = headers or {} |
| 271 |
if ( |
| 272 |
method == 'POST' |
| 273 |
and 'content-type' not in (str(k).lower() for k in headers) |
| 274 |
): |
| 275 |
headers['content-type'] = 'application/x-www-form-urlencoded' |
| 276 |
|
| 277 |
try: |
| 278 |
conn = connection_factory(host, port, **connection_options) |
| 279 |
conn.request(method, path, body=request_body, headers=headers) |
| 280 |
res = conn.getresponse() |
| 281 |
|
| 282 |
http_status = res.status |
| 283 |
http_headers = res.msg |
| 284 |
http_body = res.read() |
| 285 |
conn.close() |
| 286 |
except Exception as e: |
| 287 |
logger.debug("httplib request failed:", exc_info=True) |
| 288 |
raise NetworkError(uri=uri, error=str(e)) |
| 289 |
|
| 290 |
encoding = res.getheader('Content-Encoding') |
| 291 |
if encoding == 'gzip': |
| 292 |
http_body = gzip_decompress(http_body) |
| 293 |
elif encoding == 'deflate': |
| 294 |
http_body = zlib.decompress(http_body) |
| 295 |
|
| 296 |
logger.debug('response status %d', http_status) |
| 297 |
logger.debug('response headers %s', http_headers) |
| 298 |
logger.debug('response body (decoded): %r', http_body) |
| 299 |
|
| 300 |
return http_status, http_headers, http_body |