]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/autoca.c
0fd2034122095b47db60506dab6046ae5176c6ff
[openldap] / servers / slapd / overlays / autoca.c
1 /* autoca.c - Automatic Certificate Authority */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 2009-2017 The OpenLDAP Foundation.
6  * Copyright 2009-2017 by Howard Chu.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted only as authorized by the OpenLDAP
11  * Public License.
12  *
13  * A copy of this license is available in the file LICENSE in the
14  * top-level directory of the distribution or, alternatively, at
15  * <http://www.OpenLDAP.org/license.html>.
16  */
17 /* ACKNOWLEDGEMENTS:
18  * This work was initially developed by Howard Chu for inclusion in
19  * OpenLDAP Software.
20  */
21
22 #include "portable.h"
23
24 #define SLAPD_OVER_AUTOCA       SLAPD_MOD_DYNAMIC
25
26 #ifdef SLAPD_OVER_AUTOCA
27
28 #include <stdio.h>
29
30 #include <ac/string.h>
31 #include <ac/socket.h>
32
33 #include "lutil.h"
34 #include "slap.h"
35 #include "config.h"
36
37 #include <openssl/x509v3.h>
38 #include <openssl/evp.h>
39
40 /* This overlay implements a certificate authority that can generate
41  * certificates automatically for any entry in the directory.
42  * On startup it generates a self-signed CA cert for the directory's
43  * suffix entry and uses this to sign all other certs that it generates.
44  * User and server certs are generated on demand, using a Search request.
45  */
46
47 #define LBER_TAG_OID        ((ber_tag_t) 0x06UL)
48 #define LBER_TAG_UTF8       ((ber_tag_t) 0x0cUL)
49
50 #define KEYBITS 2048
51 #define MIN_KEYBITS     512
52
53 #define ACA_SCHEMA_ROOT "1.3.6.1.4.1.4203.666.11.11"
54
55 #define ACA_SCHEMA_AT ACA_SCHEMA_ROOT ".1"
56 #define ACA_SCHEMA_OC ACA_SCHEMA_ROOT ".2"
57
58 static AttributeDescription *ad_caCert, *ad_caPkey, *ad_usrCert, *ad_usrPkey;
59 static AttributeDescription *ad_mail, *ad_ipaddr;
60 static ObjectClass *oc_caObj, *oc_usrObj;
61
62 static char *aca_attrs[] = {
63         "( " ACA_SCHEMA_AT ".1 NAME 'cAPrivateKey' "
64                 "DESC 'X.509 CA private key, use ;binary' "
65                 "SUP x509PrivateKey )",
66         "( " ACA_SCHEMA_AT ".2 NAME 'userPrivateKey' "
67                 "DESC 'X.509 user private key, use ;binary' "
68                 "SUP x509PrivateKey )",
69         NULL
70 };
71
72 static struct {
73         char *at;
74         AttributeDescription **ad;
75 } aca_attr2[] = {
76         { "cACertificate;binary", &ad_caCert },
77         { "cAPrivateKey;binary", &ad_caPkey },
78         { "userCertificate;binary", &ad_usrCert },
79         { "userPrivateKey;binary", &ad_usrPkey },
80         { "mail", &ad_mail },
81         { NULL }
82 };
83
84 static struct {
85         char *ot;
86         ObjectClass **oc;
87 } aca_ocs[] = {
88         { "( " ACA_SCHEMA_OC ".1 NAME 'autoCA' "
89                 "DESC 'Automated PKI certificate authority' "
90                 "SUP pkiCA AUXILIARY "
91                 "MAY cAPrivateKey )", &oc_caObj },
92         { "( " ACA_SCHEMA_OC ".2 NAME 'autoCAuser' "
93                 "DESC 'Automated PKI CA user' "
94                 "SUP pkiUser AUXILIARY "
95                 "MAY userPrivateKey )", &oc_usrObj },
96         { NULL }
97 };
98
99 typedef struct autoca_info {
100         X509 *ai_cert;
101         EVP_PKEY *ai_pkey;
102         ObjectClass *ai_usrclass;
103         ObjectClass *ai_srvclass;
104         int ai_usrkeybits;
105         int ai_srvkeybits;
106         int ai_cakeybits;
107         int ai_usrdays;
108         int ai_srvdays;
109         int ai_cadays;
110 } autoca_info;
111
112 /* Rewrite an LDAP DN in DER form
113  * Input must be valid DN, therefore no error checking is done here.
114  */
115 static int autoca_dnbv2der( Operation *op, struct berval *bv, struct berval *der )
116 {
117         BerElementBuffer berbuf;
118         BerElement *ber = (BerElement *)&berbuf;
119         LDAPDN dn;
120         LDAPRDN rdn;
121         LDAPAVA *ava;
122         AttributeDescription *ad;
123         int irdn, iava;
124
125         ldap_bv2dn_x( bv, &dn, LDAP_DN_FORMAT_LDAP, op->o_tmpmemctx );
126
127         ber_init2( ber, NULL, LBER_USE_DER );
128         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
129
130         /* count RDNs, we need them in reverse order */
131         for (irdn = 0; dn[irdn]; irdn++);
132         irdn--;
133
134         /* DN is a SEQuence of RDNs */
135         ber_start_seq( ber, LBER_SEQUENCE );
136         for (; irdn >=0; irdn--)
137         {
138                 /* RDN is a SET of AVAs */
139                 ber_start_set( ber, LBER_SET );
140                 rdn = dn[irdn];
141                 for (iava = 0; rdn[iava]; iava++)
142                 {
143                         const char *text;
144                         char oid[1024];
145                         struct berval bvo = { sizeof(oid), oid };
146                         struct berval bva;
147
148                         /* AVA is a SEQuence of attr and value */
149                         ber_start_seq( ber, LBER_SEQUENCE );
150                         ava = rdn[iava];
151                         ad = NULL;
152                         slap_bv2ad( &ava->la_attr, &ad, &text );
153                         ber_str2bv( ad->ad_type->sat_oid, 0, 0, &bva );
154                         ber_encode_oid( &bva, &bvo );
155                         ber_put_berval( ber, &bvo, LBER_TAG_OID );
156                         ber_put_berval( ber, &ava->la_value, LBER_TAG_UTF8 );
157                         ber_put_seq( ber );
158                 }
159                 ber_put_set( ber );
160         }
161         ber_put_seq( ber );
162         ber_flatten2( ber, der, 0 );
163         ldap_dnfree_x( dn, op->o_tmpmemctx );
164         return 0;
165 }
166
167 static int autoca_genpkey(int bits, EVP_PKEY **pkey)
168 {
169         EVP_PKEY_CTX *kctx;
170         int rc;
171
172         kctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, NULL);
173         if (kctx == NULL)
174                 return -1;
175         if (EVP_PKEY_keygen_init(kctx) <= 0)
176         {
177                 EVP_PKEY_CTX_free(kctx);
178                 return -1;
179         }
180         if (EVP_PKEY_CTX_set_rsa_keygen_bits(kctx, bits) <= 0)
181         {
182                 EVP_PKEY_CTX_free(kctx);
183                 return -1;
184         }
185         rc = EVP_PKEY_keygen(kctx, pkey);
186         EVP_PKEY_CTX_free(kctx);
187         return rc;
188 }
189
190 static int autoca_signcert(X509 *cert, EVP_PKEY *pkey)
191 {
192         EVP_MD_CTX *ctx = EVP_MD_CTX_create();
193         EVP_PKEY_CTX *pkctx = NULL;
194         int rc = -1;
195
196         if ( ctx == NULL )
197                 return -1;
198         if (EVP_DigestSignInit(ctx, &pkctx, NULL, NULL, pkey))
199         {
200                 rc = X509_sign_ctx(cert, ctx);
201         }
202         EVP_MD_CTX_destroy(ctx);
203         return rc;
204 }
205
206 #define SERIAL_BITS     64      /* should be less than 160 */
207
208 typedef struct myext {
209         char *name;
210         char *value;
211 } myext;
212
213 static myext CAexts[] = {
214         { "subjectKeyIdentifier", "hash" },
215         { "authorityKeyIdentifier", "keyid:always,issuer" },
216         { "basicConstraints", "critical,CA:true" },
217         { "keyUsage", "digitalSignature,cRLSign,keyCertSign" },
218         { "nsComment", "OpenLDAP automatic certificate" },
219         { NULL }
220 };
221
222 static myext usrExts[] = {
223         { "subjectKeyIdentifier", "hash" },
224         { "authorityKeyIdentifier", "keyid:always,issuer" },
225         { "basicConstraints", "CA:false" },
226         { "keyUsage", "digitalSignature,nonRepudiation,keyEncipherment" },
227         { "extendedKeyUsage", "clientAuth,emailProtection,codeSigning" },
228         { "nsComment", "OpenLDAP automatic certificate" },
229         { NULL }
230 };
231
232 static myext srvExts[] = {
233         { "subjectKeyIdentifier", "hash" },
234         { "authorityKeyIdentifier", "keyid:always,issuer" },
235         { "basicConstraints", "CA:false" },
236         { "keyUsage", "digitalSignature,keyEncipherment" },
237         { "extendedKeyUsage", "serverAuth,clientAuth" },
238         { "nsComment", "OpenLDAP automatic certificate" },
239         { NULL }
240 };
241
242 typedef struct genargs {
243         X509 *issuer_cert;
244         EVP_PKEY *issuer_pkey;
245         struct berval *subjectDN;
246         myext *cert_exts;
247         myext *more_exts;
248         X509 *newcert;
249         EVP_PKEY *newpkey;
250         struct berval dercert;
251         struct berval derpkey;
252         int keybits;
253         int days;
254 } genargs;
255
256 static int autoca_gencert( Operation *op, genargs *args )
257 {
258         X509_NAME *subj_name, *issuer_name;
259         X509 *subj_cert;
260         struct berval derdn;
261         const unsigned char *p;
262         EVP_PKEY *evpk = NULL;
263         int rc;
264         unsigned char *pp;
265
266         if ((subj_cert = X509_new()) == NULL)
267                 return -1;
268
269         autoca_dnbv2der( op, args->subjectDN, &derdn );
270         p = (const unsigned char *)derdn.bv_val;
271         subj_name = d2i_X509_NAME( NULL, &p, derdn.bv_len );
272         op->o_tmpfree( derdn.bv_val, op->o_tmpmemctx );
273         if ( subj_name == NULL )
274         {
275 fail1:
276                 X509_free( subj_cert );
277                 return -1;
278         }
279
280         rc = autoca_genpkey( args->keybits, &evpk );
281         if ( rc <= 0 )
282         {
283 fail2:
284                 if ( subj_name ) X509_NAME_free( subj_name );
285                 goto fail1;
286         }
287         args->derpkey.bv_len = i2d_PrivateKey( evpk, NULL );
288         args->derpkey.bv_val = op->o_tmpalloc( args->derpkey.bv_len, op->o_tmpmemctx );
289         pp = args->derpkey.bv_val;
290         i2d_PrivateKey( evpk, &pp );
291         args->newpkey = evpk;
292
293         /* set random serial */
294         {
295                 BIGNUM *bn = BN_new();
296                 if ( bn == NULL )
297                 {
298 fail3:
299                         EVP_PKEY_free( evpk );
300                         goto fail2;
301                 }
302                 if (!BN_pseudo_rand(bn, SERIAL_BITS, 0, 0))
303                 {
304                         BN_free( bn );
305                         goto fail3;
306                 }
307                 if (!BN_to_ASN1_INTEGER(bn, X509_get_serialNumber(subj_cert)))
308                 {
309                         BN_free( bn );
310                         goto fail3;
311                 }
312                 BN_free(bn);
313         }
314         if (args->issuer_cert) {
315                 issuer_name = X509_get_subject_name(args->issuer_cert);
316         } else {
317                 issuer_name = subj_name;
318                 args->issuer_cert = subj_cert;
319                 args->issuer_pkey = evpk;
320         }
321         if (!X509_set_version(subj_cert, 2) ||  /* set version to V3 */
322                 !X509_set_issuer_name(subj_cert, issuer_name) ||
323                 !X509_set_subject_name(subj_cert, subj_name) ||
324                 !X509_gmtime_adj(X509_get_notBefore(subj_cert), 0) ||
325                 !X509_time_adj_ex(X509_get_notAfter(subj_cert), args->days, 0, NULL) ||
326                 !X509_set_pubkey(subj_cert, evpk))
327         {
328                 goto fail3;
329         }
330         X509_NAME_free(subj_name);
331         subj_name = NULL;
332
333         /* set cert extensions */
334         {
335                 X509V3_CTX ctx;
336                 X509_EXTENSION *ext;
337                 int i;
338
339                 X509V3_set_ctx(&ctx, args->issuer_cert, subj_cert, NULL, NULL, 0);
340                 for (i=0; args->cert_exts[i].name; i++) {
341                         ext = X509V3_EXT_nconf(NULL, &ctx, args->cert_exts[i].name, args->cert_exts[i].value);
342                         if ( ext == NULL )
343                                 goto fail3;
344                         rc = X509_add_ext(subj_cert, ext, -1);
345                         X509_EXTENSION_free(ext);
346                         if ( !rc )
347                                 goto fail3;
348                 }
349                 if (args->more_exts) {
350                         for (i=0; args->more_exts[i].name; i++) {
351                                 ext = X509V3_EXT_nconf(NULL, &ctx, args->more_exts[i].name, args->more_exts[i].value);
352                                 if ( ext == NULL )
353                                         goto fail3;
354                                 rc = X509_add_ext(subj_cert, ext, -1);
355                                 X509_EXTENSION_free(ext);
356                                 if ( !rc )
357                                         goto fail3;
358                         }
359                 }
360         }
361         rc = autoca_signcert( subj_cert, args->issuer_pkey );
362         if ( rc < 0 )
363                 goto fail3;
364         args->dercert.bv_len = i2d_X509( subj_cert, NULL );
365         args->dercert.bv_val = op->o_tmpalloc( args->dercert.bv_len, op->o_tmpmemctx );
366         pp = args->dercert.bv_val;
367         i2d_X509( subj_cert, &pp );
368         args->newcert = subj_cert;
369         return 0;
370 }
371
372 typedef struct saveargs {
373         ObjectClass *oc;
374         struct berval *dercert;
375         struct berval *derpkey;
376         slap_overinst *on;
377         struct berval *dn;
378         struct berval *ndn;
379         int isca;
380 } saveargs;
381
382 static int autoca_savecert( Operation *op, saveargs *args )
383 {
384         Modifications mod[3], *mp = mod;
385         struct berval bvs[6], *bp = bvs;
386         BackendInfo *bi;
387         slap_callback cb = {0};
388         SlapReply rs = {REP_RESULT};
389
390         if ( args->oc ) {
391                 mp->sml_numvals = 1;
392                 mp->sml_values = bp;
393                 mp->sml_nvalues = NULL;
394                 mp->sml_desc = slap_schema.si_ad_objectClass;
395                 mp->sml_op = LDAP_MOD_ADD;
396                 mp->sml_flags = SLAP_MOD_INTERNAL;
397                 *bp++ = args->oc->soc_cname;
398                 BER_BVZERO( bp );
399                 bp++;
400                 mp->sml_next = mp+1;
401                 mp++;
402         }
403         mp->sml_numvals = 1;
404         mp->sml_values = bp;
405         mp->sml_nvalues = NULL;
406         mp->sml_desc = args->isca ? ad_caCert : ad_usrCert;
407         mp->sml_op = LDAP_MOD_REPLACE;
408         mp->sml_flags = SLAP_MOD_INTERNAL;
409         *bp++ = *args->dercert;
410         BER_BVZERO( bp );
411         bp++;
412         mp->sml_next = mp+1;
413         mp++;
414
415         mp->sml_numvals = 1;
416         mp->sml_values = bp;
417         mp->sml_nvalues = NULL;
418         mp->sml_desc = args->isca ? ad_caPkey : ad_usrPkey;
419         mp->sml_op = LDAP_MOD_ADD;
420         mp->sml_flags = SLAP_MOD_INTERNAL;
421         *bp++ = *args->derpkey;
422         BER_BVZERO( bp );
423         mp->sml_next = NULL;
424
425         cb.sc_response = slap_null_cb;
426         bi = op->o_bd->bd_info;
427         op->o_bd->bd_info = args->on->on_info->oi_orig;
428         op->o_tag = LDAP_REQ_MODIFY;
429         op->o_callback = &cb;
430         op->orm_modlist = mod;
431         op->orm_no_opattrs = 1;
432         op->o_req_dn = *args->dn;
433         op->o_req_ndn = *args->ndn;
434         op->o_bd->be_modify( op, &rs );
435         op->o_bd->bd_info = bi;
436         return rs.sr_err;
437 }
438
439 enum {
440         ACA_USRCLASS = 1,
441         ACA_SRVCLASS,
442         ACA_USRKEYBITS,
443         ACA_SRVKEYBITS,
444         ACA_CAKEYBITS,
445         ACA_USRDAYS,
446         ACA_SRVDAYS,
447         ACA_CADAYS
448 };
449
450 static int autoca_cf( ConfigArgs *c )
451 {
452         slap_overinst *on = (slap_overinst *)c->bi;
453         autoca_info *ai = on->on_bi.bi_private;
454         int rc = 0;
455
456         switch( c->op ) {
457         case SLAP_CONFIG_EMIT:
458                 switch( c->type ) {
459                 case ACA_USRCLASS:
460                         if ( ai->ai_usrclass ) {
461                                 c->value_string = ch_strdup( ai->ai_usrclass->soc_cname.bv_val );
462                         } else {
463                                 rc = 1;
464                         }
465                         break;
466                 case ACA_SRVCLASS:
467                         if ( ai->ai_srvclass ) {
468                                 c->value_string = ch_strdup( ai->ai_srvclass->soc_cname.bv_val );
469                         } else {
470                                 rc = 1;
471                         }
472                         break;
473                 case ACA_USRKEYBITS:
474                         c->value_int = ai->ai_usrkeybits;
475                         break;
476                 case ACA_SRVKEYBITS:
477                         c->value_int = ai->ai_srvkeybits;
478                         break;
479                 case ACA_CAKEYBITS:
480                         c->value_int = ai->ai_cakeybits;
481                         break;
482                 case ACA_USRDAYS:
483                         c->value_int = ai->ai_usrdays;
484                         break;
485                 case ACA_SRVDAYS:
486                         c->value_int = ai->ai_srvdays;
487                         break;
488                 case ACA_CADAYS:
489                         c->value_int = ai->ai_cadays;
490                         break;
491                 }
492                 break;
493         case LDAP_MOD_DELETE:
494                 switch( c->type ) {
495                 case ACA_USRCLASS:
496                         ai->ai_usrclass = NULL;
497                         break;
498                 case ACA_SRVCLASS:
499                         ai->ai_srvclass = NULL;
500                         break;
501                 /* single-valued attrs, all no-ops */
502                 }
503                 break;
504         case SLAP_CONFIG_ADD:
505         case LDAP_MOD_ADD:
506                 switch( c->type ) {
507                 case ACA_USRCLASS:
508                         {
509                                 ObjectClass *oc = oc_find( c->value_string );
510                                 if ( oc )
511                                         ai->ai_usrclass = oc;
512                                 else
513                                         rc = 1;
514                         }
515                         break;
516                 case ACA_SRVCLASS:
517                         {
518                                 ObjectClass *oc = oc_find( c->value_string );
519                                 if ( oc )
520                                         ai->ai_srvclass = oc;
521                                 else
522                                         rc = 1;
523                         }
524                 case ACA_USRKEYBITS:
525                         if ( c->value_int < MIN_KEYBITS )
526                                 rc = 1;
527                         else
528                                 ai->ai_usrkeybits = c->value_int;
529                         break;
530                 case ACA_SRVKEYBITS:
531                         if ( c->value_int < MIN_KEYBITS )
532                                 rc = 1;
533                         else
534                                 ai->ai_srvkeybits = c->value_int;
535                         break;
536                 case ACA_CAKEYBITS:
537                         if ( c->value_int < MIN_KEYBITS )
538                                 rc = 1;
539                         else
540                                 ai->ai_cakeybits = c->value_int;
541                         break;
542                 case ACA_USRDAYS:
543                         ai->ai_usrdays = c->value_int;
544                         break;
545                 case ACA_SRVDAYS:
546                         ai->ai_srvdays = c->value_int;
547                         break;
548                 case ACA_CADAYS:
549                         ai->ai_cadays = c->value_int;
550                         break;
551                 }
552         }
553         return rc;
554 }
555
556 static ConfigTable autoca_cfg[] = {
557         { "userClass", "objectclass", 2, 2, 0,
558           ARG_STRING|ARG_MAGIC|ACA_USRCLASS, autoca_cf,
559           "( OLcfgOvAt:22.1 NAME 'olcACAuserClass' "
560           "DESC 'ObjectClass of user entries' "
561           "SYNTAX OMsDirectoryString )", NULL, NULL },
562         { "servererClass", "objectclass", 2, 2, 0,
563           ARG_STRING|ARG_MAGIC|ACA_SRVCLASS, autoca_cf,
564           "( OLcfgOvAt:22.2 NAME 'olcACAserverClass' "
565           "DESC 'ObjectClass of server entries' "
566           "SYNTAX OMsDirectoryString )", NULL, NULL },
567         { "userKeybits", "integer", 2, 2, 0,
568           ARG_INT|ARG_MAGIC|ACA_USRKEYBITS, autoca_cf,
569           "( OLcfgOvAt:22.3 NAME 'olcACAuserKeybits' "
570           "DESC 'Size of PrivateKey for user entries' "
571           "SYNTAX OMsInteger )", NULL, NULL },
572         { "serverKeybits", "integer", 2, 2, 0,
573           ARG_INT|ARG_MAGIC|ACA_SRVKEYBITS, autoca_cf,
574           "( OLcfgOvAt:22.4 NAME 'olcACAserverKeybits' "
575           "DESC 'Size of PrivateKey for server entries' "
576           "SYNTAX OMsInteger )", NULL, NULL },
577         { "caKeybits", "integer", 2, 2, 0,
578           ARG_INT|ARG_MAGIC|ACA_CAKEYBITS, autoca_cf,
579           "( OLcfgOvAt:22.5 NAME 'olcACAKeybits' "
580           "DESC 'Size of PrivateKey for CA certificate' "
581           "SYNTAX OMsInteger )", NULL, NULL },
582         { "userDays", "integer", 2, 2, 0,
583           ARG_INT|ARG_MAGIC|ACA_USRDAYS, autoca_cf,
584           "( OLcfgOvAt:22.6 NAME 'olcACAuserDays' "
585           "DESC 'Lifetime of user certificates in days' "
586           "SYNTAX OMsInteger )", NULL, NULL },
587         { "serverDays", "integer", 2, 2, 0,
588           ARG_INT|ARG_MAGIC|ACA_SRVDAYS, autoca_cf,
589           "( OLcfgOvAt:22.7 NAME 'olcACAserverDays' "
590           "DESC 'Lifetime of server certificates in days' "
591           "SYNTAX OMsInteger )", NULL, NULL },
592         { "caDays", "integer", 2, 2, 0,
593           ARG_INT|ARG_MAGIC|ACA_CADAYS, autoca_cf,
594           "( OLcfgOvAt:22.8 NAME 'olcACADays' "
595           "DESC 'Lifetime of CA certificate in days' "
596           "SYNTAX OMsInteger )", NULL, NULL },
597         { NULL, NULL, 0, 0, 0, ARG_IGNORED }
598 };
599
600 static ConfigOCs autoca_ocs[] = {
601         { "( OLcfgOvOc:22.1 "
602           "NAME 'olcACAConfig' "
603           "DESC 'AutoCA configuration' "
604           "SUP olcOverlayConfig "
605           "MAY ( olcACAuserClass $ olcACAserverClass $ "
606            "olcACAuserKeybits $ olcACAserverKeybits $ olcACAKeyBits $ "
607            "olcACAuserDays $ olcACAserverDays $ olcACADays ) )",
608           Cft_Overlay, autoca_cfg },
609         { NULL, 0, NULL }
610 };
611
612 static int
613 autoca_op_response(
614         Operation *op,
615         SlapReply *rs
616 )
617 {
618         slap_overinst *on = op->o_callback->sc_private;
619         autoca_info *ai = on->on_bi.bi_private;
620         Attribute *a;
621         int isusr = 0;
622
623         if (rs->sr_type != REP_SEARCH)
624                 return SLAP_CB_CONTINUE;
625
626         /* If root or self */
627         if ( !be_isroot( op ) &&
628                 !dn_match( &rs->sr_entry->e_nname, &op->o_ndn ))
629                 return SLAP_CB_CONTINUE;
630
631         isusr = is_entry_objectclass( rs->sr_entry, ai->ai_usrclass, SLAP_OCF_CHECK_SUP );
632         if ( !isusr )
633         {
634                 if (!is_entry_objectclass( rs->sr_entry, ai->ai_srvclass, SLAP_OCF_CHECK_SUP ))
635                         return SLAP_CB_CONTINUE;
636         }
637         a = attr_find( rs->sr_entry->e_attrs, ad_usrPkey );
638         if ( !a )
639         {
640                 Operation op2;
641                 genargs args;
642                 saveargs arg2;
643                 myext extras[2];
644                 int rc;
645
646                 args.issuer_cert = ai->ai_cert;
647                 args.issuer_pkey = ai->ai_pkey;
648                 args.subjectDN = &rs->sr_entry->e_name;
649                 args.more_exts = NULL;
650                 if ( isusr )
651                 {
652                         args.cert_exts = usrExts;
653                         args.keybits = ai->ai_usrkeybits;
654                         args.days = ai->ai_usrdays;
655                         a = attr_find( rs->sr_entry->e_attrs, ad_mail );
656                         if ( a )
657                         {
658                                 extras[0].name = "subjectAltName";
659                                 extras[1].name = NULL;
660                                 extras[0].value = op->o_tmpalloc( sizeof("email:") + a->a_vals[0].bv_len, op->o_tmpmemctx );
661                                 sprintf(extras[0].value, "email:%s", a->a_vals[0].bv_val);
662                                 args.more_exts = extras;
663                         }
664                 } else
665                 {
666                         args.cert_exts = srvExts;
667                         args.keybits = ai->ai_srvkeybits;
668                         args.days = ai->ai_srvdays;
669                         if ( ad_ipaddr && (a = attr_find( rs->sr_entry->e_attrs, ad_ipaddr )))
670                         {
671                                 extras[0].name = "subjectAltName";
672                                 extras[1].name = NULL;
673                                 extras[0].value = op->o_tmpalloc( sizeof("IP:") + a->a_vals[0].bv_len, op->o_tmpmemctx );
674                                 sprintf(extras[0].value, "IP:%s", a->a_vals[0].bv_val);
675                                 args.more_exts = extras;
676                         }
677                 }
678                 rc = autoca_gencert( op, &args );
679                 if ( rc )
680                         return SLAP_CB_CONTINUE;
681                 X509_free( args.newcert );
682                 EVP_PKEY_free( args.newpkey );
683
684                 if ( is_entry_objectclass( rs->sr_entry, oc_usrObj, 0 ))
685                         arg2.oc = NULL;
686                 else
687                         arg2.oc = oc_usrObj;
688                 arg2.dercert = &args.dercert;
689                 arg2.derpkey = &args.derpkey;
690                 arg2.on = on;
691                 arg2.dn = &rs->sr_entry->e_name;
692                 arg2.ndn = &rs->sr_entry->e_nname;
693                 arg2.isca = 0;
694                 op2 = *op;
695                 rc = autoca_savecert( &op2, &arg2 );
696                 if ( !rc )
697                 {
698                         if ( !( rs->sr_flags & REP_ENTRY_MODIFIABLE ))
699                         {
700                                 Entry *e = entry_dup( rs->sr_entry );
701                                 rs_replace_entry( op, rs, on, e );
702                                 rs->sr_flags |= REP_ENTRY_MODIFIABLE | REP_ENTRY_MUSTBEFREED;
703                         }
704                         attr_merge_one( rs->sr_entry, ad_usrCert, &args.dercert, NULL );
705                         attr_merge_one( rs->sr_entry, ad_usrPkey, &args.derpkey, NULL );
706                 }
707                 op->o_tmpfree( args.dercert.bv_val, op->o_tmpmemctx );
708                 op->o_tmpfree( args.derpkey.bv_val, op->o_tmpmemctx );
709         }
710
711         return SLAP_CB_CONTINUE;
712 }
713
714 static int
715 autoca_op_search(
716         Operation *op,
717         SlapReply *rs
718 )
719 {
720         /* we only act on a search that returns just our cert/key attrs */
721         if ( op->ors_attrs[0].an_desc == ad_usrCert &&
722                 op->ors_attrs[1].an_desc == ad_usrPkey &&
723                 op->ors_attrs[2].an_name.bv_val == NULL )
724         {
725                 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
726                 slap_callback *sc = op->o_tmpcalloc( 1, sizeof(slap_callback), op->o_tmpmemctx );
727                 sc->sc_response = autoca_op_response;
728                 sc->sc_private = on;
729                 sc->sc_next = op->o_callback;
730                 op->o_callback = sc;
731         }
732         return SLAP_CB_CONTINUE;
733 }
734
735 static int
736 autoca_db_init(
737         BackendDB *be,
738         ConfigReply *cr
739 )
740 {
741         slap_overinst *on = (slap_overinst *) be->bd_info;
742         autoca_info *ai;
743
744         ai = ch_calloc(1, sizeof(autoca_info));
745         on->on_bi.bi_private = ai;
746
747         /* set defaults */
748         ai->ai_usrclass = oc_find( "person" );
749         ai->ai_srvclass = oc_find( "ipHost" );
750         ai->ai_usrkeybits = KEYBITS;
751         ai->ai_srvkeybits = KEYBITS;
752         ai->ai_cakeybits = KEYBITS;
753         ai->ai_usrdays = 365;   /* 1 year */
754         ai->ai_srvdays = 1826;  /* 5 years */
755         ai->ai_cadays = 3652;   /* 10 years */
756         return 0;
757 }
758
759 static int
760 autoca_db_destroy(
761         BackendDB *be,
762         ConfigReply *cr
763 )
764 {
765         slap_overinst *on = (slap_overinst *) be->bd_info;
766         autoca_info *ai = on->on_bi.bi_private;
767
768         if ( ai->ai_cert )
769                 X509_free( ai->ai_cert );
770         if ( ai->ai_pkey )
771                 EVP_PKEY_free( ai->ai_pkey );
772         ch_free( ai );
773
774         return 0;
775 }
776
777 static int
778 autoca_db_open(
779         BackendDB *be,
780         ConfigReply *cr
781 )
782 {
783         slap_overinst *on = (slap_overinst *)be->bd_info;
784         autoca_info *ai = on->on_bi.bi_private;
785
786         Connection conn = { 0 };
787         OperationBuffer opbuf;
788         Operation *op;
789         void *thrctx;
790         Entry *e;
791         Attribute *a;
792         int rc;
793
794         if (slapMode & SLAP_TOOL_MODE)
795                 return 0;
796
797         thrctx = ldap_pvt_thread_pool_context();
798         connection_fake_init2( &conn, &opbuf, thrctx, 0 );
799         op = &opbuf.ob_op;
800         op->o_bd = be;
801         op->o_dn = be->be_rootdn;
802         op->o_ndn = be->be_rootndn;
803         rc = overlay_entry_get_ov( op, be->be_nsuffix, NULL, 
804                 NULL, 0, &e, on );
805
806         if ( e ) {
807                 int gotoc = 0, gotat = 0;
808                 if ( is_entry_objectclass( e, oc_caObj, 0 )) {
809                         gotoc = 1;
810                         a = attr_find( e->e_attrs, ad_caPkey );
811                         if ( a ) {
812                                 const unsigned char *pp;
813                                 pp = a->a_vals[0].bv_val;
814                                 ai->ai_pkey = d2i_AutoPrivateKey( NULL, &pp, a->a_vals[0].bv_len );
815                                 if ( ai->ai_pkey )
816                                 {
817                                         a = attr_find( e->e_attrs, ad_caCert );
818                                         if ( a )
819                                         {
820                                                 pp = a->a_vals[0].bv_val;
821                                                 ai->ai_cert = d2i_X509( NULL, &pp, a->a_vals[0].bv_len );
822                                         }
823                                 }
824                                 gotat = 1;
825                         }
826                 }
827                 overlay_entry_release_ov( op, e, 0, on );
828                 /* generate attrs, store... */
829                 if ( !gotat ) {
830                         genargs args;
831                         saveargs arg2;
832
833                         args.issuer_cert = NULL;
834                         args.issuer_pkey = NULL;
835                         args.subjectDN = &be->be_suffix[0];
836                         args.cert_exts = CAexts;
837                         args.more_exts = NULL;
838                         args.keybits = ai->ai_cakeybits;
839                         args.days = ai->ai_cadays;
840
841                         rc = autoca_gencert( op, &args );
842                         if ( rc )
843                                 return -1;
844
845                         ai->ai_cert = args.newcert;
846                         ai->ai_pkey = args.newpkey;
847
848                         arg2.dn = be->be_suffix;
849                         arg2.ndn = be->be_nsuffix;
850                         arg2.isca = 1;
851                         if ( !gotoc )
852                                 arg2.oc = oc_caObj;
853                         else
854                                 arg2.oc = NULL;
855                         arg2.on = on;
856                         arg2.dercert = &args.dercert;
857                         arg2.derpkey = &args.derpkey;
858
859                         autoca_savecert( op, &arg2 );
860                         op->o_tmpfree( args.dercert.bv_val, op->o_tmpmemctx );
861                         op->o_tmpfree( args.derpkey.bv_val, op->o_tmpmemctx );
862                 }
863         }
864
865         return 0;
866 }
867
868 static slap_overinst autoca;
869
870 /* This overlay is set up for dynamic loading via moduleload. For static
871  * configuration, you'll need to arrange for the slap_overinst to be
872  * initialized and registered by some other function inside slapd.
873  */
874
875 int autoca_initialize() {
876         int i, code;
877         const char *text;
878
879         autoca.on_bi.bi_type = "autoca";
880         autoca.on_bi.bi_db_init = autoca_db_init;
881         autoca.on_bi.bi_db_destroy = autoca_db_destroy;
882         autoca.on_bi.bi_db_open = autoca_db_open;
883         autoca.on_bi.bi_op_search = autoca_op_search;
884
885         autoca.on_bi.bi_cf_ocs = autoca_ocs;
886         code = config_register_schema( autoca_cfg, autoca_ocs );
887         if ( code ) return code;
888
889         for ( i=0; aca_attrs[i]; i++ ) {
890                 code = register_at( aca_attrs[i], NULL, 0 );
891                 if ( code ) return code;
892         }
893
894         for ( i=0; aca_attr2[i].at; i++ ) {
895                 code = slap_str2ad( aca_attr2[i].at, aca_attr2[i].ad, &text );
896                 if ( code ) return code;
897         }
898
899         /* Schema may not be loaded, ignore if missing */
900         slap_str2ad( "ipHostNumber", &ad_ipaddr, &text );
901
902         for ( i=0; aca_ocs[i].ot; i++ ) {
903                 code = register_oc( aca_ocs[i].ot, aca_ocs[i].oc, 0 );
904                 if ( code ) return code;
905         }
906
907         return overlay_register( &autoca );
908 }
909
910 #if SLAPD_OVER_AUTOCA == SLAPD_MOD_DYNAMIC
911 int
912 init_module( int argc, char *argv[] )
913 {
914         return autoca_initialize();
915 }
916 #endif
917
918 #endif /* defined(SLAPD_OVER_AUTOCA) */