Web Security Grammar Knowledge Tutorial

The difference between getRequestDispatcher and sendRedirect

125         String url = req.getRequestURL().toString();
126    
127         RequestDispatcher disp = req.getRequestDispatcher(url.substring(url.lastIndexOf("WebGoat/")

Among them, getRequestDispatcher is the internal jump of the server, and the information in the address bar is unchanged. It can only jump to the webpage in the web application.
And sendRedirect is a page redirection, the address bar information changes, you can jump to any webpage.


Xpath injection

37      sb.append("/Employees/Employee [Managers/Manager/text()='" + userId + "']/Salary ");
39      String expression = sb.toString();  
40      System.out.print("expression:" + expression);
41      nodes = (NodeList) xPath.evaluate(expression, inputSource,XPathConstants.NODESET); //sink点

The evaluate () method evaluates an XPath expression and returns an Xpathresult object.

SQL injection

Why can the preparedstatement in java prevent sql injection?
Using preparedstatement will precompile the structure of sql to the database. As far as JDBC is concerned, SQL injection attacks are only valid for Statements, but not for PreparedStatements. This is because PreparedStatement does not allow changing the logical structure of the query at different insertion times.


List result = query.list () // What does source mean?
Hibernate's HQL statement returns a QUery object, converts the Query object query into a collection, and assigns the collection to a new collection. The result will be regarded as untrusted data, because it is impossible to determine whether the data in the database comes from user input.

The difference between execute, executeUpdate and executeQuery (and return value) // sink
1. ResultSet executeQuery (String sql); execute SQL query and return ResultSet object.
2.int executeUpdate (String sql); Can add, delete, modify, and return the number of rows affected by execution.
3. boolean execute (String sql); can execute any SQL statement and return a Boolean value indicating whether to return a ResultSet.

stmt.executeUpdate (String sql) is the method
executeUpdate (String sql) in the Statement interface to
execute the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement, or a SQL statement that does not return anything, if the sql statement contains untrusted The data may cause problems such as SQL injection.


Is the data read by BufferedReader.readline () untrusted?

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), UTF8));
String s = br.readLine() //sink

BufferedReader.readline () generally reads data from a file, and data obtained from a database, file, or other container is not considered safe data.
Therefore, if s is used directly in the SQL statement, it may cause problems such as SQL injection.

104     public Boolean executeSQL(String sql) {
105         try {
106             String[]s=sql.split(Constants.ONESQL_PREFIX);
107             for(String sqls:s){
108                 if(StringUtils.isNotBlank(sqls)){
109                     getJdbcTemplate().execute(sqls.trim());   //sink
110                 }

The knowledge derived from getJdbcTemplate (). execute The
Spring JDBC framework provides the following template classes to simplify JDBC programming, such as JdbcTemplate.

JdbcTemplate mainly provides the following five types of methods:
execute (): can be used to execute any SQL statement, generally used to execute DDL statements;
update () and batchUpdate (): update method is used to execute new, modified and deleted statements; The method is used to execute batch related statements;
query () and queryForXXX (): used to execute query related statements;
call (): used to execute stored procedure, function related statements.

/** 
     * 预编译语句设值回调使用 
     * 通过JdbcTemplate的int update(String sql, PreparedStatementSetter pss)执行预编译sql 
     */  
    public void preparedStatementSql() {  
        String sql = "insert into tab_item values(?,?,?)";  
        int row = getJdbcTemplate().update(sql, new PreparedStatementSetter() {  
            @Override  
            public void setValues(PreparedStatement ps) throws SQLException {  
                ps.setInt(1, 101);// JDBC占位符集合的序号是从1开始的,而不是0  
                ps.setObject(2, "Apple");  
                ps.setString(3, "Ipad4");  
            }  
        });  
        Assert.isTrue(row == 1, "插入失败");  

        // JdbcTemplate也提供一种更简单的方式设值相应的占位符位置的值  
        sql = "delete from tab_item where id = ?";  
        row = getJdbcTemplate().update(sql, new Object[] { 101 });  
        Assert.isTrue(row == 1, "删除失败");  
    }

sqls.trim ()
The TRIM function in SQL is used to remove the beginning or end of a string. The most common use is to remove blank prefix or suffix
example:

SELECT TRIM('   Sample   ');

result:

'Sample'

String sqls: s
gets all sql statements in s


12     import org.apache.struts.action.ActionForm;

249     public ActionForward toHVPSRecvPZPPrint(ActionMapping mapping,
250             ActionForm form, HttpServletRequest request,
251             HttpServletResponse response) throws Exception {
252    
253         PS pps = (PS) this.getBean("PS");
255         PForm voform = (PForm) form;
256         PEntity ppe = voform.getPo();   //sink
            ...
261         Systemusersmanage user = (Systemusersmanage) request.getSession()
262                 .getAttribute("userentity");
263         ppe.setPrinter(user.getUsername());
            ...
268         List list = pps.queryBatchPZHvps(ppe);

The Struts framework uses ActionForm objects to temporarily store the form data in the view page. ActionForm is used to encapsulate the user's request parameters, and the request parameters are passed through the form field of the JSP page, so the value of voform.getPo () comes from untrusted sources.

import com.ban.form.systemManage.SystemorganizationscustomForm;

    buf.append(" AND Number='"+ systemOrganizationscustomForm.getBankNumber() + "'"); //sink

systemOrganizationscustomForm.getBankNumber () This place introduces insecure data, which was really not seen at first. Later, after carefully looking at the code, I discovered that systemOrganizationscustomForm inherited from ActionForm.

A.java
public class BaseActionForm extends ActionForm {
}

B.java
public class SystemorganizationsmanageForm extends BaseActionForm {
}


Cross-site scripting

response.getWriter () The response information is output to the web page through the out object, and it is automatically closed when the response ends.

50          ServletOutputStream out = response.getOutputStream();
51          out.write(file.getContent());

Output the acquired data to the page;
if the data contains tainted data, it may cause cross-site scripting. The content should be output encoded before output.

The difference between System.out.println () and out.println () in JSP
out.println () is output to the client.
In out.println (), out is an instance of response, which uses response as the object for stream output, that is, the content is output to the client. If you use System.out.println () in a JSP page, only a space will be output on the client.

System.out.println () is printed in the console.
System.out.println () uses the standard output stream, which is output on the console, and JSP is not a console program. Whether in a JSP or JAVA program, System.out.println () is printed on the console. If you want to print on the page, the simple way is:
out.print ("What to print");

entity = (T) getSession().get(getEntityClass(), id) //source

This is the hibernate api, hibernate is a framework for operating the database. Data obtained from databases, files, or other containers are not considered safe data. Therefore, if the data of the entity is directly passed to the page, it may cause problems such as cross-site scripting. The content should be output encoded before output.

XML external entity injection

164             inputSource = new InputSource(is);
165             entity = (CommonXMLEntity) unmar.unmarshal(inputSource);  //sink

unmarshal () is the method that transforms the xml object into the java object we need. To avoid XXE injection, do not use unmarshal methods that directly process XML sources as java.io.File, java.io.Reader or java.io.InputStream.
To prevent the injection of XML external entities:
1. Use the method provided by the development language to disable external entities

PHP:

libxml_disable_entity_loader(true);


JAVA:

DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();

dbf.setExpandEntityReferences(false);


Python:

from lxml import etree

xmlData = etree.parse(xmlSource,etree.XMLParser(resolve_entities=False))

2. Filter XML data submitted by users

关键词:<!DOCTYPE和<!ENTITY,或者,SYSTEMPUBLIC


in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
...
in.readFully(inb, 0, len);  //source
String recven = rb.getString("recven").trim();
returnString = new String(inb, recven);

in.readFully (inb, 0, len) is also regarded as an untrusted data source, the original problem lies in in itself.


File leak

The program receives untrusted data and uses its construction server to switch to the path used, which may result in viewing any file in the protected directory, or even downloading the binary code or jar file of the application.
If used by hackers, they "http://www.yourcorp.com/webApp/logic?returnURL=WEB-INF /applicationContext.xml"will be able to view the applicationContext.xml file of the application.


Suggestion for repair: Avoid constructing server redirection path through user input. When unavoidable, untrusted user input should be verified. You can also create a legal list of safe strings, restricting users to enter only the data in the list.


Several usages of super


------------------------------
在Java中,有时还会遇到子类中的成员变量或方法与超类(有时也称父类)中的成员变量或方法同名。因为子类中的成员变量或方法名优先级高,所以子类中的同名成员变量或方法就隐藏了超类的成员变量或方法,但是我们如果想要使用超类中的这个成员变量或方法,就需要用到super.
-----------------------------
class Country {
    String name;

    void value() {
       name = "China";
    }
}

class City extends Country {
    String name;

    void value() {
    name = "Hefei";
    super.value();//不调用此方法时,super.name返回的是父类的成员变量的值null
       System.out.println(name);
       System.out.println(super.name);
    }

    public static void main(String[] args) {
       City c=new City();
       c.value();
       }
}



------------------------------
用super直接传递参数:
------------------------------
public class Chinese extends Person {
....
    Chinese() {
       super(); // 调用父类构造函数(1)
       prt("A chinese.");// (4)
    }

    Chinese(String name) {
       super(name);// 调用父类具有相同形参的构造函数(2)
       prt("his name is:" + name);
    }
}

Denial of service

readInt input stream is read in an integer meaning
non-integer input if an exception is thrown. When the read data is too large, it may cause denial of service and other attacks.

34     int len = readInt();  //source
...
200    while ((i = read(ba, 2 + bytesRead, len - bytesRead)) > -1  //sink


The getInitParameter () method is a newly defined method in the GenericServlet interface, which is used to call the initialized parameters stored in web.xml. Generally, we write servlets using the HttpServlet class. It implements the GenericServlet interface, so it has getInitParameter () method. The calling format is:

String name = getInitParameter(“name”); 或
String name = getServletConfig().getInitParameter(“name”);

Example:

160    String dbStr = getInitParameter("hsqldb.server.database");  //source


The function of Integer.getInteger (String) is to get the integer value of the system property according to the specified name. The first parameter will be considered the name of the system property, which can be accessed through the System.getProperty (java.lang.String) method. The attribute value string will be interpreted as an integer and returned as an Integer object representing this value.

1513   retries = Integer.getInteger(HsqlDatabaseProperties.system_lockfile_poll_retries_property,
retries).intValue();   //source




HTTP message header injection

String attchmntnm = request.getParameter("attchmntnm");  //source
response.setHeader("*****","attachment;filename=\""+attchmntnm+"\""); //sink
http://www.normal.com/somepage.php?page=%0d%0aContent-type:text/html%0d%0aHTTP/1.1 200 OK%0d%0aContent-Type:text/html%0d%0a%0d%0%3Chtml%3EHacker Content%3C/html%3E
Published 30 original articles · Like 13 · Visits 100,000+

Guess you like

Origin blog.csdn.net/u013224189/article/details/49620295