camioljoyce
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # 用JAVA Filter 修改XSS攻擊的漏洞 [參考網站](https://www.gushiciku.cn/pl/p54d/zh-tw) 首先需要引入JAR檔 ``` <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>3.0-alpha-1</version> <scope>provided</scope> </dependency> ``` 需要建立這些檔案 ![](https://i.imgur.com/sKz66DK.jpg) 建立Filter ```java=\ package inspector.online.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; public class XssFilter implements Filter { @Override public void destroy() { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { // 使用包裝器 XSSRequestWrapper XSSRequestWrapper = new XSSRequestWrapper((HttpServletRequest) servletRequest); filterChain.doFilter(XSSRequestWrapper, servletResponse); } @Override public void init(FilterConfig filterConfig) throws ServletException { } } ``` 建立Wrapper ```java=\ package inspector.online.filter; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import org.apache.commons.lang3.StringUtils; public class XSSRequestWrapper extends HttpServletRequestWrapper { public XSSRequestWrapper(HttpServletRequest request) { super(request); } // 對陣列引數進行特殊字元過濾 @Override public String[] getParameterValues(String name) { String[] values = super.getParameterValues(name); if (values == null) { return null; } int count = values.length; String[] encodedValues = new String[count]; for (int i = 0; i < count; i++) { encodedValues[i] = clearXss(values[i]); } return encodedValues; } // 對引數中特殊字元進行過濾 @Override public String getParameter(String name) { String value = super.getParameter(name); if (value == null) { return null; } return clearXss(value); } // 覆蓋getParameterMap方法,將引數名和引數值都做xss & sql過濾 【一般post表單請求,或者前臺接收為實體需要這樣處理】 @SuppressWarnings({"rawtypes", "unchecked"}) @Override public Map getParameterMap() { Map<String, Object> paramMap = new HashMap<String, Object>(); Map<String, String[]> requestMap = super.getParameterMap(); Iterator<Entry<String, String[]>> it = requestMap.entrySet().iterator(); while (it.hasNext()) { Entry<String, String[]> entry = it.next(); if (entry.getValue().length == 1) { paramMap.put(xssEncode(entry.getKey()), xssEncode(entry.getValue()[0])); } else { String[] values = entry.getValue(); String value = ""; for (int i = 0; i < values.length; i++) { value = values[i] + ","; } value = value.substring(0, value.length() - 1); paramMap.put(xssEncode(entry.getKey()), xssEncode(entry.getValue()[0])); } } return paramMap; } // 獲取attribute, 特殊字元過濾 @Override public Object getAttribute(String name) { Object value = super.getAttribute(name); if (value != null && value instanceof String) { clearXss((String) value); } return value; } // 對請求頭部進行特殊字元過濾 @Override public String getHeader(String name) { String value = super.getHeader(name); if (value == null) { return null; } return clearXss(value); } //特殊字元處理(轉義或刪除) private String clearXss(String value) { if (StringUtils.isEmpty(value)) { return value; } // 字元編碼不一致,需要轉換。我們系統是UTF-8編碼,這裡不需要 /* * try { value = new String(value.getBytes("ISO8859-1"), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } */ return XssFilterUtil.stripXss(value); } //將容易引起xss漏洞的半形字元直接替換成全形字元 在保證不刪除資料的情況下儲存 private static String xssEncode(String value) { if (value == null || value.isEmpty()) { return value; } value = value.replaceAll("eval\\((.*)\\)", ""); value = value.replaceAll("<", "&lt;"); value = value.replaceAll(">", "&gt;"); value = value.replaceAll("'", "&apos;"); value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\""); value = value.replaceAll("(?i)<script.*?>.*?<script.*?>", ""); value = value.replaceAll("(?i)<script.*?>.*?</script.*?>", ""); value = value.replaceAll("(?i)<.*?javascript:.*?>.*?</.*?>", ""); value = value.replaceAll("(?i)<.*?\\s+on.*?>.*?</.*?>", ""); // value = value.replaceAll("[<>{}\\[\\];\\&]",""); return value; } } ``` 建立Util ```java=\ package inspector.online.filter; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; public class XssFilterUtil { private static final Logger log = Logger.getLogger(XssFilterUtil.class); private static List<Pattern> patterns = null; /** * @Title: XSS常見攻擊 * @methodName: getXssPatternList * @Description: Pattern.MULTILINE(? m):在這種模式下,'^'和'$'分別匹配一行的開始和結束。此外,'^'仍然匹配字串的開始,'$'也匹配字串的結束。 預設情況下,這兩個表示式僅僅匹配字串的開始和結束。 * <p> * Pattern.DOTALL(?s) :在這種模式下,表示式'.'可以匹配任意字元,包括表示一行的結束符。 預設情況下,表示式'.'不匹配行的結束符。 */ private static List<Object[]> getXssPatternList() { List<Object[]> ret = new ArrayList<Object[]>(); ret.add(new Object[] {"<(no)?script[^>]*>.*?</(no)?script>", Pattern.CASE_INSENSITIVE}); ret.add(new Object[] {"</script>", Pattern.CASE_INSENSITIVE}); ret.add(new Object[] {"<script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL}); ret.add(new Object[] {"eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL}); ret.add(new Object[] {"expression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL}); ret.add(new Object[] {"(javascript:|vbscript:|view-source:)*", Pattern.CASE_INSENSITIVE}); ret.add(new Object[] {"<(\"[^\"]*\"|\'[^\']*\'|[^\'\">])*>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL}); ret.add(new Object[] {"(window\\.location|window\\.|\\.location|document\\.cookie|document\\.|alert\\(.*?\\)|window\\.open\\()*", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL}); ret.add(new Object[] { "<+\\s*\\w*\\s*(oncontrolselect|oncopy|oncut|ondataavailable|ondatasetchanged|ondatasetcomplete|ondblclick|ondeactivate|ondrag|ondragend|ondragenter|ondragleave|ondragover|ondragstart|ondrop|onerror=|onerroupdate|onfilterchange|onfinish|onfocus|onfocusin|onfocusout|onhelp|onkeydown|onkeypress|onkeyup|onlayoutcomplete|onload|onlosecapture|onmousedown|onmouseenter|onmouseleave|onmousemove|onmousout|onmouseover|onmouseup|onmousewheel|onmove|onmoveend|onmovestart|onabort|onactivate|onafterprint|onafterupdate|onbefore|onbeforeactivate|onbeforecopy|onbeforecut|onbeforedeactivate|onbeforeeditocus|onbeforepaste|onbeforeprint|onbeforeunload|onbeforeupdate|onblur|onbounce|oncellchange|onchange|onclick|oncontextmenu|onpaste|onpropertychange|onreadystatechange|onreset|onresize|onresizend|onresizestart|onrowenter|onrowexit|onrowsdelete|onrowsinserted|onscroll|onselect|onselectionchange|onselectstart|onstart|onstop|onsubmit|onunload)+\\s*=+", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL}); return ret; } // XSS常見攻擊-正則表示式 private static List<Pattern> getPatterns() { if (patterns == null) { List<Pattern> list = new ArrayList<Pattern>(); String regex = null; Integer flag = null; int arrLength = 0; for (Object[] arr : getXssPatternList()) { arrLength = arr.length; for (int i = 0; i < arrLength; i++) { regex = (String) arr[0]; flag = (Integer) arr[1]; list.add(Pattern.compile(regex, flag)); } } patterns = list; } return patterns; } // 處理特殊字元 public static String stripXss(String value) { if (StringUtils.isNotBlank(value)) { log.info("【XSS攻擊防禦】,接收字元是:" + value); Matcher matcher = null; for (Pattern pattern : getPatterns()) { matcher = pattern.matcher(value); // 匹配 if (matcher.find()) { // 刪除相關字串 value = matcher.replaceAll(""); } } log.info("【XSS攻擊防禦】,匹配正則是:" + matcher + ",處理後是:" + value); /** * 替換為轉移字元,類似HtmlUtils.htmlEscape */ // value = value.replaceAll("<", "&lt;").replaceAll(">", "&gt;"); // 刪除特殊符號 // String specialStr = "%20|=|!=|-|--|;|'|\"|%|#|+|//|/| |\\|<|>|(|)|{|}"; if (StringUtils.isNotBlank(value)) { String specialStr = "%20|=|!=|-|--|;|'|\"|%|#|[+]|//|/| |\\|<|>|(|)|{|}"; for (String str : specialStr.split("\\|")) { if (value.indexOf(str) > -1) { value = value.replaceAll(str, ""); } } log.info("【XSS攻擊防禦】,特殊符號處理後是:" + value); } } return value; } } ``` 最後在web.xml加上過濾器 ```xml <!-- 解決xss漏洞 --> <filter> <filter-name>xssFilter</filter-name> <filter-class>inspector.online.filter.XssFilter</filter-class> </filter> <filter-mapping> <filter-name>xssFilter</filter-name> <!--過濾路徑 --> <url-pattern>*</url-pattern> </filter-mapping> <!-- 解決xss漏洞 --> ``` --- 如果要跟struts2整合在一起的話 web.xml要改成這樣 ```xml <!-- struts2 start --> <filter> <filter-name>struts2</filter-name> <!-- <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> --> <filter-class>inspector.online.filter.XssFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- struts2 end --> ``` 把原本的struts2 filter 的class註解掉,改成自己的 然後把自己寫的XssFilter 去繼承StrutsPrepareAndExecuteFilter ```java= package inspector.online.filter; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter; public class XssFilter extends StrutsPrepareAndExecuteFilter { /** * 改寫 Filter 功能,使用新的 request 物件傳遞 */ @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { // 直接呼叫原有的方式,僅將 request 替換成 處理 xss 之 Request System.out.println("XssFilter doFilter"); super.doFilter(new XSSRequestWrapper((HttpServletRequest) req), res, chain); } } ``` 用postman去測試時,即可看到攻擊代碼被轉換掉了 ![](https://i.imgur.com/2pdseXH.jpg) ###### tags: `XSS`

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully