都部份的網站上都有讓使用者輸入資訊的元件,這些元件也常常被駭客視為攻擊的途徑,所以為了防止駭客使用XSS(Cross-site scripting,跨站指令碼攻擊)的方式攻擊網站,而XSS的攻擊方式就是利用元件置入程式碼來取得資訊或權限,所以使用者輸入的資訊必需做一定的控管,通常是將輸入內容中出現的程式碼移除或取代。

底下的程式碼就是將輸入的字串中出現的Script、Style、HTML或其它語法移除掉,是利用正規表示法尋找並取代,如果想要的結果不是移除而是取代的話,只要在replaceAll("")中加入想取代的值就行了。

public String removeTag(String str){
		Pattern p_script, p_style, p_html, p_special;
		Matcher m_script, m_style, m_html, m_special;

		//script
		String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>";
		p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
		m_script = p_script.matcher(str);
		str = m_script.replaceAll("");
		
		//style
		String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>";
		p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
		m_style = p_style.matcher(str);
		str = m_style.replaceAll("");
		
		//HTML
		String regEx_html = "<[^>]+>";
		p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
		m_html = p_html.matcher(str);
		str = m_html.replaceAll("");
		
		//special case
		String regEx_special = "\\&[a-zA-Z]{1,10};";
		p_special = Pattern.compile(regEx_special, Pattern.CASE_INSENSITIVE);
		m_special = p_special.matcher(str);
		str = m_special.replaceAll("");
		
		return str;
	}
 
arrow
arrow
    全站熱搜

    taurus770423 發表在 痞客邦 留言(0) 人氣()