summaryrefslogtreecommitdiffstats
path: root/install/certmonger/dogtag-ipa-ca-renew-agent-submit
blob: 6da7f6dbf01fdbaeac733f70d8c6e218a3302622 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
#!/usr/bin/python2 -E
#
# Authors:
#   Jan Cholasta <jcholast@redhat.com>
#
# Copyright (C) 2013  Red Hat
# see file 'COPYING' for use and warranty information
#
# 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.
#
# 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
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os
# Prevent garbage from readline on standard output
# (see https://fedorahosted.org/freeipa/ticket/4064)
if not os.isatty(1):
    os.environ['TERM'] = 'dumb'
import sys
import syslog
import traceback
import tempfile
import shutil
import base64
import contextlib

from ipapython import ipautil
from ipapython.dn import DN
from ipalib import api, errors, pkcs10, x509
from ipaserver.plugins.ldap2 import ldap2

# This is a certmonger CA helper script for IPA CA subsystem cert renewal. See
# https://git.fedorahosted.org/cgit/certmonger.git/tree/doc/submit.txt for more
# info on certmonger CA helper scripts.

# Return codes. Names of the constants are taken from
# https://git.fedorahosted.org/cgit/certmonger.git/tree/src/submit-e.h
ISSUED = 0
WAIT = 1
REJECTED = 2
UNREACHABLE = 3
UNCONFIGURED = 4
WAIT_WITH_DELAY = 5
OPERATION_NOT_SUPPORTED_BY_HELPER = 6

@contextlib.contextmanager
def ldap_connect():
    conn = None
    tmpdir = tempfile.mkdtemp(prefix="tmp-")
    try:
        principal = str('host/%s@%s' % (api.env.host, api.env.realm))
        ccache = ipautil.kinit_hostprincipal('/etc/krb5.keytab', tmpdir,
                                             principal)

        conn = ldap2(shared_instance=False, ldap_uri=api.env.ldap_uri)
        conn.connect(ccache=ccache)

        yield conn
    finally:
        if conn is not None and conn.isconnected():
            conn.disconnect()
        shutil.rmtree(tmpdir)

def request_cert():
    """
    Request certificate from IPA CA.
    """
    syslog.syslog(syslog.LOG_NOTICE,
                  "Forwarding request to dogtag-ipa-renew-agent")

    path = '/usr/libexec/certmonger/dogtag-ipa-renew-agent-submit'
    args = [path] + sys.argv[1:]
    stdout, stderr, rc = ipautil.run(args, raiseonerr=False, env=os.environ)
    sys.stderr.write(stderr)
    sys.stderr.flush()

    syslog.syslog(syslog.LOG_NOTICE, "dogtag-ipa-renew-agent returned %d" % rc)

    if stdout.endswith('\n'):
        stdout = stdout[:-1]

    if rc == WAIT_WITH_DELAY:
        delay, sep, cookie = stdout.partition('\n')
        return (rc, delay, cookie)
    else:
        return (rc, stdout)

def store_cert():
    """
    Store certificate in LDAP.
    """
    operation = os.environ.get('CERTMONGER_OPERATION')
    if operation == 'SUBMIT':
        attempts = 0
    elif operation == 'POLL':
        cookie = os.environ.get('CERTMONGER_CA_COOKIE')
        if not cookie:
            return (UNCONFIGURED, "Cookie not provided")

        try:
            attempts = int(cookie)
        except ValueError:
            return (UNCONFIGURED, "Invalid cookie")
    else:
        return (OPERATION_NOT_SUPPORTED_BY_HELPER,)

    csr = os.environ.get('CERTMONGER_CSR')
    if not csr:
        return (UNCONFIGURED, "Certificate request not provided")

    nickname = pkcs10.get_friendlyname(csr)
    if not nickname:
        return (REJECTED, "No friendly name in the certificate request")

    cert = os.environ.get('CERTMONGER_CERTIFICATE')
    if not cert:
        return (REJECTED, "New certificate requests not supported")

    dercert = x509.normalize_certificate(cert)

    dn = DN(('cn', nickname), ('cn', 'ca_renewal'),
            ('cn', 'ipa'), ('cn', 'etc'), api.env.basedn)
    try:
        with ldap_connect() as conn:
            try:
                entry = conn.get_entry(dn, ['usercertificate'])
                entry['usercertificate'] = [dercert]
                conn.update_entry(entry)
            except errors.NotFound:
                entry = conn.make_entry(
                    dn,
                    objectclass=['top', 'pkiuser', 'nscontainer'],
                    cn=[nickname],
                    usercertificate=[dercert])
                conn.add_entry(entry)
            except errors.EmptyModlist:
                pass
    except Exception, e:
        attempts += 1
        if attempts < 10:
            syslog.syslog(
                syslog.LOG_ERR,
                "Updating renewal certificate failed: %s. Sleeping 30s" % e)
            return (WAIT_WITH_DELAY, 30, attempts)
        else:
            syslog.syslog(
                syslog.LOG_ERR,
                "Giving up. To retry storing the certificate, resubmit the "
                "request with profile \"ipaStorage\"")

    return (ISSUED, cert)

