View Javadoc
1   /*
2    * $Id$
3    *
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *  http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  package org.apache.struts.util;
22  
23  import java.nio.charset.StandardCharsets;
24  import java.security.MessageDigest;
25  import java.security.NoSuchAlgorithmException;
26  
27  import org.apache.struts.Globals;
28  
29  import jakarta.servlet.http.HttpServletRequest;
30  import jakarta.servlet.http.HttpSession;
31  
32  /**
33   * TokenProcessor is responsible for handling all token related functionality.
34   * The methods in this class are synchronized to protect token processing from
35   * multiple threads.  Servlet containers are allowed to return a different
36   * HttpSession object for two threads accessing the same session so it is not
37   * possible to synchronize on the session.
38   *
39   * @since Struts 1.1
40   */
41  public class TokenProcessor {
42      /**
43       * The singleton instance of this class.
44       */
45      private static TokenProcessor instance = new TokenProcessor();
46  
47      /**
48       * The timestamp used most recently to generate a token value.
49       */
50      private long previous;
51  
52      /**
53       * Protected constructor for TokenProcessor.  Use TokenProcessor.getInstance()
54       * to obtain a reference to the processor.
55       */
56      protected TokenProcessor() {
57          super();
58      }
59  
60      /**
61       * Retrieves the singleton instance of this class.
62       */
63      public static TokenProcessor getInstance() {
64          return instance;
65      }
66  
67      /**
68       * <p>Return <code>true</code> if there is a transaction token stored in
69       * the user's current session, and the value submitted as a request
70       * parameter with this action matches it.  Returns <code>false</code>
71       * under any of the following circumstances:</p>
72       *
73       * <ul>
74       *
75       * <li>No session associated with this request</li>
76       *
77       * <li>No transaction token saved in the session</li>
78       *
79       * <li>No transaction token included as a request parameter</li>
80       *
81       * <li>The included transaction token value does not match the transaction
82       * token in the user's session</li>
83       *
84       * </ul>
85       *
86       * @param request The servlet request we are processing
87       */
88      public synchronized boolean isTokenValid(HttpServletRequest request) {
89          return this.isTokenValid(request, false);
90      }
91  
92      /**
93       * Return <code>true</code> if there is a transaction token stored in the
94       * user's current session, and the value submitted as a request parameter
95       * with this action matches it.  Returns <code>false</code>
96       *
97       * <ul>
98       *
99       * <li>No session associated with this request</li> <li>No transaction
100      * token saved in the session</li>
101      *
102      * <li>No transaction token included as a request parameter</li>
103      *
104      * <li>The included transaction token value does not match the transaction
105      * token in the user's session</li>
106      *
107      * </ul>
108      *
109      * @param request The servlet request we are processing
110      * @param reset   Should we reset the token after checking it?
111      */
112     public synchronized boolean isTokenValid(HttpServletRequest request,
113         boolean reset) {
114         // Retrieve the current session for this request
115         HttpSession session = request.getSession(false);
116 
117         if (session == null) {
118             return false;
119         }
120 
121         // Retrieve the transaction token from this session, and
122         // reset it if requested
123         String saved =
124             (String) session.getAttribute(Globals.TRANSACTION_TOKEN_KEY);
125 
126         if (saved == null) {
127             return false;
128         }
129 
130         if (reset) {
131             this.resetToken(request);
132         }
133 
134         // Retrieve the transaction token included in this request
135         String token = request.getParameter(Globals.TOKEN_KEY);
136 
137         if (token == null) {
138             return false;
139         }
140 
141         return saved.equals(token);
142     }
143 
144     /**
145      * Reset the saved transaction token in the user's session.  This
146      * indicates that transactional token checking will not be needed on the
147      * next request that is submitted.
148      *
149      * @param request The servlet request we are processing
150      */
151     public synchronized void resetToken(HttpServletRequest request) {
152         HttpSession session = request.getSession(false);
153 
154         if (session == null) {
155             return;
156         }
157 
158         session.removeAttribute(Globals.TRANSACTION_TOKEN_KEY);
159     }
160 
161     /**
162      * Save a new transaction token in the user's current session, creating a
163      * new session if necessary.
164      *
165      * @param request The servlet request we are processing
166      */
167     public synchronized void saveToken(HttpServletRequest request) {
168         HttpSession session = request.getSession();
169         String token = generateToken(request);
170 
171         if (token != null) {
172             session.setAttribute(Globals.TRANSACTION_TOKEN_KEY, token);
173         }
174     }
175 
176     /**
177      * Generate a new transaction token, to be used for enforcing a single
178      * request for a particular transaction.
179      *
180      * @param request The request we are processing
181      */
182     public synchronized String generateToken(HttpServletRequest request) {
183         HttpSession session = request.getSession();
184 
185         return generateToken(session.getId());
186     }
187 
188     /**
189      * Generate a new transaction token, to be used for enforcing a single
190      * request for a particular transaction.
191      *
192      * @param id a unique Identifier for the session or other context in which
193      *           this token is to be used.
194      */
195     public synchronized String generateToken(String id) {
196         try {
197             long current = System.currentTimeMillis();
198 
199             if (current == previous) {
200                 current++;
201             }
202 
203             previous = current;
204 
205             byte[] now = String.valueOf(current).getBytes(StandardCharsets.US_ASCII);
206             MessageDigest md = MessageDigest.getInstance("SHA-256");
207 
208             md.update(id.getBytes());
209             md.update(now);
210 
211             return toHex(md.digest());
212         } catch (NoSuchAlgorithmException e) {
213             return null;
214         }
215     }
216 
217     /**
218      * Convert a byte array to a String of hexadecimal digits and return it.
219      *
220      * @param buffer The byte array to be converted
221      */
222     private String toHex(byte[] buffer) {
223         StringBuilder sb = new StringBuilder(buffer.length * 2);
224 
225         for (int i = 0; i < buffer.length; i++) {
226             sb.append(Character.forDigit((buffer[i] & 0xf0) >> 4, 16));
227             sb.append(Character.forDigit(buffer[i] & 0x0f, 16));
228         }
229 
230         return sb.toString();
231     }
232 }