001/*
002 * Copyright (c) 2009 The openGion Project.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
013 * either express or implied. See the License for the specific language
014 * governing permissions and limitations under the License.
015 */
016package org.opengion.hayabusa.filter;
017
018import java.io.File;                                                    // 5.7.3.2 (2014/02/28) Tomcat8 対応
019import java.io.BufferedReader;
020import java.io.FileInputStream;
021import java.io.IOException;
022import java.io.InputStreamReader;
023import java.io.PrintWriter;
024import java.io.UnsupportedEncodingException;
025
026import javax.servlet.Filter;
027import javax.servlet.FilterChain;
028import javax.servlet.FilterConfig;
029import javax.servlet.ServletContext;
030import javax.servlet.ServletException;
031import javax.servlet.ServletRequest;
032import javax.servlet.ServletResponse;
033import javax.servlet.http.HttpServletRequest;
034
035import org.opengion.fukurou.security.HybsCryptography;
036import org.opengion.fukurou.util.Closer;
037import org.opengion.fukurou.util.StringUtil;
038import org.opengion.hayabusa.common.HybsSystem;
039
040/**
041 * URLCheckFilter は、Filter インターフェースを継承した URLチェッククラスです。
042 * web.xml で filter 設定することにより、該当のリソースに対して、og:linkタグで、
043 * useURLCheck="true"が指定されたリンクURL以外を拒否することができます。
044 * また、og:linkタグを経由した場合でも、リンクの有効期限を設定することで、
045 * リンクURLの漏洩に対しても、一定時間の経過を持って、アクセスを拒否することができます。
046 * また、リンク時にユーザー情報も埋め込んでいますので(初期値は、ログインユーザー)、
047 * リンクアドレスが他のユーザーに知られた場合でも、アクセスを拒否することができます。
048 * 
049 * システムリソースの「URL_CHECK_CRYPT」で暗号復号化のキーを指定可能です。
050 * 指定しない場合はデフォルトのキーが利用されます。
051 * キーの形式はHybsCryptographyに従います。
052 *
053 * フィルターに対してweb.xml でパラメータを設定します。
054 *   ・filename :停止時メッセージ表示ファイル名
055 *   ・ignoreURL:暗号化されたURLのうち空白に置き換える接頭文字列を指定します。
056 *                      外部からアクセスしたURLがロードバランサで内部向けURLに変換されてチェックが動作しないような場合に
057 *                      利用します。https://wwwX.のように指定します。通常は設定しません。
058 *
059 * 【WEB-INF/web.xml】
060 *     <filter>
061 *         <filter-name>URLCheckFilter</filter-name>
062 *         <filter-class>org.opengion.hayabusa.filter.URLCheckFilter</filter-class>
063 *         <init-param>
064 *             <param-name>filename</param-name>
065 *             <param-value>jsp/custom/refuseAccess.html</param-value>
066 *         </init-param>
067 *     </filter>
068 *
069 *     <filter-mapping>
070 *         <filter-name>URLCheckFilter</filter-name>
071 *         <url-pattern>/jsp/*</url-pattern>
072 *     </filter-mapping>
073 *
074 * @og.group フィルター処理
075 *
076 * @version  4.0
077 * @author   Hiroki Nakamura
078 * @since    JDK5.0,
079 */
080public final class URLCheckFilter implements Filter {
081
082//      private static final HybsCryptography HYBS_CRYPTOGRAPHY = new HybsCryptography(); // 4.3.7.0 (2009/06/01)
083        private static final HybsCryptography HYBS_CRYPTOGRAPHY 
084                                                = new HybsCryptography( HybsSystem.sys( "URL_CHECK_CRYPT" ) ); // 5.8.8.0 (2015/06/05)
085
086        private String  filename  = null;                       // アクセス拒否時メッセージ表示ファイル名
087//      private int             maxInterval = 3600;                     // リンクの有効期限
088        private boolean  isDebug         = false;
089        private boolean  isDecode        = true;                // 5.4.5.0(2012/02/28) URIDecodeするかどうか
090        
091        private String          ignoreURL       = null; //5.8.6.1 (2015/04/17) 飛んできたcheckURLから取り除くURL文字列
092        private String          ommitURL        = null; // 5.10.11.0 (2019/05/03) URLチェックを行わないURLの正規表現
093        private String          ommitReferer    = null; // 5.10.11.0 (2019/05/03) URLチェックを行わないドメイン
094        
095        private String encoding = "utf-8";      // 5.10.12.4 (2019/06/21) 日本語対応
096
097        /**
098         * フィルター処理本体のメソッドです。
099         * 
100         * @ob.re 5.10.12.4 (2019/06/21) 日本語対応(encoding指定)
101         *
102         * @param       request         ServletRequestオブジェクト
103         * @param       response        ServletResponseオブジェクト
104         * @param       chain           FilterChainオブジェクト
105         * @throws ServletException サーブレット関係のエラーが発生した場合、throw されます。
106         */
107        public void doFilter( final ServletRequest request, final ServletResponse response, final FilterChain chain ) throws IOException, ServletException {
108                request.setCharacterEncoding(encoding); // 5.10.12.1 (2019/06/21)
109                
110                if( !isValidAccess( request ) ) {
111                        BufferedReader in = null ;
112                        try {
113                                response.setContentType( "text/html; charset=UTF-8" );
114                                PrintWriter out = response.getWriter();
115                                in = new BufferedReader( new InputStreamReader(
116                                                                new FileInputStream( filename ) ,"UTF-8" ) );
117                                String str ;
118                                while( (str = in.readLine()) != null ) {
119                                        out.println( str );
120                                }
121                                out.flush();
122                        }
123                        catch( UnsupportedEncodingException ex ) {
124                                String errMsg = "指定されたエンコーディングがサポートされていません。[UTF-8]" ;
125                                throw new RuntimeException( errMsg,ex );
126                        }
127                        catch( IOException ex ) {
128                                String errMsg = "ストリームがオープン出来ませんでした。[" + filename + "]" ;
129                                throw new RuntimeException( errMsg,ex );
130                        }
131                        finally {
132                                Closer.ioClose( in );
133                        }
134                        return;
135                }
136                
137                request.setAttribute( "RequestEncoding", encoding ); // 5.10.12.1 (2019/06/21) リクエスト変数で送信しておく
138
139                chain.doFilter(request, response);
140        }
141
142        /**
143         * フィルターの初期処理メソッドです。
144         *
145         * フィルターに対してweb.xml で初期パラメータを設定します。
146         *   ・maxInterval:リンクの有効期限
147         *   ・filename   :停止時メッセージ表示ファイル名
148         *   ・decode     :URLデコードを行ってチェックするか(初期true)
149         *
150         * @og.rev 5.4.5.0 (2102/02/28)
151         * @og.rev 5.7.3.2 (2014/02/28) Tomcat8 対応。getRealPath( "/" ) の互換性のための修正。
152         * @og.rev 5.8.6.1 (2015/04/17) DMZのURL変換対応
153         * @og.rev 5.10.11.0 (2019/05/03) ommitURL,ommitReferer
154         * @og.rev 5.10.12.4 (2019/06/21) encoding
155         *
156         * @param filterConfig FilterConfigオブジェクト
157         */
158        public void init(final FilterConfig filterConfig) {
159                ServletContext context = filterConfig.getServletContext();
160//              String realPath = context.getRealPath( "/" );
161                String realPath = context.getRealPath( "" ) + File.separator;           // 5.7.3.2 (2014/02/28) Tomcat8 対応
162
163//              maxInterval = StringUtil.nval( filterConfig.getInitParameter("maxInterval"), maxInterval );
164                filename  = realPath + filterConfig.getInitParameter("filename");
165                isDebug = StringUtil.nval( filterConfig.getInitParameter("debug"), false );
166                isDecode = StringUtil.nval( filterConfig.getInitParameter("decode"), true ); // 5.4.5.0(2012/02/28)
167                ignoreURL = filterConfig.getInitParameter("ignoreURL"); // 5.8.6.1 (2015/04/17)
168                ommitURL = filterConfig.getInitParameter("ommitURL"); // 5.10.11.0 (2019/05/03) 
169                ommitReferer = filterConfig.getInitParameter("ommitReferer"); // 5.10.11.0 (2019/05/03) 
170                encoding = StringUtil.nval( filterConfig.getInitParameter("encoding"), encoding ); // 5.10.12.4 (2019/06/21)
171        }
172
173        /**
174         * フィルターの終了処理メソッドです。
175         *
176         */
177        public void destroy() {
178                // ここでは処理を行いません。
179        }
180
181        /**
182         * フィルターの内部状態をチェックするメソッドです。
183         *
184         * @og.rev 5.4.5.0 (2012/02/28) Decode
185         * @og.rev 5.8.8.2 (2015/07/17) マルチバイト対応追加
186         *
187         * @param request ServletRequestオブジェクト
188         *
189         * @return      (true:許可  false:拒否)
190         */
191        private boolean isValidAccess( final ServletRequest request ) {
192                String checkKey = request.getParameter( HybsSystem.URL_CHECK_KEY );
193                // 5.10.11.0 (2019/05/03) データ取得位置変更
194                String queryStr = ((HttpServletRequest)request).getQueryString();
195                String reqStr =  ((HttpServletRequest)request).getRequestURL().toString();
196                String referer = ((HttpServletRequest)request).getHeader("REFERER");
197                
198                // 5.10.11.0 referer判定追加
199                // 入っている場合はtrueにする。
200                if(referer != null && ommitReferer != null && referer.indexOf( ommitReferer ) >= 0 ) {
201                        if( isDebug ) {
202                                System.out.println("URLCheck ommitRef"+reqStr);
203                        }
204                        return true;
205                }
206                
207                // リクエスト変数をURLに追加
208                reqStr = reqStr + (queryStr != null ? "?" + queryStr : "");
209                
210                // 5.10.11.0 ommitURL追加
211                // ommitに合致する場合はtrueにする。
212                if(ommitURL != null && reqStr.matches( ommitURL )) {
213                        if( isDebug ) {
214                                System.out.println("URLCheck ommitURL"+reqStr);
215                        }
216                        return true;
217                }
218                
219                if( checkKey == null || checkKey.length() == 0 ) {
220                        if( isDebug ) {
221                                System.out.println( "  check NG [ No Check Key ]" );
222                        }
223                        return false;
224                }
225
226                boolean rtn = false;
227                try {
228                        checkKey = HYBS_CRYPTOGRAPHY.decrypt( checkKey ).replace( "&", "&" );
229
230                        if( isDebug ) {
231                                System.out.println( "checkKey=" + checkKey );
232                        }
233
234                        String url = checkKey.substring( 0 , checkKey.lastIndexOf( ",time=") );
235                        long time = Long.parseLong( checkKey.substring( checkKey.lastIndexOf( ",time=") + 6, checkKey.lastIndexOf( ",userid=" ) ) );
236                        String userid = checkKey.substring( checkKey.lastIndexOf( ",userid=") + 8 );
237                        // 4.3.8.0 (2009/08/01)
238                        String[] userArr = StringUtil.csv2Array( userid );
239                        
240                        // 5.8.6.1 (2015/04/17)ignoreURL対応
241                        if( ignoreURL!=null && ignoreURL.length()>0 && url.indexOf( ignoreURL ) == 0 ){
242                                url = url.substring( ignoreURL.length() );
243                        }
244
245                        if( isDebug ) {
246                                System.out.println( " [ignoreURL]=" + ignoreURL ); // 2015/04/17 (2015/04/17)
247                                System.out.println( " [url]    =" + url );
248                                System.out.println( " [vtime]  =" + time );
249                                System.out.println( " [userid] =" + userid );
250                        }
251
252                        
253                        // 5.4.5.0 (2012/02/28) URLDecodeを行う
254                        if(isDecode){
255                                if( isDebug ) {
256                                        System.out.println( "[BeforeURIDecode]="+reqStr );
257                                }
258                                reqStr = StringUtil.urlDecode( reqStr );
259                                url = StringUtil.urlDecode( url ); // 5.8.8.2 (2015/07/17)
260                        }
261                        reqStr = reqStr.substring( 0, reqStr.lastIndexOf( HybsSystem.URL_CHECK_KEY ) -1 );
262                        //      String reqStr =  ((HttpServletRequest)request).getRequestURL().toString();
263                        String reqUser = ((HttpServletRequest)request).getRemoteUser();
264
265                        if( isDebug ) {
266                                System.out.println( " [reqURL] =" + reqStr );
267                                System.out.println( " [ctime]  =" + System.currentTimeMillis() );
268                                System.out.println( " [reqUser]=" + reqUser );
269                        }
270
271                        if( reqStr.endsWith( url )
272//                                      && System.currentTimeMillis() - time < maxInterval * 1000
273                                        && System.currentTimeMillis() - time < 0
274//                                      && userid.equals( reqUser ) ) {
275                                        && userArr != null && userArr.length > 0 ) {
276                                // 4.3.8.0 (2009/08/01)
277                                for( int i=0; i<userArr.length; i++ ) {
278                                        if( "*".equals( userArr[i] ) || reqUser.equals( userArr[i] ) ) {
279                                                rtn = true;
280                                                if( isDebug ) {
281                                                        System.out.println( "  check OK" );
282                                                }
283                                                break;
284                                        }
285                                }
286                        }
287                }
288                catch( RuntimeException ex ) {
289                        if( isDebug ) {
290                                String errMsg = "チェックエラー。 "
291                                                        + " checkKey=" + checkKey
292                                                        + " " + ex.getMessage();                        // 5.1.8.0 (2010/07/01) errMsg 修正
293                                System.out.println( errMsg );
294                                ex.printStackTrace();
295                        }
296                        rtn = false;
297                }
298                return rtn;
299        }
300
301        /**
302         * 内部状態を文字列で返します。
303         *
304         * @return      このクラスの文字列表示
305         */
306        @Override
307        public String toString() {
308                StringBuilder sb = new StringBuilder();
309                sb.append( "UrlCheckFilter" );
310//              sb.append( "[" ).append( maxInterval ).append( "],");
311                sb.append( "[" ).append( filename  ).append( "],");
312                return (sb.toString());
313        }
314}