File: SecurityUtil.java

package info (click to toggle)
tomcat10 10.1.40-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 46,748 kB
  • sloc: java: 371,059; xml: 57,665; jsp: 4,654; sh: 1,381; perl: 314; makefile: 25; ansic: 15
file content (371 lines) | stat: -rw-r--r-- 15,211 bytes parent folder | download | duplicates (4)
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
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.catalina.security;


import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.Principal;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.security.auth.Subject;

import jakarta.servlet.Filter;
import jakarta.servlet.Servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.UnavailableException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;

import org.apache.catalina.Globals;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.res.StringManager;

/**
 * This utility class associates a <code>Subject</code> to the current <code>AccessControlContext</code>. When a
 * <code>SecurityManager</code> is used, the container will always associate the called thread with an
 * AccessControlContext containing only the principal of the requested Servlet/Filter. This class uses reflection to
 * invoke the methods.
 */

public final class SecurityUtil {

    // Note that indexes overlap.
    // A Servlet uses "init", "service", "event", "destroy".
    // A Filter uses "doFilter", "doFilterEvent", "destroy".
    private static final int INIT = 0;
    private static final int SERVICE = 1;
    private static final int DOFILTER = 1;
    private static final int EVENT = 2;
    private static final int DOFILTEREVENT = 2;
    private static final int DESTROY = 3;

    private static final String INIT_METHOD = "init";
    private static final String DOFILTER_METHOD = "doFilter";
    private static final String SERVICE_METHOD = "service";
    private static final String EVENT_METHOD = "event";
    private static final String DOFILTEREVENT_METHOD = "doFilterEvent";
    private static final String DESTROY_METHOD = "destroy";

    /**
     * Cache every class for which we are creating methods.
     */
    private static final Map<Class<?>,Method[]> classCache = new ConcurrentHashMap<>();

    private static final Log log = LogFactory.getLog(SecurityUtil.class);

    private static final boolean packageDefinitionEnabled =
            (System.getProperty("package.definition") == null && System.getProperty("package.access") == null) ? false :
                    true;

    /**
     * The string resources for this package.
     */
    private static final StringManager sm = StringManager.getManager(Constants.PACKAGE);


    /**
     * Perform work as a particular <code>Subject</code>. Here the work will be granted to a <code>null</code> subject.
     *
     * @param methodName   the method to apply the security restriction
     * @param targetObject the <code>Servlet</code> on which the method will be called.
     *
     * @throws Exception an execution error occurred
     */
    public static void doAsPrivilege(final String methodName, final Servlet targetObject) throws Exception {
        doAsPrivilege(methodName, targetObject, null, null, null);
    }


    /**
     * Perform work as a particular <code>Subject</code>. Here the work will be granted to a <code>null</code> subject.
     *
     * @param methodName      the method to apply the security restriction
     * @param targetObject    the <code>Servlet</code> on which the method will be called.
     * @param targetType      <code>Class</code> array used to instantiate a <code>Method</code> object.
     * @param targetArguments <code>Object</code> array contains the runtime parameters instance.
     *
     * @throws Exception an execution error occurred
     */
    public static void doAsPrivilege(final String methodName, final Servlet targetObject, final Class<?>[] targetType,
            final Object[] targetArguments) throws Exception {

        doAsPrivilege(methodName, targetObject, targetType, targetArguments, null);
    }


    /**
     * Perform work as a particular <code>Subject</code>. Here the work will be granted to a <code>null</code> subject.
     *
     * @param methodName           the method to apply the security restriction
     * @param targetObject         the <code>Servlet</code> on which the method will be called.
     * @param targetParameterTypes <code>Class</code> array used to instantiate a <code>Method</code> object.
     * @param targetArguments      <code>Object</code> array contains the runtime parameters instance.
     * @param principal            the <code>Principal</code> to which the security privilege applies
     *
     * @throws Exception an execution error occurred
     */
    public static void doAsPrivilege(final String methodName, final Servlet targetObject,
            final Class<?>[] targetParameterTypes, final Object[] targetArguments, Principal principal)
            throws Exception {

        Method method = null;
        Method[] methodsCache = classCache.get(Servlet.class);
        if (methodsCache == null) {
            method = createMethodAndCacheIt(null, Servlet.class, methodName, targetParameterTypes);
        } else {
            method = findMethod(methodsCache, methodName);
            if (method == null) {
                method = createMethodAndCacheIt(methodsCache, Servlet.class, methodName, targetParameterTypes);
            }
        }

        execute(method, targetObject, targetArguments, principal);
    }


    /**
     * Perform work as a particular <code>Subject</code>. Here the work will be granted to a <code>null</code> subject.
     *
     * @param methodName   the method to apply the security restriction
     * @param targetObject the <code>Filter</code> on which the method will be called.
     *
     * @throws Exception an execution error occurred
     */
    public static void doAsPrivilege(final String methodName, final Filter targetObject) throws Exception {

        doAsPrivilege(methodName, targetObject, null, null);
    }


    /**
     * Perform work as a particular <code>Subject</code>. Here the work will be granted to a <code>null</code> subject.
     *
     * @param methodName      the method to apply the security restriction
     * @param targetObject    the <code>Filter</code> on which the method will be called.
     * @param targetType      <code>Class</code> array used to instantiate a <code>Method</code> object.
     * @param targetArguments <code>Object</code> array contains the runtime parameters instance.
     *
     * @throws Exception an execution error occurred
     */
    public static void doAsPrivilege(final String methodName, final Filter targetObject, final Class<?>[] targetType,
            final Object[] targetArguments) throws Exception {

        doAsPrivilege(methodName, targetObject, targetType, targetArguments, null);
    }

    /**
     * Perform work as a particular <code>Subject</code>. Here the work will be granted to a <code>null</code> subject.
     *
     * @param methodName            the method to apply the security restriction
     * @param targetObject          the <code>Filter</code> on which the method will be called.
     * @param targetParameterTypes  <code>Class</code> array used to instantiate a <code>Method</code> object.
     * @param targetParameterValues <code>Object</code> array contains the runtime parameters instance.
     * @param principal             the <code>Principal</code> to which the security privilege applies
     *
     * @throws Exception an execution error occurred
     */
    public static void doAsPrivilege(final String methodName, final Filter targetObject,
            final Class<?>[] targetParameterTypes, final Object[] targetParameterValues, Principal principal)
            throws Exception {

        Method method = null;
        Method[] methodsCache = classCache.get(Filter.class);
        if (methodsCache == null) {
            method = createMethodAndCacheIt(null, Filter.class, methodName, targetParameterTypes);
        } else {
            method = findMethod(methodsCache, methodName);
            if (method == null) {
                method = createMethodAndCacheIt(methodsCache, Filter.class, methodName, targetParameterTypes);
            }
        }

        execute(method, targetObject, targetParameterValues, principal);
    }


    /**
     * Perform work as a particular <code>Subject</code>. Here the work will be granted to a <code>null</code> subject.
     *
     * @param method          the method to apply the security restriction
     * @param targetObject    the <code>Servlet</code> on which the method will be called.
     * @param targetArguments <code>Object</code> array contains the runtime parameters instance.
     * @param principal       the <code>Principal</code> to which the security privilege applies
     *
     * @throws Exception an execution error occurred
     */
    @SuppressWarnings("deprecation")
    private static void execute(final Method method, final Object targetObject, final Object[] targetArguments,
            Principal principal) throws Exception {

        try {
            Subject subject = null;
            PrivilegedExceptionAction<Void> pea = () -> {
                method.invoke(targetObject, targetArguments);
                return null;
            };

            // The first argument is always the request object
            if (targetArguments != null && targetArguments[0] instanceof HttpServletRequest) {
                HttpServletRequest request = (HttpServletRequest) targetArguments[0];

                boolean hasSubject = false;
                HttpSession session = request.getSession(false);
                if (session != null) {
                    subject = (Subject) session.getAttribute(Globals.SUBJECT_ATTR);
                    hasSubject = (subject != null);
                }

                if (subject == null) {
                    subject = new Subject();

                    if (principal != null) {
                        subject.getPrincipals().add(principal);
                    }
                }

                if (session != null && !hasSubject) {
                    session.setAttribute(Globals.SUBJECT_ATTR, subject);
                }
            }

            Subject.doAsPrivileged(subject, pea, null);
        } catch (PrivilegedActionException pe) {
            Throwable e;
            if (pe.getException() instanceof InvocationTargetException) {
                e = pe.getException().getCause();
                ExceptionUtils.handleThrowable(e);
            } else {
                e = pe;
            }

            if (log.isDebugEnabled()) {
                log.debug(sm.getString("SecurityUtil.doAsPrivilege"), e);
            }

            if (e instanceof UnavailableException) {
                throw (UnavailableException) e;
            } else if (e instanceof ServletException) {
                throw (ServletException) e;
            } else if (e instanceof IOException) {
                throw (IOException) e;
            } else if (e instanceof RuntimeException) {
                throw (RuntimeException) e;
            } else {
                throw new ServletException(e.getMessage(), e);
            }
        }
    }


    /**
     * Find a method stored within the cache.
     *
     * @param methodsCache the cache used to store method instance
     * @param methodName   the method to apply the security restriction
     *
     * @return the method instance, null if not yet created.
     */
    private static Method findMethod(Method[] methodsCache, String methodName) {
        if (methodName.equals(INIT_METHOD)) {
            return methodsCache[INIT];
        } else if (methodName.equals(DESTROY_METHOD)) {
            return methodsCache[DESTROY];
        } else if (methodName.equals(SERVICE_METHOD)) {
            return methodsCache[SERVICE];
        } else if (methodName.equals(DOFILTER_METHOD)) {
            return methodsCache[DOFILTER];
        } else if (methodName.equals(EVENT_METHOD)) {
            return methodsCache[EVENT];
        } else if (methodName.equals(DOFILTEREVENT_METHOD)) {
            return methodsCache[DOFILTEREVENT];
        }
        return null;
    }


    /**
     * Create the method and cache it for further re-use.
     *
     * @param methodsCache   the cache used to store method instance
     * @param targetType     the class on which the method will be called.
     * @param methodName     the method to apply the security restriction
     * @param parameterTypes <code>Class</code> array used to instantiate a <code>Method</code> object.
     *
     * @return the method instance.
     *
     * @throws Exception an execution error occurred
     */
    private static Method createMethodAndCacheIt(Method[] methodsCache, Class<?> targetType, String methodName,
            Class<?>[] parameterTypes) throws Exception {

        if (methodsCache == null) {
            methodsCache = new Method[4];
        }

        Method method = targetType.getMethod(methodName, parameterTypes);

        if (methodName.equals(INIT_METHOD)) {
            methodsCache[INIT] = method;
        } else if (methodName.equals(DESTROY_METHOD)) {
            methodsCache[DESTROY] = method;
        } else if (methodName.equals(SERVICE_METHOD)) {
            methodsCache[SERVICE] = method;
        } else if (methodName.equals(DOFILTER_METHOD)) {
            methodsCache[DOFILTER] = method;
        } else if (methodName.equals(EVENT_METHOD)) {
            methodsCache[EVENT] = method;
        } else if (methodName.equals(DOFILTEREVENT_METHOD)) {
            methodsCache[DOFILTEREVENT] = method;
        }

        classCache.put(targetType, methodsCache);

        return method;
    }


    /**
     * Remove the object from the cache.
     *
     * @param cachedObject The object to remove
     */
    public static void remove(Object cachedObject) {
        classCache.remove(cachedObject);
    }


    /**
     * Return the <code>SecurityManager</code> only if Security is enabled AND package protection mechanism is enabled.
     *
     * @return <code>true</code> if package level protection is enabled
     */
    public static boolean isPackageProtectionEnabled() {
        if (packageDefinitionEnabled && Globals.IS_SECURITY_ENABLED) {
            return true;
        }
        return false;
    }


}