summaryrefslogtreecommitdiffstats
path: root/base/server/cms/src/org/dogtagpki/server/rest/ACLInterceptor.java
blob: ca19ef188c8a0425040538183f8f2729fbe3cc54 (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
//--- BEGIN COPYRIGHT BLOCK ---
//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; version 2 of the License.
//
//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, write to the Free Software Foundation, Inc.,
//51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
//(C) 2012 Red Hat, Inc.
//All rights reserved.
//--- END COPYRIGHT BLOCK ---
package org.dogtagpki.server.rest;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.security.Principal;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.ext.Provider;

import org.apache.catalina.realm.GenericPrincipal;
import org.jboss.resteasy.core.ResourceMethodInvoker;
import org.jboss.resteasy.spi.Failure;

import com.netscape.certsrv.acls.ACLMapping;
import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.authentication.ExternalAuthToken;
import com.netscape.certsrv.authentication.IAuthToken;
import com.netscape.certsrv.authorization.AuthzToken;
import com.netscape.certsrv.authorization.EAuthzAccessDenied;
import com.netscape.certsrv.authorization.EAuthzUnknownRealm;
import com.netscape.certsrv.authorization.IAuthzSubsystem;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.ForbiddenException;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.logging.LogEvent;
import com.netscape.certsrv.logging.event.AuthzFailEvent;
import com.netscape.certsrv.logging.event.AuthzSuccessEvent;
import com.netscape.cms.logging.Logger;
import com.netscape.cms.logging.SignedAuditLogger;
import com.netscape.cms.realm.PKIPrincipal;

/**
 * @author Endi S. Dewata
 */
@Provider
public class ACLInterceptor implements ContainerRequestFilter {

    private static Logger signedAuditLogger = SignedAuditLogger.getLogger();

    private final static String LOGGING_ACL_PARSING_ERROR = "internal error: ACL parsing error";
    private final static String LOGGING_NO_ACL_ACCESS_ALLOWED = "no ACL configured; OK";
    private final static String LOGGING_MISSING_AUTH_TOKEN = "auth token not found";
    private final static String LOGGING_MISSING_ACL_MAPPING = "ACL mapping not found; OK";
    private final static String LOGGING_INVALID_ACL_MAPPING = "internal error: invalid ACL mapping";

    Properties properties;

    @Context
    ServletContext servletContext;

    @Context
    SecurityContext securityContext;

    public synchronized void loadProperties() throws IOException {

        if (properties != null)
            return;

        properties = new Properties();

        String context = servletContext.getContextPath();
        String subsystem = context.startsWith("/") ? context.substring(1) : context;

        // load default mapping
        String defaultMapping = "/usr/share/pki/" + subsystem + "/conf/acl.properties";
        CMS.debug("ACLInterceptor: loading " + defaultMapping);
        try (FileReader in = new FileReader(defaultMapping)) {
            properties.load(in);
        }

        // load custom mapping
        File customMapping = new File(System.getProperty("catalina.base")
                + "/" + subsystem + "/conf/acl.properties");
        CMS.debug("ACLInterceptor: checking " + customMapping);
        if (customMapping.exists()) {
            CMS.debug("ACLInterceptor: loading " + customMapping);
            try (FileReader in = new FileReader(customMapping)) {
                properties.load(in);
            }
        }
    }

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        ResourceMethodInvoker methodInvoker = (ResourceMethodInvoker) requestContext
                .getProperty("org.jboss.resteasy.core.ResourceMethodInvoker");
        Method method = methodInvoker.getMethod();
        Class<?> clazz = methodInvoker.getResourceClass();
        String auditInfo =  clazz.getSimpleName() + "." + method.getName();

        CMS.debug("ACLInterceptor: " + auditInfo + "()");
        String auditSubjectID = ILogger.UNIDENTIFIED;

        /*
         * when aclMapping is null, it's either of the following :
         *   - only authentication needed
         *   - allows anonymous, i.e. no authentication or authorization needed
         * use authzRequired to track when aclMapping is not null for ease of following the code
         */
        boolean authzRequired = true;
        ACLMapping aclMapping = method.getAnnotation(ACLMapping.class);
        // If not available, get ACL mapping for the class.
        if (aclMapping == null) {
            aclMapping = clazz.getAnnotation(ACLMapping.class);
        }
        if (aclMapping == null) {
            CMS.debug("ACLInterceptor.filter: no authorization required");
            authzRequired = false;
        }

        Principal principal = null;
        principal = securityContext.getUserPrincipal();

        // If unauthenticated, reject request.
        if (principal == null && authzRequired) {
            CMS.debug("ACLInterceptor: No user principal provided.");
            // audit comment: no Principal, no one to blame here
            throw new ForbiddenException("No user principal provided.");
        }
        if (principal != null)
            CMS.debug("ACLInterceptor: principal: " + principal.getName());

        IAuthzSubsystem authzSubsystem =
            (IAuthzSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_AUTHZ);

        IAuthToken authToken = null;
        String authzMgrName = null;
        if (principal != null) {
            if (principal instanceof PKIPrincipal) {
                authzMgrName = "DirAclAuthz";
                authToken = ((PKIPrincipal) principal).getAuthToken();
            }
            else if (principal instanceof GenericPrincipal) {
                String realm = null;
                String[] parts = principal.getName().split("@", 2);
                if (parts.length == 2) {
                    realm = parts[1];
                }
                try {
                    authzMgrName = authzSubsystem.getAuthzManagerNameByRealm(realm);
                } catch (EAuthzUnknownRealm e) {
                    throw new ForbiddenException(
                        "Cannot find AuthzManager for external principal " + principal.getName(),
                        e
                    );
                }
                authToken = new ExternalAuthToken((GenericPrincipal) principal);
            }
            CMS.debug("ACLInterceptor: will use authz manager " + authzMgrName);
        }

        // If missing auth token, reject request.
        if (authToken == null && authzRequired) {
            CMS.debug("ACLInterceptor: No authentication token present.");
            // store a message in the signed audit log file
            // although if it didn't pass authentication, it should not have gotten here
            audit(new AuthzFailEvent(
                        auditSubjectID,
                        ILogger.FAILURE,
                        null, // resource
                        null, // operation
                        LOGGING_MISSING_AUTH_TOKEN + ":" + auditInfo));

            throw new ForbiddenException("No authorization token present.");
        }
        if (authToken != null)
            auditSubjectID = authToken.getInString(IAuthToken.USER_ID);

        // If still not available, it's unprotected, allow request.
        if (!authzRequired) {
            CMS.debug("ACLInterceptor: No ACL mapping; authz not required.");

            audit(new AuthzSuccessEvent(
                        auditSubjectID,
                        ILogger.SUCCESS,
                        null, //resource
                        null, //operation
                        LOGGING_MISSING_ACL_MAPPING + ":" + auditInfo)); //info

            return;
        }

        // we know aclMapping is not null now (!noAuthzRequired); authz game on...
        String name = aclMapping.value();
        CMS.debug("ACLInterceptor: mapping: " + name);

        String values[] = null;
        String value = null;
        try {
            loadProperties();

            value = properties.getProperty(name);

        } catch (IOException e) {

            audit(new AuthzFailEvent(
                        auditSubjectID,
                        ILogger.FAILURE,
                        null, //resource
                        null, //operation
                        LOGGING_ACL_PARSING_ERROR + ":" + auditInfo));

            e.printStackTrace();
            throw new Failure(e);
        }

        // If no property defined, allow request.
        if (value == null) {
            CMS.debug("ACLInterceptor: No ACL configuration.");

            audit(new AuthzSuccessEvent(
                    auditSubjectID,
                    ILogger.SUCCESS,
                    null, //resource
                    null, //operation
                    LOGGING_NO_ACL_ACCESS_ALLOWED + ":" + auditInfo));

            return;
        }

        values = value.split(",");

        // If invalid mapping, reject request.
        if (values.length != 2) {
            CMS.debug("ACLInterceptor: Invalid ACL mapping.");

            audit(new AuthzFailEvent(
                    auditSubjectID,
                    ILogger.FAILURE,
                    null, //resource
                    null, //operation
                    LOGGING_INVALID_ACL_MAPPING + ":" + auditInfo));

            throw new ForbiddenException("Invalid ACL mapping.");
        }

        CMS.debug("ACLInterceptor: ACL: " + value);

        try {
            // Check authorization.
            AuthzToken authzToken = authzSubsystem.authorize(
                    authzMgrName,
                    authToken,
                    values[0], // resource
                    values[1]); // operation

            // If not authorized, reject request.
            if (authzToken == null) {
                String info = "No authorization token present.";
                CMS.debug("ACLInterceptor: " + info);

                audit(new AuthzFailEvent(
                            auditSubjectID,
                            ILogger.FAILURE,
                            values[0], // resource
                            values[1], // operation
                            info));

                throw new ForbiddenException("No authorization token present.");
            }

            CMS.debug("ACLInterceptor: access granted");

        } catch (EAuthzAccessDenied e) {
            String info = e.getMessage();
            CMS.debug("ACLInterceptor: " + info);

            audit(new AuthzFailEvent(
                        auditSubjectID,
                        ILogger.FAILURE,
                        values[0], // resource
                        values[1], // operation
                        info));

            throw new ForbiddenException(e.toString());

        } catch (EBaseException e) {
            String info = e.getMessage();

            audit(new AuthzFailEvent(
                        auditSubjectID,
                        ILogger.FAILURE,
                        values[0], // resource
                        values[1], // operation
                        info));

            e.printStackTrace();
            throw new Failure(e);
        }

        // Allow request.

        audit(new AuthzSuccessEvent(
                    auditSubjectID,
                    ILogger.SUCCESS,
                    values[0], // resource
                    values[1], // operation
                    auditInfo));

        return;
    }

    /**
     * Signed Audit Log
     *
     * This method is called to store messages to the signed audit log.
     * <P>
     *
     * @param msg signed audit log message
     */
    protected void audit(String msg) {
        signedAuditLogger.log(msg);
    }

    protected void audit(LogEvent event) {
        signedAuditLogger.log(event);
    }
}