summaryrefslogtreecommitdiffstats
path: root/base/common/src/com/netscape/cmscore/realm/PKIRealm.java
blob: 9b4b97c2a5e0dfbb78775f5b46ec41c7a4e839c2 (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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
package com.netscape.cmscore.realm;

import java.io.IOException;
import java.io.InputStream;
import java.security.Principal;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletResponse;

import netscape.security.x509.X509CertImpl;

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.deploy.SecurityConstraint;
import org.apache.catalina.realm.RealmBase;

import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.authentication.IAuthManager;
import com.netscape.certsrv.authentication.IAuthSubsystem;
import com.netscape.certsrv.authentication.IAuthToken;
import com.netscape.certsrv.authorization.AuthzToken;
import com.netscape.certsrv.authorization.IAuthzSubsystem;
import com.netscape.certsrv.usrgrp.EUsrGrpException;
import com.netscape.certsrv.usrgrp.IGroup;
import com.netscape.certsrv.usrgrp.IUGSubsystem;
import com.netscape.certsrv.usrgrp.IUser;
import com.netscape.cms.servlet.common.AuthCredentials;
import com.netscape.cmscore.authentication.CertUserDBAuthentication;
import com.netscape.cmscore.authentication.PasswdUserDBAuthentication;

/**
 *  PKI Realm
 *
 *  This realm provides an authentication service against PKI user database.
 *  The realm also provides an authorization service that validates request
 *  URL's against the access control list defined in the internal database.
 */

public class PKIRealm extends RealmBase {

    public final static String PROP_AUTH_FILE_PATH = "/WEB-INF/auth.properties";
    public final static int EXPRESSION_SIZE = 2;

    Properties authzProperties;

    public PKIRealm() {
        logDebug("Creating PKI realm");
    }

    @Override
    protected void initInternal() throws LifecycleException {
        logDebug("Initializing PKI realm");
        super.initInternal();
    }

    @Override
    protected void startInternal() throws LifecycleException {
        logDebug("Starting PKI realm");
        super.startInternal();
    }

    @Override
    protected String getName() {
        return "PKIRealm";
    }

    @Override
    public Principal authenticate(String username, String password) {
        logDebug("Authenticating username "+username+" with password.");

        try {
            IAuthSubsystem authSub = (IAuthSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_AUTH);
            IAuthManager authMgr = authSub.getAuthManager(IAuthSubsystem.PASSWDUSERDB_AUTHMGR_ID);

            AuthCredentials creds = new AuthCredentials();
            creds.set(PasswdUserDBAuthentication.CRED_UID, username);
            creds.set(PasswdUserDBAuthentication.CRED_PWD, password);

            IAuthToken authToken = authMgr.authenticate(creds); // throws exception if authentication fails

            return getPrincipal(username, authToken);

        } catch (Throwable e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public Principal authenticate(final X509Certificate certs[]) {
        logDebug("Authenticating certificate chain:");

        try {
            X509CertImpl certImpls[] = new X509CertImpl[certs.length];
            for (int i=0; i<certs.length; i++) {
                X509Certificate cert = certs[i];
                logDebug("  "+cert.getSubjectDN());

                // Convert sun.security.x509.X509CertImpl to netscape.security.x509.X509CertImpl
                certImpls[i] = new X509CertImpl(cert.getEncoded());
            }

            IAuthSubsystem authSub = (IAuthSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_AUTH);
            IAuthManager authMgr = authSub.getAuthManager(IAuthSubsystem.CERTUSERDB_AUTHMGR_ID);

            AuthCredentials creds = new AuthCredentials();
            creds.set(CertUserDBAuthentication.CRED_CERT, certImpls);

            IAuthToken authToken = authMgr.authenticate(creds); // throws exception if authentication fails

            String username = authToken.getInString(CertUserDBAuthentication.TOKEN_USERID);
            logDebug("User ID: "+username);

            return getPrincipal(username, authToken);

        } catch (Throwable e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected Principal getPrincipal(String username) {
        return getPrincipal(username, (IAuthToken)null);
    }

    protected Principal getPrincipal(String username, IAuthToken authToken) {

        try {
            IUser user = getUser(username);
            return getPrincipal(user, authToken);

        } catch (Throwable e) {
            e.printStackTrace();
            return null;
        }
    }

    protected Principal getPrincipal(IUser user, IAuthToken authToken) throws EUsrGrpException {
        List<String> roles = getRoles(user);
        return new PKIPrincipal(user.getUserID(), null, roles, authToken);
    }

    protected IUser getUser(String username) throws EUsrGrpException {
        IUGSubsystem ugSub = (IUGSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_UG);
        IUser user = ugSub.getUser(username);
        logDebug("User DN: "+user.getUserDN());
        return user;
    }

    protected List<String> getRoles(IUser user) throws EUsrGrpException {

        List<String> roles = new ArrayList<String>();

        IUGSubsystem ugSub = (IUGSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_UG);
        Enumeration<IGroup> groups = ugSub.findGroupsByUser(user.getUserDN());

        logDebug("Roles:");
        while (groups.hasMoreElements()) {
            IGroup group = groups.nextElement();

            String name = group.getName();
            logDebug("  "+name);
            roles.add(name);
        }

        return roles;
    }

    @Override
    protected String getPassword(String username) {
        return null;
    }

    /**
     * Perform access control based on the specified authorization constraint.
     * Return <code>true</code> if this constraint is satisfied and processing
     * should continue, or <code>false</code> otherwise.
     * override to check for custom PKI ACL's authz permissions.
     *
     * @param request Request we are processing
     * @param response Response we are creating
     * @param constraints Security constraint we are enforcing
     * @param context The Context to which client of this class is attached.
     *
     * @exception IOException if an input/output error occurs
     */
    @Override
    public boolean hasResourcePermission(Request request,
            Response response,
            SecurityConstraint[] constraints,
            Context context)
            throws IOException {

        String requestURI = request.getDecodedRequestURI();
        logDebug("Checking permission: "+requestURI);

        boolean allowed = super.hasResourcePermission(request, response, constraints, context);
        logDebug("Resource permission: "+allowed);

        if (allowed) {
            allowed = checkACL(request, response, constraints, context);
            logDebug("ACL permission: "+allowed);
        }

        if (!allowed) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, sm.getString("realmBase.forbidden"));
        }

        return allowed;
    }

    public boolean checkACL(Request request,
            Response response,
            SecurityConstraint[] constraints,
            Context context) {

        try {
            loadAuthzProperties(context);
            if (!hasAuthzProperties()) return false;

            String requestURI = request.getDecodedRequestURI();
            String match = getACLEntry(requestURI);
            if (match == null) return false;

            logDebug("ACL: "+match);
            String[] authzParams = match.split("\\,");

            String resource = null;
            String operation = null;

            if (authzParams.length >= EXPRESSION_SIZE) {
                resource = authzParams[0];
                operation = authzParams[1];

                if (resource != null) {
                    resource = resource.trim();
                }

                if (operation != null) {
                    operation = operation.trim();
                }
            }

            Principal principal = request.getUserPrincipal();
            if (principal instanceof PKIPrincipal) {
                PKIPrincipal pkiPrincipal = (PKIPrincipal)principal;
                IAuthToken authToken = pkiPrincipal.getAuthToken();

                logDebug("Auth token:");
                Enumeration<String> names = authToken.getElements();
                while (names.hasMoreElements()) {
                    String name = names.nextElement();
                    Object value = authToken.get(name);
                    logDebug("  " + name +": " + value);
                }

                logDebug("Resource: " + resource);
                logDebug("Operation: " + operation);

                IAuthzSubsystem mAuthz = (IAuthzSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_AUTHZ);
                AuthzToken authzToken = mAuthz.authorize("DirAclAuthz", authToken, resource, operation);
                if (authzToken != null) return true;
            }

        } catch (Throwable e) {
            e.printStackTrace();
        }

        return false;
    }

    // Search for the proper auth.properties entry corresponding
    // to a particular incoming URL
    // TODO: In the admin interface, often the operation is sent
    // as one of the parameters to the message.
    // There may be a way to extract this information at this level.
    // The parameter name to scan for could be configured with the Realm.

    public String getACLEntry(String requestURI) {

        if (!hasAuthzProperties()) {
            return null;
        }

        logDebug("Checking path: "+requestURI);
        String aclEntryData = authzProperties.getProperty(requestURI);

        if (aclEntryData != null) {
            logDebug("Found exact match: "+aclEntryData);
            return aclEntryData;
        }

        // Check for a partial match such as
        // ex: /kra/pki/keyrequest/2
        // TODO: Check into more sophisticated
        // methods of doing this mapping.
        // Perhaps Rest gives us this more
        // sophisticated mapping ability.

        Properties props = authzProperties;
        Enumeration<?> e = props.propertyNames();

        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();
            if (requestURI.startsWith(key)) {
                aclEntryData = props.getProperty(key);
                logDebug("Found partial match ["+key+"]: "+aclEntryData);
                break;
            }
        }

        if (aclEntryData == null) {
            logDebug("No match found");
        }

        return aclEntryData;

    }

    // Check to see if we have read in the auth properties file
    public boolean hasAuthzProperties() {

        if (authzProperties != null) {
            return true;
        } else {
            return false;
        }
    }

    // Load the custom mapping file auth.properties, which maps urls to acl resourceID and operation value
    // example entry: /kra/pki/config/cert/transport = certServer.kra.pki.config.cert.transport,read
    // TODO: Look into a more sophisticated method than this simple properties file if appropriate.
    public synchronized void loadAuthzProperties(Context context) throws IOException {

        if (authzProperties == null && context != null) {

            InputStream inputStream = context.getServletContext().getResourceAsStream(PROP_AUTH_FILE_PATH);

            if (inputStream == null) {
                logDebug("Resource "+PROP_AUTH_FILE_PATH+" not found.");
                throw new IOException("Resource "+PROP_AUTH_FILE_PATH+" not found.");
            }

            try {
                logDebug("Loading authorization properties");

                Properties properties = new Properties();
                properties.load(inputStream);

                authzProperties = properties;

            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /*
     * TODO: Figure out how to do real logging
     */
    public void logErr(String msg) {
        System.err.println(msg);
    }

    public void logDebug(String msg) {
        System.out.println("PKIRealm: "+msg);
    }
}