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        /**
096         * フィルター処理本体のメソッドです。
097         *
098         * @param       request         ServletRequestオブジェクト
099         * @param       response        ServletResponseオブジェクト
100         * @param       chain           FilterChainオブジェクト
101         * @throws ServletException サーブレット関係のエラーが発生した場合、throw されます。
102         */
103        public void doFilter( final ServletRequest request, final ServletResponse response, final FilterChain chain ) throws IOException, ServletException {
104
105                if( !isValidAccess( request ) ) {
106                        BufferedReader in = null ;
107                        try {
108                                response.setContentType( "text/html; charset=UTF-8" );
109                                PrintWriter out = response.getWriter();
110                                in = new BufferedReader( new InputStreamReader(
111                                                                new FileInputStream( filename ) ,"UTF-8" ) );
112                                String str ;
113                                while( (str = in.readLine()) != null ) {
114                                        out.println( str );
115                                }
116                                out.flush();
117                        }
118                        catch( UnsupportedEncodingException ex ) {
119                                String errMsg = "指定されたエンコーディングがサポートされていません。[UTF-8]" ;
120                                throw new RuntimeException( errMsg,ex );
121                        }
122                        catch( IOException ex ) {
123                                String errMsg = "ストリームがオープン出来ませんでした。[" + filename + "]" ;
124                                throw new RuntimeException( errMsg,ex );
125                        }
126                        finally {
127                                Closer.ioClose( in );
128                        }
129                        return;
130                }
131
132                chain.doFilter(request, response);
133        }
134
135        /**
136         * フィルターの初期処理メソッドです。
137         *
138         * フィルターに対してweb.xml で初期パラメータを設定します。
139         *   ・maxInterval:リンクの有効期限
140         *   ・filename   :停止時メッセージ表示ファイル名
141         *   ・decode     :URLデコードを行ってチェックするか(初期true)
142         *
143         * @og.rev 5.4.5.0 (2102/02/28)
144         * @og.rev 5.7.3.2 (2014/02/28) Tomcat8 対応。getRealPath( "/" ) の互換性のための修正。
145         * @og.rev 5.8.6.1 (2015/04/17) DMZのURL変換対応
146         * @og.rev 5.10.11.0 (2019/05/03) ommitURL,ommitReferer
147         *
148         * @param filterConfig FilterConfigオブジェクト
149         */
150        public void init(final FilterConfig filterConfig) {
151                ServletContext context = filterConfig.getServletContext();
152//              String realPath = context.getRealPath( "/" );
153                String realPath = context.getRealPath( "" ) + File.separator;           // 5.7.3.2 (2014/02/28) Tomcat8 対応
154
155//              maxInterval = StringUtil.nval( filterConfig.getInitParameter("maxInterval"), maxInterval );
156                filename  = realPath + filterConfig.getInitParameter("filename");
157                isDebug = StringUtil.nval( filterConfig.getInitParameter("debug"), false );
158                isDecode = StringUtil.nval( filterConfig.getInitParameter("decode"), true ); // 5.4.5.0(2012/02/28)
159                ignoreURL = filterConfig.getInitParameter("ignoreURL"); // 5.8.6.1 (2015/04/17)
160                ommitURL = filterConfig.getInitParameter("ommitURL"); // 5.10.11.0 (2019/05/03) 
161                ommitReferer = filterConfig.getInitParameter("ommitReferer"); // 5.10.11.0 (2019/05/03) 
162        }
163
164        /**
165         * フィルターの終了処理メソッドです。
166         *
167         */
168        public void destroy() {
169                // ここでは処理を行いません。
170        }
171
172        /**
173         * フィルターの内部状態をチェックするメソッドです。
174         *
175         * @og.rev 5.4.5.0 (2012/02/28) Decode
176         * @og.rev 5.8.8.2 (2015/07/17) マルチバイト対応追加
177         *
178         * @param request ServletRequestオブジェクト
179         *
180         * @return      (true:許可  false:拒否)
181         */
182        private boolean isValidAccess( final ServletRequest request ) {
183                String checkKey = request.getParameter( HybsSystem.URL_CHECK_KEY );
184                // 5.10.11.0 (2019/05/03) データ取得位置変更
185                String queryStr = ((HttpServletRequest)request).getQueryString();
186                String reqStr =  ((HttpServletRequest)request).getRequestURL().toString();
187                String referer = ((HttpServletRequest)request).getHeader("REFERER");
188                
189                // 5.10.11.0 referer判定追加
190                // 入っている場合はtrueにする。
191                if(referer != null && ommitReferer != null && referer.indexOf( ommitReferer ) >= 0 ) {
192                        if( isDebug ) {
193                                System.out.println("URLCheck ommitRef"+reqStr);
194                        }
195                        return true;
196                }
197                
198                // リクエスト変数をURLに追加
199                reqStr = reqStr + (queryStr != null ? "?" + queryStr : "");
200                
201                // 5.10.11.0 ommitURL追加
202                // ommitに合致する場合はtrueにする。
203                if(ommitURL != null && reqStr.matches( ommitURL )) {
204                        if( isDebug ) {
205                                System.out.println("URLCheck ommitURL"+reqStr);
206                        }
207                        return true;
208                }
209                
210                if( checkKey == null || checkKey.length() == 0 ) {
211                        if( isDebug ) {
212                                System.out.println( "  check NG [ No Check Key ]" );
213                        }
214                        return false;
215                }
216
217                boolean rtn = false;
218                try {
219                        checkKey = HYBS_CRYPTOGRAPHY.decrypt( checkKey ).replace( "&", "&" );
220
221                        if( isDebug ) {
222                                System.out.println( "checkKey=" + checkKey );
223                        }
224
225                        String url = checkKey.substring( 0 , checkKey.lastIndexOf( ",time=") );
226                        long time = Long.parseLong( checkKey.substring( checkKey.lastIndexOf( ",time=") + 6, checkKey.lastIndexOf( ",userid=" ) ) );
227                        String userid = checkKey.substring( checkKey.lastIndexOf( ",userid=") + 8 );
228                        // 4.3.8.0 (2009/08/01)
229                        String[] userArr = StringUtil.csv2Array( userid );
230                        
231                        // 5.8.6.1 (2015/04/17)ignoreURL対応
232                        if( ignoreURL!=null && ignoreURL.length()>0 && url.indexOf( ignoreURL ) == 0 ){
233                                url = url.substring( ignoreURL.length() );
234                        }
235
236                        if( isDebug ) {
237                                System.out.println( " [ignoreURL]=" + ignoreURL ); // 2015/04/17 (2015/04/17)
238                                System.out.println( " [url]    =" + url );
239                                System.out.println( " [vtime]  =" + time );
240                                System.out.println( " [userid] =" + userid );
241                        }
242
243                        
244                        // 5.4.5.0 (2012/02/28) URLDecodeを行う
245                        if(isDecode){
246                                if( isDebug ) {
247                                        System.out.println( "[BeforeURIDecode]="+reqStr );
248                                }
249                                reqStr = StringUtil.urlDecode( reqStr );
250                                url = StringUtil.urlDecode( url ); // 5.8.8.2 (2015/07/17)
251                        }
252                        reqStr = reqStr.substring( 0, reqStr.lastIndexOf( HybsSystem.URL_CHECK_KEY ) -1 );
253                        //      String reqStr =  ((HttpServletRequest)request).getRequestURL().toString();
254                        String reqUser = ((HttpServletRequest)request).getRemoteUser();
255
256                        if( isDebug ) {
257                                System.out.println( " [reqURL] =" + reqStr );
258                                System.out.println( " [ctime]  =" + System.currentTimeMillis() );
259                                System.out.println( " [reqUser]=" + reqUser );
260                        }
261
262                        if( reqStr.endsWith( url )
263//                                      && System.currentTimeMillis() - time < maxInterval * 1000
264                                        && System.currentTimeMillis() - time < 0
265//                                      && userid.equals( reqUser ) ) {
266                                        && userArr != null && userArr.length > 0 ) {
267                                // 4.3.8.0 (2009/08/01)
268                                for( int i=0; i<userArr.length; i++ ) {
269                                        if( "*".equals( userArr[i] ) || reqUser.equals( userArr[i] ) ) {
270                                                rtn = true;
271                                                if( isDebug ) {
272                                                        System.out.println( "  check OK" );
273                                                }
274                                                break;
275                                        }
276                                }
277                        }
278                }
279                catch( RuntimeException ex ) {
280                        if( isDebug ) {
281                                String errMsg = "チェックエラー。 "
282                                                        + " checkKey=" + checkKey
283                                                        + " " + ex.getMessage();                        // 5.1.8.0 (2010/07/01) errMsg 修正
284                                System.out.println( errMsg );
285                                ex.printStackTrace();
286                        }
287                        rtn = false;
288                }
289                return rtn;
290        }
291
292        /**
293         * 内部状態を文字列で返します。
294         *
295         * @return      このクラスの文字列表示
296         */
297        @Override
298        public String toString() {
299                StringBuilder sb = new StringBuilder();
300                sb.append( "UrlCheckFilter" );
301//              sb.append( "[" ).append( maxInterval ).append( "],");
302                sb.append( "[" ).append( filename  ).append( "],");
303                return (sb.toString());
304        }
305}