def request_and_store_cert():
    """
    Request certificate from IPA CA and store it in LDAP.
    """
    operation = os.environ.get('CERTMONGER_OPERATION')
    if operation == 'SUBMIT':
        state = 'request'
        cookie = None
    elif operation == 'POLL':
        cookie = os.environ.get('CERTMONGER_CA_COOKIE')
        if not cookie:
            return (UNCONFIGURED, "Cookie not provided")

        state, sep, cookie = cookie.partition(':')
        if state not in ('request', 'store'):
            return (UNCONFIGURED, "Invalid cookie")
    else:
        return (OPERATION_NOT_SUPPORTED_BY_HELPER,)

    if state == 'request':
        if cookie is None:
            os.environ['CERTMONGER_OPERATION'] = 'SUBMIT'
        else:
            os.environ['CERTMONGER_CA_COOKIE'] = cookie

        result = request_cert()
        if result[0] == WAIT:
            return (result[0], 'request:%s' % result[1])
        elif result[0] == WAIT_WITH_DELAY:
            return (result[0], result[1], 'request:%s' % result[2])
        elif result[0] != ISSUED:
            return result
        else:
            cert = result[1]
            cookie = None
    else:
        cert, sep, cookie = cookie.partition(':')

    if cookie is None:
        os.environ['CERTMONGER_OPERATION'] = 'SUBMIT'
    else:
        os.environ['CERTMONGER_CA_COOKIE'] = cookie
    os.environ['CERTMONGER_CERTIFICATE'] = cert

    result = store_cert()
    if result[0] == WAIT:
        return (result[0], 'store:%s:%s' % (cert, result[1]))
    elif result[0] == WAIT_WITH_DELAY:
        return (result[0], result[1], 'store:%s:%s' % (cert, result[2]))
    else:
        return result

def retrieve_cert():
    """
    Retrieve new certificate from LDAP.
    """
    csr = os.environ.get('CERTMONGER_CSR')
    if not csr:
        return (UNCONFIGURED, "Certificate request not provided")

    nickname = pkcs10.get_friendlyname(csr)
    if not nickname:
        return (REJECTED, "No friendly name in the certificate request")

    syslog.syslog(syslog.LOG_NOTICE, "Updating certificate for %s" % nickname)

    with ldap_connect() as conn:
        try:
            entry = conn.get_entry(
                DN(('cn', nickname), ('cn', 'ca_renewal'),
                   ('cn', 'ipa'), ('cn', 'etc'), api.env.basedn),
                ['usercertificate'])
        except errors.NotFound:
            syslog.syslog(
                syslog.LOG_INFO,
                "Updated certificate for %s not available" % nickname)
            # No cert available yet, tell certmonger to wait another 8 hours
            return (WAIT_WITH_DELAY, 8 * 60 * 60)

        cert = entry.single_value['usercertificate']
        cert = base64.b64encode(cert)
        cert = x509.make_pem(cert)

    return (ISSUED, cert)

def main():
    handlers = {
        'ipaStorage':       store_cert,
        'ipaRetrieval':     retrieve_cert,
    }

    api.bootstrap(context='renew')
    api.finalize()

    profile = os.environ.get('CERTMONGER_CA_PROFILE')
    if profile:
        handler = handlers.get(profile, request_and_store_cert)
    else:
        handler = request_and_store_cert

    res = handler()
    for item in res[1:]:
        print item
    return res[0]

try:
    sys.exit(main())
except Exception, e:
    syslog.syslog(syslog.LOG_ERR, traceback.format_exc())
    print "Internal error"
    sys.exit(UNREACHABLE)