You are on page 1of 381

1

1
        
  Zero Day   (SW)    
   . 2011     Sony  
SQL .

ICT     ,    
         
     . , 
          
.
          

. ,   , SW     ,  
       ,     
.

2
    ( "" )  
, SW 

.

2 SW 
SW  SW   ,     SW 
, SW
  .   SW  SW (SDLC, SW Development
Lifecycle)      ,   SW 
     (Secure Coding)'
.
 ,      
 Zero Day ,       ,   SW
.  , 
75%(, SW).

: , Now is the time for security at Application Level(2005. 12.)

      ,    
           .
, 
.
      (XSS)  SQL 
   (, SW)     ,  SW
       . ,   
, SW 
.

SW       ,  
. , 8
.

: , 15(2009. 4.)


, 
.

SW 
     . ,     
 (DB) ,      
  . ,      SW
()   ,     
.
SW 
, 30
. , 
30. , 20

.
< SW >

5
1

10
10
1

15
20
10

30
30
20

[ : The Economic Impacts of Inadequate Infrastructure for Software Testing, 2002.5, NIST]

, , 
           . ,
          
, 
.

3 SW 
CWE1), CWE/SANS Top252), OWASP Top103),
CERT4)         ,

.
   ,    , API   
 7 ,     .   
CWE    7 Pernicious Kingdoms5)     
SW .
   :

      

.

XSS,

SQL , , .
API : API, API
. gets(), J2EE: System.exit().
gets(), 

: (, , , ,   ) 
. , , 
.
  :        ,   
         . 
(dead lock), , .
: 
. , 
.
:    , ,   SW
, ()
. .
: 
    .     
, .
1) Common Weakness Enumeration, http://cwe.mitre.org
2) CWE/SANS TOP 25 Most Dangerous Software Errors, http://www.sans.org
3) Open Web Application Security Project, http://www.owasp.org
4) Computer Emergency Response Team, http://www.cert.org
5) Seven Pernicious Kingdoms: A Taxonomy of Software Security Errors, IEEE Security and Privacy Magazine, Vol.3, No.6, 2005, pp.81-84.

1 
. 
        
,         
.
        XSS, SQL , HTTP 
, , , , LDAP , 
,  .

1. (XSS)
. 
()
, 
. (
, ,  )     , 
, .

. 

.
.
(URI).
.
.
.

.
, 
ReplaceAll().

. 
- HTML

1:
2:
3:
4:
5:

<h1>XSS Sample</h1>
<%
String name = request.getParameter("name");
%>
<p>NAME:<%=name%></p>

- HTML
1:

<%

2:

String name = request.getParameter("name");

3:

if ( name != null ) {

4:

name = name.replaceAll("<","&lt;");

5:

name = name.replaceAll(">","&gt;");

6:

name = name.replaceAll("&","&amp;");

7:
8:

name = name.replaceAll("","&quot;");
} else { return; }

9:
%>
(name) <script>alert    replaceAll() 

(document.cookie);</script>  javascript <, >, &, " " 


,  &lt, &gt, &amp, &quot,
.

(name).

2. SQL
. 
DB 
() DB, 
SQL SQL
.

. 

SQL Injection 


SQL Injectionxx' OR 1=1--' xx OR 1=1
.

.
SQL , 
.
preparedStatement executeQuery(), execute(),
executeUpdate().



. 
SQL SQL Query

. SQL .
- JAVA
1:

try {

2:

String

tableName

- JAVA

String

try {

2:

String

props.getProperty("jdbc.tableName");
3:

1:

props.getProperty("jdbc.name");

String

name

props.getProperty("jdbc.name");
4:

String query = "SELECT * FROM " + ta-

4:

props.getProperty("jdbc.tableName");
3:

name

tableName

String query = "SELECT

* FROM

bleName + " WHERE Name =" + name;

5:

stmt = con.prepareStatement(query);

5:

stmt = con.prepareStatement(query);

6:

stmt.setString(1, tableName);

6:

rs = stmt.executeQuery();

7:

stmt.setString(2, name);

7:

... ...

8:

rs = stmt.executeQuery();

8:

} catch (SQLException sqle) {

9:

... ...

9:

finally {

WHERE Name = ? ";

10:

} catch (SQLException sqle) {

11: finally {
}
  tableName name PreparedStatement

SQL   , name     ,

 

"name' OR 'a'='a"  setXXX() , 


.

.

- C
1:
2:
3:
4:
5:

void U51000089_1(SQLHSTMT sqlh)


{
char *query = getenv("query_string");
SQLExecDirect(sqlh, query, SQL_NTS);
}

- C
1:
2:
3:
4:
5:

void S51000089_1(SQLHSTMT sqlh)


{
char *query_items = "SELECT * FROM items";
SQLExecDirect(sqlh, query_items, SQL_NTS);
}

SQL  


, "name' OR 'a'='a"    SQL Injection 
WHERE .

SQL  JDO(Java Data Objects) SQL    JDO API SQL


JDOQL 
. SQL JDO
.



- JAVA
try {

1:

- JAVA
1:

2:

Properties props = new

3:

String fileName =

4:

FileInputStream in = new FileInputStream(fileName);

5:

if( in != null ) {

6:

in.close();

7:

String name = props.getProperty("name"); 6:

name = props.getProperty("name");

8:

if( name != null ) {

if (name == null || "".equals(name)) return null;

9:

query += " where name = '" + name + "'"; 8:

2:

Properties props = new Properties();

3:

String fileName = "contacts.txt";

4:

props.load(in); }

}
return (List<Contact>)

FileInputStream

in

new

FileInputStream(fileName);
5:

} catch (IOException e) {

11:
13:

"contacts.txt";

10:
12:

Properties();

try {

7:

props.load(in);

query += " where name = ?";


} catch (IOException e) {

9:
10:

11:

javax.jdo.Query q = pm.newQuery(query);

12:

return (List<Contact>) q.execute(name);

13: }
pm.newQuery(query).execute();
  (name)  "name';
   ? (Parameterize
DELETE FROM MYTABLE; --" ,
Query), 
.
  (name)  
(SELECT col1 FROM MYTABLE WHERE name
.
= 'name' ; DELETE FROM MYTABLE; --')

SQL PersistenceJava SQL 


J2EE Persistence API
.



- JAVA

- JAVA
1:

try {

1:

props

new 3:

Properties();

4:

String fileName = "conditions.txt";

3:

FileInputStream

4:

in

5:

props.load(in);

6:

String id =

7:

Query query =

new 5:

props.getProperty("id");
OBJECT(i) 9:
+

id);

10:

return r_type;

10:

in

new

String id = props.getProperty("id");
if

(id

==

null

||

"".equals(id))

id

Query query =
em.createNativeQuery("SELECT

OBJECT(i)

FROM Item i WHERE i.itemID > :id");

List<U9103> items = query.getResultList(); 11:

9:

FileInputStream

"itemid";
8:

FROM Item i WHERE i.itemID > "

"conditions.txt";

props.load(in);

6:
7:

em.createNativeQuery("SELECT

Properties();

String fileName =

FileInputStream(fileName);

FileInputStream(fileName);

8:

Properties props = new

2:

Properties

2:

try {

query.setParameter("id", id);
List<S9103>

items

query.getResultList();

12:

return r_type;

13:

  (id)  "foo';

DELETE FROM MYTABLE; --" , (query), 


.   .    

(SELECT col1 FROM MYTABLE WHERE name .


= 'foo' ; DELETE FROM MYTABLE; --')

SQL mybatis Data MapSQL 

.
- XML
1:

<!DOCTYPE

sqlMap

PUBLIC

"-//iBATIS.com//DTD SQL Map 2.0//EN"

- XML
1:

<?xml version="1.0"

2:

<!DOCTYPE

... ...

3:

<!-- dynamic SQL -->

4:

<delete id="delStudent"
Class="Student">

5:

DELETE STUDENTS

6:

WHERE NUM = #num# AND Name =


'$name$'

7:

"http://www.ibatis.com/dtd/sql-map-2.dtd">
3:

parameter-

</delete>

PUBLIC

"-//iBATIS.com//DTD SQL Map 2.0//EN"

"http://www.ibatis.com/dtd/sql-map-2.dtd">
2:

encoding="UTF-8"?>
sqlMap

... ...

4:

<!-- static SQL -->

5:

<delete

id="delStudent"

parameter-

Class="Student">
6:
7:

DELETE STUDENTS
WHERE NUM = #num# AND Name =
'#name#'

8:

</delete>

 delStudent 
 $name$
    
.  name "' OR 'x'='x'"

Name #name# .

    
.



3. HTTP 
. 
HTTP HTTP 
CR(Carriage Return)LF(Line Feed)HTTP
2. 
XSS (cache poisoning) .

. 

HTTP HTTP 
HTTP .

.
HTTP (Set Cookie )CR,
LF.



. 
- JAVA

- JAVA

1:

throws IOException, ServletException {

2:

response.setContentType("text/html");

3:

String author = request.getParameter("authorName");

4:

Cookie

cookie

cookie.setMaxAge(1000);

6:

response.addCookie(cookie);

7:

RequestDispatcher

new

response.setContentType("text/html");

3:

String

frd

frd.forward(request, response);

4:

if (author == null || "".equals(author)) return;

5:

String filtered_author = author.replaceAll("\r",


"").replaceAll("\n",

"");

Cookie cookie = new Cookie("replidedAuthor",

7:

cookie.setMaxAge(1000);

8:

cookie.setSecure(true);

9:

response.addCookie(cookie);

10:

RequestDispatcher

frd

request.getRequestDispatcher("cookie-

9:

author

filtered_author);

Test.jsp");

10:

2:

6:

request.getRequestDispatcher("cookie8:

throws IOException, ServletException {

request.getParameter("authorName");

Cookie("replidedAuthor", author);
5:

1:

Test.jsp");

frd.forward(request, response);

11:

12:
13:


 .

 "Wiley  Null

Hacker\r\nHTTP/1.1 200 OK\r\n" author- ,      reName,  lpaceAll  (\r, \n) 


,  .
.



4. 
. 

. ,
, 
.

. 


, User Memory(18Bytes)
.

.
.
.
.
(bounds checking).
strcpy().

. 
(, )

.



- C

- C
1:

void manipulate_string(char* string) {


char buf[24];

2:

void manipulate_string(char* string) {

1:

3:

/* buf. */
if (strlen(string < sizeof(buf))

2:

char buf[24];

4:

3:

ctrcpy(buf, string);

5:

4:

6:

5:

7:

    
, strcpy() 
. 

.

strncpy(buf, string, sizeof(buf)-1);


/* null*/
buf[sizeof(buf)-1] = '\0';

8:

9:

(string) buf
 . strncpy()   
 buf  , buf  

'\0'.

(, malloc() )


, 
.

- C

- C

1:

#include <stdio.h>

1:

#include <stdio.h>

2:

#include <stdlib.h>

2:

#include <stdlib.h>

3:

#include <string.h>

3:

#include <string.h>

4:

#define BUFSIZE 10

4:

#define BUFSIZE 10

5:

int main(char **argv)

5:

int main(int argc, char **argv)

6:

6:

7:

char *dest = NULL;

7:

char *dest = NULL;

8:

dest = (char *)malloc(BUFSIZE);

8:

dest = (char *)malloc(BUFSIZE);

9:

9:

10:

strcpy(dest, argv[1]);

10:

strlcpy(dest, argv[1], BUFSIZE);

11:

11:

12:

free(dest);

12:

free(dest);

13:

return 0;

13:

return 0;

}
14: }

  (string)  buf
, strcpy() 
. strncpy() 
  .  
buf, buf

'\0'.
.
14:



5. 
. 

, 
.  (.., / )

.

. 

../../../rootFile.txt
"/usr/local/tmp/rootFile.txt
. "/usr/local/tmp/rootFile.txt
.

.
. 
, replaceAll() 
(",/,\).

. 

 . ,  .. . 

.



- JAVA

1:

public void f(Properties request) {

2:

String name = request.getProperty("filename");

3:

if( name != null ) {

4:

File file = new File("/usr/local/tmp/" + name);


file.delete();

5:

6:
7:

- JAVA
1:

public void f(Properties request) {

2:

String name = request.getProperty("user");

3:

if ( name != null && !"".equals(name) ) {

4:

name = name.replaceAll("/", "");

5:

name = name.replaceAll("\\", "");

6:

name = name.replaceAll(".", "");

7:

name = name.replaceAll("&", "");

8:

name = name + "-report";

9:

File file = new File("/usr/local/tmp/" +


name);

10:

if (file != null)

11:

file.delete();

12:

}
 Null
13:

name../../../rootFile.txt

.

,   (name)
(/, \\, &, . )re-

placeAll.

- C
1:

void f()

2:

3:

char* rName = getenv("reportName");

4:

char buf[30];

5:

strncpy(buf, "/home/www/tmp/", 30);

6:

strncat(buf, rName, 30);

7:

unlink(buf);

8:
}
reportName    

 /home/www/tmp   
, reportName ../../../etc/passwd


- C
1:

void f()

2:

3:

char buf[30];

4:

strncpy(buf, "/home/www/tmp/", 30);

5:

strncat(buf, "report", 30);


unlink(buf);

6:
7:


.

.



, 
. 

.
- JAVA

- JAVA
1:

public

void

f(Properties

cfg)

throws

IOException {
2:
1:

public

void

f(Properties

cfg)

throws 3:

IOException {
FileInputStream

2:

4:

fis

FileInputStream fis;
String subject = cfg.getProperty("subject");
if (subject.equals("math"))

new 5:

FileInputStream(cfg.getProperty("subject"));

fis = new FileInputStream("math");


else if (subject.equals("physics"))

6:

3:

byte[] arr = new byte[30];

7:

4:

fis.read(arr);

8:

5:

System.out.println(arr);

9:

6:

10:

else fis = new FileInputStream("default");

11:

byte[] arr = new byte[30];

12:

fis.read(arr);

7:

fis = new FileInputStream("physics");


else if (subject.equals("chemistry"))
fis = new FileInputStream("chemistry");

System.out.println(arr);

13:

14:

 (fis)    

, 

, 
.
.

- C
1:

void f()

2:

3:

char* rName = getenv("reportName");

4:

unlink(rName);

5:
}
reportName 


.



- C
1:

void f()

2:

{
unlink("/home/www/tmp/report");

3:
4:


.

6. 
. 
         
. 
(, )
.

. 

.
.
.

.
.

.



. 
- JAVA

- JAVA
1:

1:

2:

props.load(in);

3:

String version[] = {"1.0", "1.1"};

4:

int

props.load(in);

3:

String version = props.getProperty("dir_type");

String cmd = new String("cmd.exe /K

5:

\"rmanDB.bat \"");

String cmd = new String("cmd.exe 6:


/K

\"rmanDB.bat \"");

String vs = "";
if (versionSelection == 0)

7:

Runtime.getRuntime().exec(cmd

5:

Integer.parseInt(props.getProperty("version"));

2:
4:

versionSelection

" 8:

c:\\prog_cmd\\" + version);

9:

6:

10:

7:

11:

vs = version[0];
else if (versionSelection == 1)
vs = version[1];
else
vs = version[1];

12:

Runtime.getRuntime().exec(cmd

13:

"

c:\\prog_cmd\\" + vs);

14:

cmd.exe

rmanDB.bat   , 
 dir_type  manDB.bat
, 

, dir_type,


, 
, 
.



- C
1:

- C

1:

2:

fgets(arg,80,stdin);

3:

commandLength

strlen(cat)

command

4:

(char

*)

5:

strncpy(command, cat, commandLength);

6:

strncat(command,

9:

return 0;


, 
.



7:

commandLength = strlen(cat) + strlen(arg) + 1;


if(commandLength < 20) {
command

9:

system(command);

exit(1);

6:

argv[1], 8:

(commandLength - strlen(cat)) );
8:

if (strpbrk(arg,";\"'."))
{

mal- 5:

loc(commandLength);

7:

fgets(arg,80,stdin);

+ 3:

strlen(arg) + 1;
4:

2:

(char

*)

mal-

loc(commandLength);
10:
11:

strpbrk()      
.

7. LDAP
. 
LDAP . 
, LDAP 
, Authentication
.

. 

LDAP*
.

.
LDAP , (white list) 
(black list= + < > # ; \ ),
.



. 
- JAVA

1:

Properties props = new Properties();

2:

String fileName = "ldap.properties";

3:

FileInputStream

in

- JAVA
Properties props = new Properties();

2:

String fileName = "ldap.properties";

3:

FileInputStream in = new FileInputStream(fileName);

new 4:

FileInputStream(fileName);
props.load(in);

4:

1:

if (in == null || in.available() <= 0) return;

5:

props.load(in);

6:

if (props == null || props.isEmpty()) return;

5:

String name = props.getProperty("name");

7:

String name = props.getProperty("name");

6:

String filter = "(name =" + name + ")";

8:

if (name == null || "".equals(name)) return;

7:

NamingEnumeration
ctx.search("ou=NewHires",

answer

= 9:

filter,

new

String

filter

"(name

="

nam-

e.replaceAll("\\*", "") + ")";

SearchControls());

10:

NamingEnumeration answer =

8:

printSearchEnumeration(answer);

11:

ctx.search("ou=NewHires",

9:

ctx.close();

filter,

new

SearchControls());
printSearchEnumeration(answer);

12:

ctx.close();
 name  "*" 
13:

"(name=*)"      
.

.

- C

- C

1:

int main()

1:

int main()

2:

2:

3:

char* filter = getenv("filter_string");

3:

char* filter = "(manager=admin)";

4:

int rc;

4:

int rc;

5:

LDAP *ld = NULL;

5:

LDAP *ld = NULL;

6:

LDAPMessage* result;

6:

7:

rc

ldap_search_ext_s(ld,

rc

ldap_search_ext_s(

ld,

FIND_DN,

LDAP_SCOPE_BASE, filter, NULL, 0, NULL,

LDAP_SCOPE_BASE, filter, NULL, 0, NULL,

NULL,

NULL,

LDAP_NO_LIMIT,

LDAP_NO_LIMIT, &result);
8:

LDAPMessage* result;

FIND_DN, 7:

return 0;

LDAP_NO_LIMIT,

return 0;

8:

}
9:
  getenv()   LDAP
9:

LDAP_NO_LIMIT,

&result);
}

. 
 
   '|'  
.



8. 
. 
. , C
      1    
. 
.

. 

.

.
.
.

. 
- C

- C

1:

int main()

1:

int main()

2:

2:

3:

int i;

3:

int i;

4:

int sum = 0;

4:

int sum = 0;

5:

int buf[10];

5:

int buf[10];

6:

for(i=0; i < 10; i++)

6:

for(i = 0; i < 10; i++)

7:

7:

{
sum += i;

8:

sum += i;

8:

9:

9:

10:

sum = buf[i];

10:

sum = buf[i-1];

return 0;

11:

11:
12:

12:

return 0;
}

10 -1
.

.



9. 
. 


.

. 

URI

.

.
, 
(white list). , 
.



. 
- JAVA

- JAVA
1:

1:

String service = props.getProperty("Service No");


int port = Integer.parseInt(service);

2:

2:

props.load(in);

3:

service = props.getProperty("Service No");

4:

5:

if ("".equals(service)) service = "8080";


switch (port) {

7:

if (port != 0)

8:

4:

serverSocket = new ServerSocket(port + 3000);

9:

6:

int port = Integer.parseInt(service);

6:

3:

else

5:

if (in != null && in.available() > 0) {

case 1:
port = 3001; break;
case 2:

10:

serverSocket = new ServerSocket(def + 3000);

port = 3002; break;

11:

default:

12:

port = 3000;

13:

14:

serverSocket = new ServerSocket(port);

15:

16:

(service)
. ,  Service No 

-2920 80



.

- C

- C
1:

int main()

2:

1:

int main()

3:

char* rPort = getenv("rPort");

2:

4:

struct sockaddr_in serv_addr;

3:

char* rPort = getenv("rPort");

5:

int sockfd = 0;

4:

struct sockaddr_in serv_addr;

6:

char buf[25];

5:

int sockfd = 0;

7:

if(strcmp(rPort,"") < 0)

6:

char buf[25]

8:

7:

strcpy(buf, rPort, 25);

9:

if

(connect(sockfd,(struct

sockaddr 10:

*)&buf,sizeof(serv_addr)) < 0) {

11:

strncpy(buf, rPort, 25);

12:

if

8:

exit(1);

9:

10:

return 0;

11:
12:

printf("bad input");

}
(connect(sockfd,(struct

sockaddr

*)&buf,sizeof(serv_addr)) < 0) {
exit(1);

13:
14:

15:

return 0;

}
 
16:

getenv("rPort").  
.

.



2 API
API(Application Programming Interface)    
  ,  C, C++, JAVA, MFC    
       .  API  
  API        
.
API , J2EE: System.exit()
, Null , equals()hashCode()  .

1. 
. 
, 
. gets() 
.
gets() , 
. , .

. 

.
gets() .

. 
- C
#include <stdio.h>

1:

#include <stdio.h>

2:

#include <stdlib.h>

2:

#include <stdlib.h>

3:

#define BUFSIZE 100

3:

#define BUFSIZE 100

4:

void f() {

4:

void f() {

5:

char buf[BUFSIZE];

5:

6:

gets(buf);

6:

7:

gets().



- C

1:

7:

char buf[BUFSIZE];
fgets(buf, BUFSIZE, stdin);
}

gets() fgets() .

2. J2EE: System.exit()
. 
J2EE System.exit(). , 

Exception" ""

", J2EE System.exit() Multi-thread


J2EEJVM. , System.exit()

.

. 

J2EE System.exit().
System.exit(), .
System.exit()JVM.
.
JVM .

.
J2EE System.exit().



. 
- JAVA
1:

public class U382 extends


public

2:

void

- JAVA
1:

HttpServlet {

doPost(HttpServletRequest

request, HttpServletResponse response)


throws ServletException,

3:
4:

FileHandler

5:

Logger

IOException {

handler

new

FileHandler("errors.log");
logger

Logger.getLogger("com.mycompany");
6:

logger.addHandler(handler);

7:

try {

8:

do_something(logger);

9:

} catch (IOException ase) {


System.exit(1);

10:

11:
12:

2:

public class S382 extends


public

void

HttpServlet {

doPost(HttpServletRequest

request, HttpServletResponse response)


throws ServletException,

3:
4:

FileHandler

handler

IOException {
=

new

FileHandler("errors.log");
5:

Logger

logger

6:

logger.addHandler(handler);

7:

try {

Logger.getLogger("com.mycompany");

8:

do_something(logger);

9:

} catch (IOException ase) {

10:

logger.info("Caught:

12:

" + ase.toString());

// System.exit(1);

11:

13:
}
System.exit()   System.exit()   





.

3. Null 
. 
Java Object.equals(), Comparable.compareTo(), Comparator.compare()
null. 
.

. 

Null 
Object.equals(), Comparable.compareTo(), Comparator.compare()
Null .

.
Object.equals(), Comparable.compareTo()Comparator.compare()
Null .

. 
- JAVA
public class Test implements java.util.Comparator {
public int compare(Object o1, Object o2)
{
3:
int i1 = o1.hashCode();
4:
int i2 = o2.hashCode();
5:
int ret;
6:
if (i1 > i2)
{
ret = 1;
}
7:
else if (i1 == i2) {
ret = 0;
}
8:
else {
ret = -1;
}
9:
return ret;
10: }
1:
2:

null.

- JAVA
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:

public class Test implements java.util.Comparator {


public int compare(Object o1, Object o2)
{
int ret;
if (o1 != null && o2 != null) {
int i1 = o1.hashCode();
int i2 = o2.hashCode();
if (i1 > i2) {
ret = 1;
}
else if (i1 == i2) {
ret = 0;
}
else {
ret = -1;
}
} else
ret = -1;
return ret;
}

null .



4. equals()hashCode() 
. 
Java . "a.equals(b) ==
true" "a.hashCode() == b.hashCode()"  .     equals()
hashCode().

. 

equals()equals()
hashCode().

.
equals()hashCode()hashCode()
equals().

. 



1:

1:

public class Test {

2:

3:

public boolean equals(Object obj) {


boolean ret;

4:
5:
6:

7:

8:

public class Test {

2:

3:

public boolean equals(Object obj) {


boolean ret;

4:
5:

6:

public int hashCode() {


return new HashCodeBuilder(17,

7:

37).toHashCode();
8:

9:

}
Test  equal() hashCode() 
10:

Test equals() .



.

3
         .
, , , , .
      ,    ,
, , , 
 .

1. 
. 
, 
.
,      ,   
.

. 

. 
.

.
.
SW , "-" 
.



. 
- JAVA
1:

public

Connection DBConnect(String url,

String id) {
2:

try {

3:

conn = DriverManager.getConnection(url, id, "tiger");


} catch (SQLException e) {

4:

System.err.println("...");

5:

6:

1:

try {

2:

String url = props.getProperty("url");

3:

String id = props.getProperty("id");

4:

String pwd = props.getProperty("passwd");

5:

6:

byte[] decrypted_pwd =

7:

pwd = new String(decrypted_pwd);

cipher.doFinal(pwd.getBytes());

return conn;

7:

- JAVA

}
8:
conn = DriverManager.getConnection(url, id, pwd);
}
 
8:
9:

 , 
.

.

- C

- C
1:

int dbaccess(char *server, char *user, char


*passwd) {

1:

int dbaccess(char *server, char *user) {

2:

SQLHENV henv;

2:

SQLHENV henv;

3:

SQLHDBC hdbc;

3:

SQLHDBC hdbc;

4:

SQLAllocHandle(SQL_HANDLE_ENV,

SQLAllocHandle(SQL_HANDLE_ENV,

4:

SQL_NULL_HANDLE, &henv);

SQL_NULL_HANDLE, &henv);
5:

SQLAllocHandle(SQL_HANDLE_DBC,

5:

henv, &hdbc);
SQLConnect(hdbc,

6:

henv, &hdbc);
6:

(SQLCHAR*)

server,

strlen(server), user, strlen(user), "asdf", 4);

SQLAllocHandle(SQL_HANDLE_DBC,
SQLConnect(hdbc,

(SQLCHAR*)

server,

strlen(server), user, strlen(user), passwd,


7:

strlen(passwd) );

7:

return 0;

8:

SQLFreeHandle(SQL_HANDLE_DBC, hdbc);

8:

9:

SQLFreeHandle(SQL_HANDLE_ENV, henv);

10:

return 0;

}
, 
11:

asdf".

      
.



2. 
. 
(, , )
.

. 

, 
CSRF .
CSRF Script .
CSRF Script.
CSRF.

.
GET POST .
, 
URL 

. 
- HTML

-HTML

1:

2:

<form name="MyForm" method="get" ac- 2:

<form name="MyForm" method="post" ac-

tion="customer.do">

tion="customer.do">

3:

<input type=text name="txt1">

3:

<input type=text name="txt1">

4:

<input type=submit value=">"

4:

<input type=submit value=">"

5:

</form>

5:

</form>

1:

6:

6:
GET form  URL 

  GET  form
 CSRF 

Post .

.



3. 
. 

. 
(XSS) ID.

. 


.

.

.

. 
- JAVA
1:
2:

public class U613 extends HttpServlet {

- JAVA
1:

public void noExpiration(HttpSession 2:


session) {

public class S613 extends HttpServlet {


public

void

noExpiration(HttpSession

session) {

3:

if (session.isNew()) {

3:

if (session.isNew()) {

4:

session.setMaxInactiveInterval(-1);

4:

session.setMaxInactiveInterval(12000);

5:
6:

5:
6:

7:
}
7:
}
 -1,  

.  


.



.

- C

- C
1:

int

searchData2LDAP(LDAP

*ld,

char

*username, char *password) {

1:

int

searchData2LDAP(LDAP

*ld,

char

*username) {
2:

unsigned long rc;

3:

char filter[20];

4:

LDAPMessage *result;

5:

sizeof(filFIND_DN,

LDAP_SCOPE_BASE,

filter,

NULL,

LDAP_NO_LIMIT,

LDAP_NO_LIMIT, &result);
7:

return rc;

8:

4:

LDAPMessage *result

5:

if ( ldap_simple_bind_s(ld, username, password)


printf(");
return(FAIL);

7:

ldap_search_ext_s(ld,
NULL,

char filter[20];

!= LDAP_SUCCESS ) {

snprintf(filter,
rc

unsigned long rc;

3:

6:

ter),"(name=%s)",username);
6:

2:

NULL,

0,

8:

9:

if ( strcmp(username,getLoginName()) != 0 ) {
printf(");

10:

return(FAIL);

11:
12:

13:

snprintf(filter,

sizeof(filter),

"(name=%s)",

username);
14:

rc

ldap_search_ext_s(ld,

LDAP_SCOPE_BASE,
NULL,

NULL,

filter,

FIND_DN,
NULL,

0,

LDAP_NO_LIMIT,

LDAP_NO_LIMIT, &result);
15:

return rc;

}
LDAP  username user
16:

     LDAP 
.

.



4. 
. 

, .

. 

.

(attack surface).
ACL(Access Control List).
     .  , JAAS Authorization Framework
OWASP ESAPI Access Control .



. 
- JAVA
1:

- JAVA

public void f(String sSingleId, int iFlag, String


sServiceProvider, String sUid, String sPwd) {

2:
3:
4:

env.put(Context.INITIAL_CONTEXT_FAC 1:

public void f(String sSingleId, int iFlag, String

TORY, CommonMySingleConst.INITCTX);

sServiceProvider, String sUid, String sPwd) {

e n v . p u t ( C o n t e x t . P R O V I D E R _ U R L , 2:

env.put(Context.PROVIDER_URL, sServiceProvider);

sServiceProvider);

env.put(Context.SECURITY_AUTHENTICATIO

3:

env.put(Context.SECURITY_AUTHENTIC

5:
6:

N, "simple");
4:

env.put(Context.SECURITY_PRINCIPAL, sUid);

env.put(Context.SECURITY_PRINCIPAL, 5:

env.put(Context.SECURITY_CREDENTIALS,

sUid);

sPwd);

ATION, "none");

env.put(Context.SECURITY_CREDENTIALS

, sPwd);
name LDAP
, 
. IDpassword
anonymous binding. .

.

- C
1:

#define

- C

FIND_DN

"uid=han,ou=staff,dc=example,dc=com"
2:

int

searchData2LDAP(LDAP

*ld,

char

*username) {
unsigned long rc;

4:

char filter[20];

5:

LDAPMessage *result;
snprintf(filter,

sizeof(filter),

"(name=%s)",

username);
7:

rc

ldap_search_ext_s(ld,

FIND_DN,

LDAP_SCOPE_BASE,

filter,

NULL,

LDAP_NO_LIMIT,

NULL,

NULL,

0,

LDAP_NO_LIMIT, &result);
8:

9:

return rc;

}
, LDAP 
10:

if ( ldap_simple_bind_s(ld, username, password)


!= LDAP_SUCCESS ) {
printf(");

2:

return(FAIL);

3:

3:

6:

1:

4:

5:

if ( strcmp(username,getLoginName()) != 0 ) {
printf(");

6:

return(FAIL);

7:
8:

9:

snprintf(filter,

sizeof(filter),

"(name=%s)",

username);
10:

rc

ldap_search_ext_s(ld,

LDAP_SCOPE_BASE,
NULL,

NULL,

filter,

FIND_DN,
NULL,

0,

LDAP_NO_LIMIT,

LDAP_NO_LIMIT, &result);

.  LDAP username, username


username .
.



5. 
. 
(DES, MD5 ),
.

. 

 DES
.

.
, 
.
DES, RC5, 3DES, AES, SEED
.

. 
- JAVA
1:
2:
3:
4:
5:
6:

try {
Cipher c = Cipher.getInstance("DES");
c.init(Cipher.ENCRYPT_MODE, k);
rslt = c.update(msg);
}
catch (InvalidKeyException e) {

- JAVA
1:

try {

2:

Cipher c =
Cipher.getInstance("AES/CBC/PKCS5Padding");

3:

c.init(Cipher.ENCRYPT_MODE, k);

4:

rslt = c.update(msg);

6:

DES .

5:

catch (InvalidKeyException e) {

AES .

- C
1:

... ...

- C
1:

EVP_CIPHER_CTX ctx;

2:

EVP_CIPHER_CTX ctx;

3:

EVP_CIPHER_CTX_init(&ctx);

3:

EVP_CIPHER_CTX_init(&ctx);

4:

EVP_EncryptInit(&ctx, EVP_des_ecb(), NULL, 4:


NULL);

5:

... ...

DES .



... ...

2:

EVP_EncryptInit(&ctx,

EVP_aes_128_cbc(),

key, iv);
5:

... ...

AES .

6. 
. 

, 
.

. 

 ClientServer
, 
.

.

.

. 

1:
2:
3:
4:
5:
6:
7:
8:

void foo() {
try {
Socket socket = new Socket("taranis", 4444);
PrintWriter out = new PrintWriter
(socket.getOutputStream(), true);
String password = getPassword();
out.write(password);
} catch (FileNotFoundException e) {

(Plain text)
. 
.


1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:

void foo() {
try {
Socket socket = new Socket("taranis", 4444);
PrintStream out = new PrintStream
(socket.getOutputStream(), true);
Cipher c = Cipher.getInstance
("AES/CBC/PKCS5Padding");
String password = getPassword();
encryptedStr= c.update(password.getBytes());
out.write(encryptedStr,0,encryptedStr.length);
} catch (FileNotFoundException e) {


128.



4 
          
(   )    (   ) 
.
         , 
, J2EE  .

1. : 
. 
. 
. ,

.

. 

.
(: ), 
.
(EX : thread safe , 
C(mutex)JAVAsynchronized



. 
- JAVA

- JAVA

public class MyServlet extends HttpServlet {


String name;
public void doPost ( HttpRequestRequest
hreq, HttpResponceServlet hres ) {
4: name = hreq.getParameter("name");
5: }
HttpServetMyServletname
1:
2:
3:

1:
2:
3:
4:

public class MyServlet extends HttpServlet {


public void doPost ( HttpRequestRequest
hreq, HttpResponceServlet hres ) {
String name = hreq.getParameter("name");
}

 name MyServlet namedoPost 


 , .
.

- C

- C
1:

void file_operation(char* file)


{

1:

void file_operation(char* file)

2:

2:

3:

char *file_name;

3:

if(!access(file,W_OK))

4:

int fd;

4:

5:

5:

f = fopen(file,"w+");

6:

operate(f);

fd

open(

file_name,

O_WRONLY

O_CREAT | O_EXCL, S_IRWXU);


if (fd == -1) {

6:

7:

7:

8:

else {

8:

if (fchmod(fd, S_IRUSR) == -1)

9:

fprintf(stderr,"Unable

to

open

file 9:

%s.\n",file);
10:

access()     fopen() 


      

.

{
}

10:
11:

close(fd);

12:


, 
.  chmod  fchmod
fd.



2. 
. 

. , (base case)
.

. 

Func_A
.

.
.

. 
- JAVA

- JAVA

public int factorial(int n) {


int i;
if (n == 1) {
1:
i = 1;
2: public int factorial(int n) {
} else {
3:
return n * factorial(n - 1);
i = n * factorial(n - 1);
4: }
}
return i;
}
  /         
1:
2:
3:
4:
5:
6:
7:
8:
9:

.

- C
1:

int fac(n) {

2:

return n*fac(n-1);

3:

.



- C
1:

int fac(n) {

2:

if (n <= 0) return 1;

3:

else return n*fac(n-1);

}
      
4:

3. J2EE : 
. 
J2EE . 

. , , , .

. 


.

.
J2EE.

. 
- JAVA
1:

public class U383 extends HttpServlet {

2:

protected void doGet(HttpServletRequest


request, HttpServletResponse response)
throws ServletException, IOException {

3:

Runnable r = new Runnable() {

4:

public void run() {

5:

System.err.println("do
}

6:
7:
8:

something");

};
new Thread(r).start();

}
J2EE 

- JAVA

1:

public class S383 extends HttpServlet {

2:

protected

void

doGet(HttpServletRequest

request, HttpServletResponse response)


throws ServletException, IOException {
3:

// New MyClass().main();

4:

Runtime.getRuntime().exec("java AsyncClass");
}

5:
6:

9:

, , , 
.


.



5
() 
.
         
, .

1. 
. 
.
//9.

. 

, 
.

.
.
//9.

. 
- JAVA

- JAVA
1:

1:

try {

2:

String id = request.getParameter("id");

3:

String passwd = request.getParameter("passwd");

4:

} catch (SQLException e)

5:

try {

2:

String id = request.getParameter("id");

3:

String passwd = request.getParameter("passwd");

4:

if (passwd == null || "".equals(passwd))

5:

return;

6:

if (!passwd.matches("") &&
passwd.indexOf("@!#")

> 4 &&

passwd.length() > 8)
7:

} catch (SQLException e)

}
      
8:

.



.

2. 
. 
, , 
.

. 

, 
MS-SQL.

.
.

.
.

. 
- JAVA

- JAVA

1:

public static void main(String[] args) {

1:

public static void main(String[] args) {

2:

String urlString = args[0];

2:

String urlString = args[0];

3:

try{

3:

try{

4:

URL url = new URL(urlString);

4:

URL url = new URL(urlString);

5:

URLConnection cmx =

5:

URLConnection cmx =

6:

url.openConnection();

6:

url.openConnection();

7:

cmx.connect();

7:

cmx.connect();

8:

8:
9:

catch (Exception e)

9:

catch (Exception e)

10:

{ e.printStackTrace();

10:

{ System.out.println("");

11:

11:

}
12: }

.
.
12:



- C
1:

int main (int argc, char* argv[])

2:

3:

char* path=getenv("MYPATH");

4:

fprintf(stderr,path);

5:

return 0;

}
(MYAPTH) 
6:


.



- C
1:

int main (int argc, char* argv[])

2:

{
char* path=getenv("MYPATH");

3:

return 0;

4:
5:

     
.

6
, , , , , 
     .    ,
,        , 
.

1. 
. 
(signed integer)(unsigned integer)
. , 
.

. 

-1
.

.
, .
, .



. 
- C
1:

unsigned int len(char *s)

2:

3:

unsigned int l = 0;

4:

if (s == NULL) {

5:

return -1;
}

6:
7:

l = strnlen(s, BUFSIZE-1);

8:

return l;

9:

- C

10:

int main(int argc, char **argv)

11:

12:

char buf[BUFSIZE];

13:

unsigned int l = 0;

14:

l = len(argv[1]);

15:

strncpy(buf, argv[1], l);

16:

buf[l] = '\0';

17:

printf("last

character

%c\n",

buf[l-1]);
19:

unsigned int len(char *s)

2:

3:

unsigned int l = 0;

4:

if (s == NULL) {

5:

return 0;

6:

7:

l = strnlen(s, BUFSIZE-1);

8:

return l;

9:

return 0;

18:

1:

10:

int main(int argc, char **argv)

11:

12:

char buf[BUFSIZE];

13:

unsigned int l = 0;

14:

l = len(argv[1]);

15:

if (l > 0) {

16:

strncpy(buf, argv[1], l);

17:

buf[l] = '\0';

18:

printf("last character : %c\n", buf[l-1]);


}

19:

return 0;

20:
21:

 len()
 NULL  -1    un-

signed

int  int 4byte  len()  NULL -1 

4,294,967,295(0xffffffff) .  0 0


 strncpy() .

      
.



2. 
. 
(character).
41
. 
.

. 

(4Bytes)1111(1Bytes)3Bytes 
.

.
, 
.

. 
- C

- C

1:

char char_type()

1:

int char_type()

2:

2:

3:

char bA;

3:

int bA;

4:

int iB;

4:

int iB;

5:

iB = 24;

5:

iB = 24;

6:

bA = iB;

6:

bA = iB;

7:

f(iB);

7:

8:

printf("int = %d char = %d\n", iB, bA); 8:

9:

return iB;

9:

}
10:
1  char int
10:

f(iB);
printf("int = %d char = %d\n", iB, bA);
return iB;
}

/charoverflow .
.



3. 
. 
, (open file descriptor), (heap memory), (socket) . , 

.

. 

.
.

. 
- JAVA

1:
2:
3:
4:
5:
6:

... ...
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url);
conn.close();
} catch (ClassNotFoundException e) {

- JAVA
1: ... ...
2:
try {
3:
Class.forName("com.mysql.jdbc.Driver");
4:
conn = DriverManager.getConnection(url);
5:
} catch (ClassNotFoundException e) {
6:
System.err.print("error");
7:
} catch (SQLException e) {
8:
System.err.print("error");
9:
} finally {
10:
conn.close();

 
 JDBC   finally   
.



7
       ,  


. 

.
, 
, .

1. 
. 
. 
. 

.

. 

.

.
.

. 



- JAVA
1:

protected void doGet(HttpServletRequest


request, ) throws { }

2:

- JAVA
1:

protected void doPost(HttpServletRequest


request, ) throws { }

3:

public static void main(String args[]) {

4:

System.err.printf("Print debug

5:

code");

J2EE
main() .

protected void doGet(HttpServletRequest request, ) throws { }

2:

protected void doPost(HttpServletRequest request, ) throws { }

3:

//

.

- C
1:

int main(int argc,char** argv) {

2:

println("Debug Info...");

3:

- C
1:

......

2:

//

 main()    main() 


.



.

2. 
. 

, .

. 

User GroupPrivate Class.

.
Private .
Private.
    (Static)  (local) 
(anonymous) .

. 
- JAVA
1:
2:
3:
4:
5:
6:

public final class U492 extends Applet {


public class urlHelper {
String openData = secret;
}
String secret;
urlHelper helper = new urlHelper();
}

- JAVA
1:
2:
3:
4:
5:

public class S492 extends Applet {


public static class urlHelper { ... }
String secret;
urlHelper helper = new urlHelper(secret);
}

 (static) 
.

private .



3. 
. 
getMessage(), , DB 
, 
.

. 

getMessage()
.

.
, 
.

. 
- JAVA
1:

public void f() {


}

public void f() {

2:

try {

2:

try {

3:

catch (IOException e) {

3:

catch (IOException e) {

4:

System.err.printf(e.getMessage());

4:

System.err.println("IOException Occured");

5:
6:

g();

- JAVA
1:

5:
6:

g();

  getMessage()    
.



.

+"7"





 944


42-




42-+%0


42-1FSTJTUFODF

42-NZCBUJT%BUB.BQ












-%"1




-%"1




)551






%0.
























42-)JCFSOBUF


63-

91BUI




92VFSZ





"1*


+&&




+&&

%/4MPPLVQ




+&&4ZTUFNFYJU


OVMM


&+#




FRVBMT
IBTI$PEF





















































34"
























)5514





















+&&

































OPUJGZ












TFSJBM1FSTJTUFOU'JFMET

5ISFBESVO























'JOBM




QSJWBUF

QSJWBUF



















<1> JAVA




API

CWE-ID

(XSS)

CWE-80

SQL

CWE-89

SQL : JDO

CWE-89

SQL : Persistence

CWE-89

SQL :myBatis Data Map

CWE-89



CWE-23



CWE-36



CWE-78

LDAP

CWE-90

LDAP

CWE-90

CWE-99

HTTP 

CWE-113



CWE-15

: DOM

CWE-80



CWE-95

CWE-114

CWE-190



CWE-434



CWE-470



CWE-494

SQL :Hibernate

CWE-564

URL 

CWE-601

XPath

CWE-643

XQuery

CWE-652



CWE-807

J2EE: 

CWE-245

CWE-ID

J2EE: 

CWE-246

DNS lookup

CWE-247

J2EE: System.exit()

CWE-382

null 

CWE-398

EJB: 

CWE-577

equals()hashCode() 

CWE-581

CWE-259

CWE-285



CWE-352



CWE-613

: 

CWE-226



CWE-255



CWE-256

CWE-260



CWE-261



CWE-306

: 

CWE-310



CWE-311



CWE-319



CWE-321

: RSA

CWE-325

: 

CWE-326



CWE-327



CWE-330

: 

CWE-359



CWE-ID



CWE-521

: 

CWE-539



CWE-605

HTTPS 

CWE-614



CWE-615



CWE-732

: 

CWE-362

: 

CWE-362

: 

CWE-367

J2EE : 

CWE-383



CWE-386



CWE-609



CWE-674



CWE-521



CWE-209



CWE-390



CWE-754

: notify()

CWE-362



CWE-404

CWE-476

: serialPersistentFields

CWE-485

: Thread.run()

CWE-572

: 

CWE-665



CWE-770



CWE-488




CWE-ID

CWE-489



CWE-492

Final 

CWE-493

private -

CWE-495

private -

CWE-496



CWE-497



CWE-545

1 JAVA 
1 
.

       

,         
.

1. (XSS)
(Improper Neutralization of Script-Related HTML Tags in a Web Page (Basic XSS))
.
, 

.

. 
, replaceAll() 

.

.
- HTML
1:

<%@page

2:

<html>

3:

<head>

4:

<meta

5:

</head>

6:

<body>

contentType="text/html" pageEncoding="UTF-8"%>

http-equiv="Content-Type" content="text/html;

7:

<h1>XSS

8:

<%

9:

<!- -->

10:

String name = request.getParameter("name");

11:

%>

12:

<!-- name -->

13:

charset=UTF-8">

Sample</h1>

<p>NAME:<%=name%></p>

14:

</body>

15:

</html>

name , 

. name , 

attack.jsp , 


.
(: <script>url = "http://devil.com/attack.jsp;</script>)

- HTML
1:

<%@page

2:

<html>

3:

<head>

4:

<meta

5:

</head>

6:

<body>

contentType="text/html" pageEncoding="UTF-8"%>

http-equiv="Content-Type" content="text/html;

7:

<h1>XSS

8:

<%

9:

<!-- -->

10:

String name = request.getParameter("name");

charset=UTF-8">

Sample</h1>

11:
12:

<!-- . -->

13:

if ( name != null ) {

14:

name = name.replaceAll("<","&lt;");

15:

name = name.replaceAll(">","&gt;");

16:

} else {
return;

17:
18:

19:

%>

20:

<!-- name-->

21:

<p>NAME:<%=name%></p>

22:

</body>

23:

</html>

      replaceAll()   < ">"


HTML"&lt;"&gt;"
. 
.

. 
[1] CWE-80 (XSS) - http://cwe.mitre.org/data/definitions/80.html
[2] OWASP Top 10 2010 - (OWASP 2010) A2 Cross-Site Scripting(XSS)
[3] SANS Top 25 2010 - Insecure Interaction Between Components, RANK 1 CWE-79 Improper
Neutralization of Input During Web Page Generation ('Cross-site Scripting')

2. SQL (SQL Injection)


.
SQL . 

DB.

. 
preparedStatement executeQuery(), execute(), executeUpdate()
.

.
- JAVA
1:

2:

PreparedStatement stmt = null;

3:
4:

try {

5:

6:

// (tablename)(name).

7:

String tableName = props.getProperty("jdbc.tableName");

8:

String name = props.getProperty("jdbc.name");

9:

String query = "SELECT * FROM " + tableName + " WHERE Name =" + name;

10:
11:

// SQL.

12:

// SQL(name).

13:

stmt = con.prepareStatement(query);

14:

rs = stmt.executeQuery();

15:

ResultSetMetaData rsmd = rs.getMetaData();

16:

17:

while (rs.next()) {

18:

dos.writeBytes(printStr);

19:

} catch (SQLException sqle) {

20:

finally {

21:

tableNamenameSQL .
name"name' OR 'a'='a", 
.
(SELECT * FROM userTable WHERE Name ='name' OR 'a'='a')
name ["name'; DELETE FROM userTable; --"]
.
(SELECT * FROM userTable WHERE Name ='name'; DELETE FROM userTable; --')

- JAVA
1:

2:

PreparedStatement stmt = null;

3:
4:

try {

5:

6:

String tableName = props.getProperty("jdbc.tableName");

7:

String name = props.getProperty("jdbc.name");

8:
9:

// PreparedStatement.

10:

String query = "SELECT

11:

stmt = con.prepareStatement(query);

12:

// setXXX().

13:

stmt.setString(1, tableName);

14:

stmt.setString(2, name);

* FROM ? WHERE Name = ? ";

15:
16:

rs = stmt.executeQuery();

17:

ResultSetMetaData rsmd =

18:

int columnCount =

19:

String printStr =

20:

while (rs.next()) {

21:

dos.writeBytes(printStr);

"";

22:

} catch (SQLException sqle) {

23:

finally {

24:

rs.getMetaData();

rsmd.getColumnCount();
}

PreparedStatement , 
setXXX() , .

. 
[1] CWE-89 SQL - http://cwe.mitre.org/data/definitions/89.html
[2] OWASP Top 10 2010 - (OWASP 2010) A1 - Injection
[3] SANS Top 25 2010 - Insecure Interaction Between Components, RANK 2 CWE-89 Improper
Neutralization of Special Elements used in an SQL Command ('SQL Injection')

3. SQL : JDO(SQL Injection: JDO)


.
JDO(Java Data Objects)
APISQL JDOQL , 

.

. 
JDO Query.execute(...) 
(Parameterize Query).

.
- JAVA
1:

2:

public class U9102 implements ContactDAO {

3:

public List<Contact> listContacts() {

4:

PersistenceManager pm = getPersistenceManagerFactory().getPersistenceManager();

5:

String query = "select from " + Contact.class.getName();

6:

try {

7:

Properties props = new

Properties();

8:

String fileName =

9:

FileInputStream in = new

10:

if( in != null ) {

11:

in.close();

12:

// 

13:

String name = props.getProperty("name");

14:

if( name != null ) {

"contacts.txt";
FileInputStream(fileName);

props.load(in);

query += " where name = '" + name + "'";

15:

16:

} catch (IOException e) {

17:

18:

// JDO .

19:

return (List<Contact>) pm.newQuery(query).execute();

20:
21:

22:

(name) "name'; DELETE FROM MYTABLE; --" ,


.
(SELECT col1 FROM MYTABLE WHERE name = 'name' ; DELETE FROM MYTABLE;
--')

- JAVA
1:

2:

public class S9102 implements ContactDAO {

3:

public List<Contact> listContacts() {


PersistenceManager pm =

4:

getPersistenceManagerFactory().getPersistenceManager();

5:
6:

String query = "select from " + Contact.class.getName();

7:

String name = "";

8:

try {

9:

Properties props = new Properties();

10:

String fileName = "contacts.txt";

11:

FileInputStream in = new FileInputStream(fileName);

12:

props.load(in);

13:

// .

14:

name = props.getProperty("name");

15:

// .

16:

if (name == null || "".equals(name)) return null;


query += " where name = ?";

17:

} catch (IOException e) {

18:

19:
20:

javax.jdo.Query q = pm.newQuery(query);

21:

// Query API.
return (List<Contact>) q.execute(name);

22:
23:

24:

?(Parameterize Query), 


(name).

. 
[1] CWE-89 SQL - http://cwe.mitre.org/data/definitions/89.html
[2] OWASP Top 10 2010 - (OWASP 2010) A1 Injection
[3] JDO API Documentation
[4] SANS Top 25 2010 - Insecure Interaction Between Components, RANK 2 CWE-89 Improper
Neutralization of Special Elements used in an SQL Command ('SQL Injection')

4. SQL : Persistence(SQL Injection: Persistence)


.
J2EE Persistence API
, 
.

. 
(Parameterize Query)
. , javax.persistence.Query.setParameter()
.

.
- JAVA
1:

2:

public class U9103 implements ServletContextListener {

3:

public List<?> getAllItemsInWildcardCollection() {

4:

EntityManager em = getEntityManager();

5:

List<U9103> r_type = null;

6:

try {

7:

Properties props = new

Properties();

8:

String fileName = "conditions.txt";

9:

FileInputStream in = new FileInputStream(fileName);

10:

props.load(in);

11:
12:

// .

13:

String id =

14:

// query.

15:

Query query =

props.getProperty("id");

em.createNativeQuery("SELECT OBJECT(i) FROM Item i WHERE

16:

i.itemID > " + id);


17:

List<U9103> items = query.getResultList();

18:

return r_type;

19:
20:

21:

(id)"foo'; DELETE FROM MYTABLE; --",


.
(SELECT col1 FROM MYTABLE WHERE name = 'foo' ; DELETE FROM MYTABLE;
--')

- JAVA
1:

2:

public class S9103

3:

implements ServletContextListener {

public List<?> getAllItemsInWildcardCollection() {

4:

EntityManager em = getEntityManager();

5:

List<S9103> r_type = null;

6:

try {

7:

Properties props = new

8:

String fileName =

9:

FileInputStream in = new

10:

props.load(in);

Properties();

"conditions.txt";
FileInputStream(fileName);

11:
12:

// .

13:

String id = props.getProperty("id");

14:

// .

15:

if (id == null || "".equals(id)) id = "itemid";

16:

// Query.

17:

Query query =
em.createNativeQuery("SELECT OBJECT(i) FROM Item i WHERE

18:

i.itemID > :id");


19:

query.setParameter("id", id);

20:

List<S9103> items = query.getResultList();

21:

return r_type;

22:
23:

24:

(query), 
. .

. 
[1] CWE-89 SQL - http://cwe.mitre.org/data/definitions/89.html
[2] OWASP Top 10 2010 - (OWASP 2010) A1 Injection
[3] SANS Top 25 2010 - Insecure Interaction Between Components, RANK 2 CWE-89 Improper
Neutralization of Special Elements used in an SQL Command ('SQL Injection')

5. SQL : mybatis Data Map(SQL Injection: mybatis Data Map)


.
, 
, 
.

. 

.
mybatis Data Map ($...$)
. #<># .

.
- XML
1:

<?xml version="1.0"

2:

<!DOCTYPE

sqlMap

encoding="UTF-8"?>
PUBLIC

"-//iBATIS.com//DTD

SQL

Map

2.0//EN"

"http://www.ibatis.com/dtd/sql-map-2.dtd">
3:
4:
5:
6:
7:
8:

<sqlMap

namespace="Student">

<resultMap id="StudentResult" class="Student">


<result column="ID" property="id" />
<result column="NAME" property="name" />
</resultMap>
<select id="listStudents" resultMap="StudentResult">

9:

SELECT NUM, NAME

10:

FROM STUDENTS

11:

ORDER BY NUM

12:

</select>

13:

<select id="nameStudent"

parameterClass="Integer" resultClass="Student">

14:

SELECT NUM, NAME

15:

FROM STUDENTS

16:

WHERE NUM = #num#

17:

</select>

18:

<!-- dynamic SQL -->

19:

<delete id="delStudent"

20:
21:
22:
23:

parameterClass="Student">

DELETE STUDENTS
WHERE NUM = #num# AND Name = '$name$'
</delete>
</sqlMap>

mybatis Data Map(XML). 


delStudent $name$
     .   name  "' OR

'x'='x'".
(DELETE STUDENTS WHERE NUM = #num# and Name = '' OR 'x'='x')

- XML
1:

<?xml version="1.0"

2:

<!DOCTYPE

sqlMap

encoding="UTF-8"?>
PUBLIC

"-//iBATIS.com//DTD

SQL

Map

2.0//EN"

"http://www.ibatis.com/dtd/sql-map-2.dtd">
3:
4:
5:

<sqlMap

namespace="Student">

<resultMap

id="StudentResult" class="Student">

<result column="ID" property="id" />

6:

<result column="NAME" property="name" />

7:
8:

</resultMap>

9:

<select

id="listStudents" resultMap="StudentResult">

10:

SELECT NUM, NAME

11:

FROM STUDENTS

12:

ORDER BY NUM

13:

</select>

14:

<select id="nameStudent" parameterClass="Integer" resultClass="Student">

15:

SELECT NUM, NAME

16:

FROM STUDENTS
WHERE NUM = #num#

17:
18:

</select>

19:
20:

<!-- static SQL -->

21:

<delete id="delStudent"

parameterClass="Student">

22:

DELETE STUDENTS

23:

WHERE NUM = #num# AND Name = '#name#'

24:
25:

</delete>
</sqlMap>

Name #name# .

. 
[1] CWE-89 SQL - http://cwe.mitre.org/data/definitions/89.html
[2] OWASP Top 10 2010 - (OWASP 2010) A1 Injection
[3] SANS Top 25 2010 - Insecure Interaction Between Components, RANK 2 CWE-89 Improper
Neutralization of Special Elements used in an SQL Command ('SQL Injection')



6. (Relative Path Traversal)


.
 , 
, 
, .

. 
. 
, replaceAll() 
(",/,\).

.
- JAVA
1:

2:

public void f(Properties request) {

3:

4:

String name = request.getProperty("filename");

5:

if( name != null ) {

6:

File file = new File("/usr/local/tmp/" + name);

7:

file.delete();
}

8:

9:
10:

(name). name
../../../rootFile.txt
.



- JAVA
1:

2:

public void f(Properties request) {

3:

4:

String name = request.getProperty("user");

5:

if ( name != null && !"".equals(name) ) {

6:

name = name.replaceAll("/", "");

7:

name = name.replaceAll("\\", "");

8:

name = name.replaceAll(".", "");

9:

name = name.replaceAll("&", "");

10:

name = name + "-report";

11:

File file = new File("/usr/local/tmp/" + name);

12:

if (file != null) file.delete();


}

13:

14:
15:

Null, (name)
(/, \\, &, . )replaceAll
.

. 
[1] CWE-23 - http://cwe.mitre.org/data/definitions/23.html
[2] OWASP Top 10 2010 - (OWASP 2010) A4 Insecure Direct Object Reference
[3] SANS Top 25 2010 - (SANS 2010) Risky Resource Management, Rank 7 CWE ID 22:
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')



7. (Absolute Path Traversal)


.

. ,

. , , 
.

. 
, 
.

.
- JAVA
1:

2:

public void f(Properties cfg) throws IOException {

3:

FileInputStream fis = new FileInputStream(cfg.getProperty("subject"));

4:

byte[] arr = new byte[30];

5:

fis.read(arr);

6:

System.out.println(arr);

7:
8:

(fis), 
, .



- JAVA
1:

2:

public void f(Properties cfg) throws IOException {

3:

FileInputStream fis;

4:

String subject = cfg.getProperty("subject");

5:

if (subject.equals("math"))

6:

fis = new FileInputStream("math");

7:

else if (subject.equals("physics"))

8:

fis = new FileInputStream("physics");

9:

else if (subject.equals("chemistry"))

10:

fis = new FileInputStream("chemistry");

11:

else

12:

fis = new FileInputStream("default");

13:
14:
15:

byte[] arr = new byte[30];

16:

fis.read(arr);
System.out.println(arr);

17:
18:

19:


.

. 
[1] CWE-36 - http://cwe.mitre.org/data/definitions/36.html
[2] OWASP Top 10 2010 - (OWASP 2010) A4 Insecure Direct Object Reference
[3] SANS Top 25 2010 - Risky Resource Management, Rank 7 CWE ID 22: Improper Limitation
of a Pathname to a Restricted Directory ('Path Traversal')



8. 
(Improper Neutralization of Special Elements Used in an OS Command (OS Command Injection))
.
. 

   .  ,     
.

. 
. 

.

.
- JAVA
1:

2:

public void f() throws IOException {

3:

Properties props = new Properties();

4:

String fileName = "file_list";

5:

FileInputStream in = new FileInputStream(fileName);

6:

props.load(in);

7:

String version = props.getProperty("dir_type");

8:

String cmd = new String("cmd.exe /K

9:

Runtime.getRuntime().exec(cmd + " c:\\prog_cmd\\" + version);

10:

11:

\"rmanDB.bat \"");

cmd.exe rmanDB.bat , 


 dir_type  manDB.bat      .
, dir_type
, .



- JAVA
1:

2:

public void f() throws IOException {

3:

Properties props = new Properties();

4:

String fileName = "file_list";

5:

FileInputStream in = new

6:

props.load(in);

7:

String version[] = {"1.0",

8:

int versionSelection = Integer.parseInt(props.getProperty("version"));

9:

String cmd = new String("cmd.exe /K

10:

String vs = "";

FileInputStream(fileName);
"1.01", "1.11", "1.4"};
\"rmanDB.bat \"");

11:
12:

// .

13:

if (versionSelection == 0)

14:

vs = version[0];

15:

else if (versionSelection == 1)

16:

vs = version[1];

17:

else if (versionSelection == 2)

18:

vs = version[2];

19:

else if (versionSelection == 3)
vs = version[3];

20:

else

21:

vs = version[3];

22:

Runtime.getRuntime().exec(cmd + "

23:

24:
25:

c:\\prog_cmd\\" + vs);

, 
, .

. 
[1] CWE-78 - http://cwe.mitre.org/data/definitions/78.html
[2] OWASP Top 10 2010 - (OWASP 2010) A1 Injection
[3] SANS, Frank Kim. "Top 25 Series - Rank 9 - OS Command Injection".
[4] SANS Top 25 2010 - Insecure Interaction Between Components, RANK 9 CWE-78: Improper
Neutralization of Special Elements used in an OS Command ('OS Command Injection')



9. LDAP (LDAP Injection)


.
LDAP . 
, LDAP 
, Authentication
.

. 
LDAP , (white list) 
(black list= + < > # ; \ ),
.

.
- JAVA
1:

2:

public void f() {

3:

Hashtable env = new Hashtable();

4:

env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

5:

env.put(Context.PROVIDER_URL,

6:

try {

"ldap://localhost:389/o=rootDir");

7:

javax.naming.directory.DirContext

8:

// .

ctx = new InitialDirContext(env);

9:

Properties props = new Properties();

10:

String fileName = "ldap.properties";

11:

FileInputStream in = new FileInputStream(fileName);

12:

props.load(in);

13:

// LDAP Searchname

14:

String name = props.getProperty("name");

15:

String filter = "(name =" + name + ")";

16:

// LDAP searchname.

17:

NamingEnumeration answer =

18:

printSearchEnumeration(answer);

19:

ctx.close();

ctx.search("ou=NewHires", filter, new SearchControls());

20:
21:

} catch (NamingException e) { }

(name). 
name "*""(name=*)"
.



- JAVA
1:

2:

public void f() {

3:

Hashtable env = new Hashtable();

4:

env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

5:

env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=rootDir");

6:

try {

7:

javax.naming.directory.DirContext ctx = new InitialDirContext(env);

8:

Properties props = new Properties();

9:

String fileName = "ldap.properties";

10:

FileInputStream in = new FileInputStream(fileName);

11:
12:

if (in == null || in.available() <= 0) return;

13:

props.load(in);

14:
15:

if (props == null || props.isEmpty()) return;

16:

String name = props.getProperty("name");

17:

if (name == null || "".equals(name)) return;

18:

// name* .

19:

String filter = "(name =" + name.replaceAll("\\*", "") + ")";

20:

NamingEnumeration answer =
ctx.search("ou=NewHires", filter, new SearchControls());

21:
22:

printSearchEnumeration(answer);

23:

ctx.close();

24:
25:

} catch (NamingException e) {


.

. 
[1] CWE-90 LDAP - http://cwe.mitre.org/data/definitions/90.html
[2] OWASP Top 10 2010 - (OWASP 2010) A1 - Injection
[3] SPI Dynamics. "Web Applications and LDAP Injection".
[4] SANS Top 25 2009 - (SANS 2009) Insecure Interaction - CWE ID 116 Improper Encoding
or Escaping of Output



10. LDAP (LDAP Manipulation)


.
LDAP LDAP
LDAP .

. 
, LDAP 
.

.
- JAVA
1:

try {

2:
3:

4:

// .

5:

String name = props.getProperty(ldap.properties");

6:

// BasicAttribute.

7:

BasicAttribute attr = new BasicAttribute("name", name);

8:

// LDAP search.

9:

NamingEnumeration answer =
ctx.search("ou=NewHires", attr.getID(), new SearchControls());

10:
11:

printSearchEnumeration(answer);

12:

ctx.close();
} catch (NamingException e) {

13:
14:

15:
16:
17:

public void printSearchEnumeration(NamingEnumeration value) {


try {

18:

while (value.hasMore()) {

19:

SearchResult

20:

System.out.println(">>>"

23:

+ sr.getName() + "\n" + sr.getAttributes());

21:
22:

sr = (SearchResult) value.next();

} catch (NamingException e) {

(name)base . 
, 
.



- JAVA
1:

try {

2:
3:

4:

// .

5:

String name = props.getProperty("name");

6:

// .

7:

if (name == null || "".equals(name)) return;

8:

String filter = "(name =" + name.replaceAll("\\*", "") + ")";

9:
10:

// LDAP search .

11:

NamingEnumeration answer =
ctx.search("ou=NewHires", filter, new SearchControls());

12:

printSearchEnumeration(answer);

13:

ctx.close();

14:

} catch (NamingException e) {

15:
16:

17:
18:
19:

public void printSearchEnumeration(NamingEnumeration value) {


try {
while (value.hasMore()) {

20:

SearchResult sr = (SearchResult) value.next();

21:

System.out.println(">>>" + sr.getName() + "\n" + sr.getAttributes());

22:

23:
24:
25:

} catch (NamingException e) {

, LDAP 
.

. 
[1] CWE-639 - http://cwe.mitre.org/data/definitions/639.html
CWE-90 LDAP - http://cwe.mitre.org/data/definitions/90.html
CWE-116 - http://cwe.mitre.org/data/definitions/116.html
[2] OWASP Top 10 2010 - (OWASP 2010) A4 Insecure Direct Object Reference
[3] SANS Top 25 2009 - (SANS 2009) Insecure Interaction - CWE ID 116 Improper Encoding
or Escaping of Output



11. (Resource Injection)


.
(resource)
.

. 
, 
(white list). , 
.

.
- JAVA
1:

2:

public void f() throws IOException {

3:

int def = 1000;

4:

ServerSocket serverSocket;

5:

Properties props = new Properties();

6:

String fileName = "file_list";

7:

FileInputStream in = new FileInputStream(fileName);

8:

props.load(in);

9:
10:

// .

11:

String service = props.getProperty("Service No");

12:

int port = Integer.parseInt(service);

13:
14:

// .

15:

if (port != 0)
serverSocket = new ServerSocket(port + 3000);

16:

else

17:

serverSocket = new ServerSocket(def + 3000);

18:

19:
20:

21:

   (service)     . , 
Service No -2920 80 
.



- JAVA
1:

2:

public void f() throws IOException {

3:

ServerSocket serverSocket;

4:

Properties props = new Properties();

5:

String fileName = "file_list";

6:

FileInputStream in = new FileInputStream(fileName);

7:

String service = "";

8:

if (in != null && in.available() > 0) {

9:
10:

props.load(in);

11:

// .

12:

service = props.getProperty("Service No");

13:

14:

// .
if ("".equals(service)) service = "8080";

15:
16:

int port = Integer.parseInt(service);

17:
18:

// .

19:

switch (port) {
case 1:

20:

port = 3001; break;

21:

case 2:

22:

port = 3002; break;

23:

case 3:

24:

port = 3003; break;

25:

default:

26:

port = 3000;

27:

28:

// .

29:

serverSocket = new ServerSocket(port);

30:

31:
32:

33:

. 
, .

. 
[1] CWE-99 - http://cwe.mitre.org/data/definitions/99.html



12. HTTP 
(Failure to Sanitize CRLF Sequences in HTTP Headers ('HTTP Response Splitting'))
.
HTTP HTTP 

  CR(Carriage Return) LF(Line Feed)  

HTTP 2. 



XSS (cache poisoning) .

. 
HTTP (Set Cookie )CR,
LF.

.
- JAVA
1:

public class U113 extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse response)

2:

throws IOException, ServletException {

3:
4:

response.setContentType("text/html");

5:

// .

6:

String author = request.getParameter("authorName");

7:

Cookie cookie = new Cookie("replidedAuthor", author);

8:

cookie.setMaxAge(1000);

9:

// cookie.setSecure(true); // HTTP()
// HTTPS 

10:

...

11:
12:

// .

13:

response.addCookie(cookie);

14:

RequestDispatcher frd = request.getRequestDispatcher("cookieTest.jsp");


frd.forward(request, response);

15:

16:
17:

. ,
"Wiley Hacker\r\nHTTP/1.1 200 OK\r\n"authorName,
. 
.
(: HTTP/1.1 200 OK...Set-Cookie: author=Wiley Hacker HTTP/1.1 200 OK...)



- JAVA
1:

public class S113 extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse response)

2:

throws IOException, ServletException {

3:

response.setContentType("text/html");

4:
5:
6:

// .

7:

String author = request.getParameter("authorName");

8:

if (author == null || "".equals(author)) return;

9:

//  \n \r

10:

.
11:

String filtered_author = author.replaceAll("\r", "").replaceAll("\n",

12:

Cookie cookie = new Cookie("replidedAuthor", filtered_author);

13:

cookie.setMaxAge(1000);

14:

cookie.setSecure(true);

"");

15:
16:

// .

17:

response.addCookie(cookie);

18:

RequestDispatcher frd = request.getRequestDispatcher("cookieTest.jsp");


frd.forward(request, response);

19:

20:
21:

Null, 
relpaceAll(\r, \n) .

. 
[1] CWE-113 HTTP - http://cwe.mitre.org/data/definitions/113.html
[2] OWASP Top 10 2004 A1 Unvalidated Input
[3] OWASP Top 10 2007 A2 Injection Flaws
[4] Web Application Security Consortium 24 + 2 HTTP Response Splitting



13. 
(External Control of System or Configuration Setting)
.
(: 
).

. 
Connection.setCatalog() .
, .

.
- JAVA
1:

2:

public void f() {


try {

3:
4:

InitialContext ctx = new InitialContext();

5:

DataSource datasource = (DataSource) ctx.lookup("jdbc:ocl:orcl");

6:

Connection con = datasource.getConnection();

7:

Properties props = new Properties();

8:

String fileName = "file.properties";

9:

FileInputStream in = new FileInputStream(fileName);

10:

props.load(in);

11:

// catalog

12:
13:

String catalog = props.getProperty("catalog");

14:

// catalogDB Connection, DB

15:

con.setCatalog(catalog);



con.close();

16:

} catch (SQLException ex) {

17:

System.err.println("SQLException Occured");

18:

} catch (NamingException e) {

19:

System.err.println("NamingException Occured");

20:

} catch (FileNotFoundException e) {

21:

System.err.println("FileNotFoundException Occured");

22:

} catch (IOException e) {

23:

System.err.println("IOException Occured");

24:

25:
26:

27:

(catalog)JDBC. 
.



- JAVA
1:

2:

public void f() {


try {

3:
4:

// caltalog c1c2

5:

InitialContext ctx = new InitialContext();

6:

DataSource datasource = (DataSource) ctx.lookup("jdbc:ocl:orcl");

7:

Connection con = datasource.getConnection();

8:
9:

Properties props = new Properties();

10:

String fileName= "file.properties";

11:

String catalog;

12:
13:

FileInputStream in = new FileInputStream(fileName);

14:

if (in != null && in.available() > 0) {


props.load(in);

15:
16:
17:

if (props == null || props.isEmpty()) catalog = "c1";

18:

else
catalog = props.getProperty("catalog");

19:

} else

20:

catalog = "c1";

21:
22:
23:

// (catalog).

24:

if ("c1".equals(catalog))
con.setCatalog("c1");

25:

else

26:

con.setCatalog("c2");

27:

con.close();

28:

} catch (SQLException ex) {

29:

System.err.println("SQLException Occured");

30:

} catch (NamingException e) {

31:

System.err.println("NamingException Occured");

32:

} catch (FileNotFoundException e) {

33:

System.err.println("FileNotFoundException Occured");

34:

} catch (IOException e) {

35:

System.err.println("IOException Occured");

36:

37:
38:


, .

. 
[1] CWE-15 - http://cwe.mitre.org/data/definitions/15.html



14. : DOM


(Improper Neutralization of Script-Related HTML Tags in a Web Page (DOM))
.

.

. 
JSPdocument.write() JSPDOM 
.

.
- HTML
1:

2:

<%

3:

// .

4:

String name = request.getParameter("name");

5:

%>

6:

<SCRIPT language="javascript">

7:

// .

8:

document.write("name:" + <%=name%> );

request.getParameter()   (name) document.write() 


.

- HTML
1:

2:

<%

3:

// .

4:

String name = request.getParameter("name");

5:

// .

6:

if ( name != null ) {
name = name.replaceAll("<","&lt;");

7:

name = name.replaceAll(">","&gt");

8:
9:

} else {

return;

10:

%>

11:

<SCRIPT language="javascript">

12:

// .

13:

document.write("name:" + <%=name%> );

(name)<">"HTML
"&lt;"&gt;".



. 
[1] CWE-79 - http://cwe.mitre.org/data/definitions/79.html
CWE-80  (XSS) - http://cwe.mitre.org/data/definitions/80.html
[2] OWASP Top 10 2010 - (OWASP 2010) A2 Cross Site Scripting (XSS)
[3] SANS Top 25 2010 - (SANS 2010) Insecure Interaction - CWE ID 079 Improper
Neutralization of Input During Web Page Generation ('Cross-site Scripting')



15. 
(Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection'))
.


. , 
.

. 
eval() JavaScript
.

.
- HTML
1:

<%@page import="org.owasp.esapi.*"%>

2:

<%@page contentType="text/html" pageEncoding="UTF-8"%>

3:

<html>

4:

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

5:
6:
7:

</head>
<body>

8:

<h1>Eval </h1>

9:

<%
String evalParam = request.getparameter("eval");

10:

11:
12:

%>

13:

<script>

14:
15:

eval(<%=evalParam%>);
</script>

16:

</body>

17:

</html>

(evalParam)eval() . javascript


eval().



- HTML
1:

<%@page import="org.owasp.esapi.*"%>

2:

<%@page contentType="text/html" pageEncoding="UTF-8"%>

3:

<html>

4:

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

5:
6:
7:

</head>
<body>

8:

<h1>Eval </h1>

9:

<%

10:

// .

11:

String evalParam = request.getparameter("eval");

12:

// .

13:

if ( evalParam != null ) {

14:

evalParam = evalParam.replaceAll("<","&lt;");

15:

evalParam = evalParam.replaceAll(">","&gt;");

16:

evalParam = evalParam.replaceAll("&","&amp;");

17:

evalParam = evalParam.replaceAll("(","&#40;");

18:

evalParam = evalParam.replaceAll(")","&#41;");

19:

evalParam = evalParam.replaceAll("\"","&quot;");
evalParam = evalParam.replaceAll("\'","&apos;");

20:
21:

22:

23:

%>

24:

<script>
eval(<%=evalParam%>);

25:
18:

</script>

19:

</body>

20:

</html>

(: <, >, &, \ )


.

. 
[1] CWE-95      - http://cwe.mitre.org/data/definitions/95.html
[2] OWASP Top Ten 2007 Category A3 - Malicious File Execution
[3] SANS Top 25 2009 - (SANS 2009) Insecure Interaction - CWE ID 116 Improper Encoding
or Escaping of Output



16. (Process Control)


.

, .

. 
.

.
- JAVA
1:

2:

public void loadLibrary() throws SecurityException, UnsatisfiedLinkError, NullPointerException


{
// .

3:

Runtime.getRuntime().loadLibrary("libraryName");

4:
5:

6:


.

- JAVA
1:

2:

public void loadLibrary() throws SecurityException, UnsatisfiedLinkError, NullPointerException


{
// .

3:

Runtime.getRuntime().loadLibrary("/usr/lib/libraryName");

4:
5:

6:

.

. 
[1] CWE-114 - http://cwe.mitre.org/data/definitions/114.html



17. (Integer Overflow)


.
, Java
. 
, ,
.

. 

.

.
- JAVA
1:

2:

public static void main(String[] args) {

3:

int size = new Integer(args[0]).intValue();

4:

size += new Integer(args[1]).intValue();


MyClass[] data = new MyClass[size];

5:
6:

7:

(args[0], args[1])
(size). (size)
.

- JAVA
1:

2:

public static void main(String[] args) {

3:

int size = new Integer(args[0]).intValue();

4:

size += new Integer(args[1]).intValue();

5:

// .

6:

if (size < 0) return ;


MyClass[ ] data = new MyClass[size];

7:
8:


.

. 
[1] CWE-190 - http://cwe.mitre.org/data/definitions/190.html



18. (Unrestricted Upload of File with Dangerous Type)


.

.

. 
, 
.
, 
.

.
- JAVA
1:

2:

public void upload(HttpServletRequest request) throws ServletException

3:

MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;

4:

String next = (String) mRequest.getFileNames().next();

5:

MultipartFile file = mRequest.getFile(next);

6:
7:

// MultipartFilefile

8:

String fileName = file.getOriginalFilename();

9:
10:

// upload , 

11:

File uploadDir = new File("/app/webapp/data/upload/notice");

12:

String uploadFilePath = uploadDir.getAbsolutePath()+"/" + fileName;

13:
14:
15:

/* file upload */

, 
.



- JAVA
1:

2:

public void upload(HttpServletRequest request) throws ServletException {

3:

MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;

4:

String next = (String) mRequest.getFileNames().next();

5:

MultipartFile file = mRequest.getFile(next);

6:

if ( file == null )
return ;

7:
8:
9:

// .

10:

int size = file.getSize();

11:

if ( size > MAX_FILE_SIZE ) throw new ServletException(");

12:
13:

// MultipartFilefile

14:

String fileName = file.getOriginalFilename().toLowerCase();

15:
16:

// .

17:

if ( fileName != null ) {
if ( fileName.endsWith(".doc") || fileName.endsWith(".hwp")

18:

|| fileName.endsWith(".pdf") || fileName.endsWith(".xls") ) {

19:

/* file */

20:

21:

else

22:

throw new ServletExeption("");

23:

24:

// .

25:

File uploadDir = new File("/app/webapp/data/upload/notice");

26:

String uploadFilePath = uploadDir.getAbsolutePath()+"/" + fileName;

27:
28:
29:

/* file upload */

. 
.

. 
[1] CWE-434 - http://cwe.mitre.org/data/definitions/434.html
[2] OWASP Top Ten 2007 A3, Malicious File Execution
[3] SANS Top 25 2010 - (SANS 2010) Insecure Interaction - CWE ID 434 Unrestricted Upload
of File with Dangerous Type



19. 
(Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection'))
.
(loading), 
.

. 
, 
(white list) .

.
- JAVA
1:

2:

public void f() {

3:

Properties props = new Properties();

4:

....

5:

if ( in !=null && in.available() > 0 ) {

6:

props.load(in);

7:

if ( props == null || props.isEmpty() )


return ;

8:
9:

10:

String type = props.getProperty("type");

11:

Worker w;

12:
13:

// type.

14:

try {

15:

Class workClass = Class.forName(type + "Worker");

16:

w = (Worker) workClass.newInstance();
w.doAction();

17:

} catch (ClassNotFoundException e) {

18:
19:

20:

21:
22:

abstract class Worker {

23:

String work = "";

24:

public abstract void doAction();

25:

(type).
.



- JAVA
1:

2:

public void f() {

3:

Properties props = new Properties();

4:

....

5:

if ( in !=null && in.available() > 0 ) {

6:

props.load(in);

7:

if ( props == null || props.isEmpty() )


return ;

8:
9:

10:

String type = props.getProperty("type");

11:

Worker w;

12:
13:

// .

14:

if (type == null || "".equals(type)) return;

15:

if (type.equals("Slow")) {
w = new SlowWorker();

16:

w.doAction();

17:
18:

} else if (type.equals("Hard")) {

19:

w = new HardWorker();
w.doAction();

20:

} else {

21:

System.err.printf("No propper class name!");

22:
23:

24:

25:

26:
27:

abstract class Worker {

28:

String work = "";


public abstract void doAction();

29:
30:

(type), (white list) 


, 
.

. 
[1] CWE-470 - http://cwe.mitre.org/data/definitions/470.html



20. 
(Download of Code Without Integrity Check)
.
, 
         
.

. 
SW          
.

. 
- JAVA
1:

URL[] classURLs= new URL[]{new URL("file:subdir/")};

2:

URLClassLoader loader = new URLClassLoader(classURLs);

3:

Class loadedClass = Class.forName("MyClass", true, loader);

URLClassLoader, . 
, .



- JAVA
1:

// private keyMyClass.

2:

String jarFile = "./download/util.jar";

3:

byte[] loadFile = FileManager.getBytes(jarFile);

4:

loadFile = encrypt(loadFile,privateKey);

5:

// jarFile.

6:

FileManager.createFile(loadFile,jarFileName);

7:

....

8:

// public key.

9:

URL[] classURLs= new URL[]{new URL("http://filesave.com/download/util.jar")};

10:

URLConnection conn=classURLs.openConnection();

11:

InputStream is = conn.getInputStream();

12:

// jarFile.

13:

FileOutputStream fos = new FileOutputStream(new File(jarFile));

14:

while ( is.read(buf) != -1 ) {
...

15:
16:

17:

byte[] loadFile = FileManager.getBytes(jarFile);

18:

loadFile = decrypt(loadFile,publicKey);

19:

// .

20:

FileManager.createFile(loadFile,jarFile);

21:

URLClassLoader loader = new URLClassLoader(classURLs);

22:

Class loadedClass = Class.forName("MyClass", true, loader);


, .

. 
[1] CWE-494 - http://cwe.mitre.org/data/definitions/494.html
[2] SANS Top 25 Most Dangerous Software Errors, http://www.sans.org/top25-software-errors/
[3] Richard Stanway (r1CH). "Dynamic File Uploads, Security and You
[4] Johannes Ullrich. "8 Basic Rules to Implement Secure File Uploads". 2009-12-28



21. SQL : Hibernate(SQL Injection: Hibernate)


.
Hibernate APISQL
, 


.

. 
. 

, setParameter(), set<


>() .

.
- JAVA
1:

2:

public void listHoney() {

3:

Session session = new Configuration().configure().buildSessionFactory().openSession();

4:

try {

5:

Properties props = new Properties();

6:

String fileName = "Hibernate.properties";

7:

FileInputStream in = new FileInputStream(fileName);

8:

props.load(in);

9:

10:

// 

11:

String idValue = props.getProperty("idLow");

12:

// SQL qeuery.

13:

Query query = session.createQuery("from Address a where a.name='" + idValue);


query.list();

14:
15:
16:

} catch (IOException e) {

(idValue).
, "n' or '1'='1" , 
.
("from Address a where a.name='n' or '1'='1'")



- JAVA
1:

2:

public void listHoney() {

3:

Session session = new Configuration().configure().buildSessionFactory().openSession();

4:

try {

5:

Properties props = new Properties();

6:

String fileName = "Hibernate.properties";

7:

FileInputStream in = new FileInputStream(fileName);

8:

if (in == null || in.available() <= 0) return;

9:

props.load(in);

10:

11:

// .

12:

String idValue = props.getProperty("idLow");

13:

// .

14:

if (idValue == null || "".equals(idValue)) idValue = "defaultID";

15:

// SQL query .

16:

Query query = session.createSQLQuery("select h from Honey as h where h.id '= :idVal");

17:

query.setParameter("idVal", idValue);

18:

query.list();

19:
20:

} catch (IOException e) {

(idValue)setParameter 
.

. 
[1] CWE-564 SQL : Hibernate - http://cwe.mitre.org/data/definitions/564.html
[2] SANS Top 25 2009 - (SANS 2009) Insecure Interaction - CWE ID 116 Improper Encoding
or Escaping of Output



22. URL 


(URL Redirection to Untrusted Site ('Open Redirect'))
.
URL 
. URL 
, 
URL.

. 
URL.

.
- JAVA
1:

2:

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

3:
4:

String query = request.getQueryString();

5:

if (query.contains("url")) {

6:

String url = request.getParameter("url");

7:

response.sendRedirect(url);

8:

9:


().
(<a href="http://bank.example.com/redirect?url=http://attacker.example.net">Click here to
log in</a>)



- JAVA
1:

2:

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

3:
4:

String query = request.getQueryString();

5:
6:

// URL .

7:

String allowURL[] = { "url1", "url2", "url3" };

8:

ArrayList arr = new ArrayList();

9:

for ( int i = 0; i < allowURL.length; i++ )


arr.add(allowURL[i]);

10:
11:
12:

if (query.contains("url")) {
String url = request.getParameter("url");

13:

// url. http://URL

14:

redirect.
15:

if (url != null && url.indexOf("http://") != -1 ) {

16:

url = url.replaceAll("\r", "").replaceAll("\n",

17:

// URL .

18:

if ( !arr.contains(url) ) throw new MyException(");

"");

response.sendRedirect(url);

19:

20:
21:

22:

URL , URL


.

. 
[1] CWE-601 URL - http://cwe.mitre.org/data/definitions/601.html
[2] OWASP Top Ten 2010 Category A10 - Unvalidated Redirects and Forward
[3] SANS 2010 Top 25 - Insecure Interaction Between Components



23. XPath
(Failure to Sanitize Data within XPath Expressions (XPath injection))
.
XPath 
, 
.

. 
XQuery 
.

.
- JAVA
1:

2:

// 

3:

String name = props.getProperty("name");

4:

String passwd = props.getProperty("password");

5:

6:

XPathFactory factory = XPathFactory.newInstance();

7:

XPath xpath = factory.newXPath();

8:

9:

// xpath

10:

XPathExpression expr = xpath.compile("//users/user[login/text()='" + name


+ "' and password/text() = '" + passwd + "']/home_dir/text()");

11:
12:

Object result = expr.evaluate(doc, XPathConstants.NODESET);

13:

NodeList nodes = (NodeList) result;

14:

for (int i = 0; i < nodes.getLength(); i++) {

15:

String value = nodes.item(i).getNodeValue();

16:

if (value.indexOf(">") < 0) {
System.out.println(value);

17:

18:
19:

nameuser1, passwd' or ''='


.
(//users/user[login/text()=user1' or ''='' and password/text() = or =]/home_dir/text())



- JAVA
dologin.xp
1:

declare variable $loginID as xs:string external;

2:

declare variable $password as xs:string external;

3:

//users/user[@loginID=$loginID and @password=$password]

XQueryXPath Injection
1:

// 

2:

String name = props.getProperty("name");

3:

String passwd = props.getProperty("password");

4:

Document doc = new Builder().build("users.xml");

5:

// XQuery

6:

XQuery xquery = new XQueryFactory().createXQuery(new File("dologin.xq"));

7:

Map vars = new HashMap();

8:

vars.put("loginID", name);

9:

vars.put("password", passwd);

10:

Nodes results = xquery.execute(doc, null, vars).toNodes();

11:

for (int i=0; i < results.size(); i++) {


System.out.println(results.get(i).toXML());

12:
13:

XQuery

.

. 
[1] CWE-643 XPath - http://cwe.mitre.org/data/definitions/643.html
[2] OWASP Top 10 2010 A1 Injection Flaws
[3] Web Application Security Consortium. "XPath Injection".
http://www.webappsec.org/projects/threat/classes/xpath_injection.shtml



24. XQuery
(Failure to Sanitize Data within XQuery Expressions (XQuery injection))
.
XQueryXML 
, 
.

. 
prepareExpression() (Parameterized
Query), .

.
- JAVA
1:

2:

// 

3:

String name = props.getProperty("name");

4:

Hashtable env = new Hashtable();

5:

env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

6:

env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=rootDir");

7:

javax.naming.directory.DirContext ctx = new InitialDirContext(env);

8:

javax.xml.xquery.XQDataSource xqds =
(javax.xml.xquery.XQDataSource) ctx.lookup("xqj/personnel");

9:
10:

javax.xml.xquery.XQConnection conn = xqds.getConnection();

11:
12:

String es = "doc('users.xml')/userlist/user[uname='" + name + "']";

13:

// Xquery

14:

XQPreparedExpression expr = conn.prepareExpression(es);

15:

XQResultSequence result = expr.executeQuery();

16:

while (result.next()) {

17:

String str = result.getAtomicValue();

18:

if (str.indexOf('>') < 0) {
System.out.println(str);

19:

20:
21:

(name)executeQuery
. something' or '='1 name
, .
(doc('users.xml')/userlist/user[uname='something' or '=')



- JAVA
1:

2:

// 

3:

String name = props.getProperty("name");

4:

Hashtable env = new Hashtable();

5:

env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

6:

env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=rootDir");

7:

javax.naming.directory.DirContext ctx = new InitialDirContext(env);

8:

javax.xml.xquery.XQDataSource xqds =
(javax.xml.xquery.XQDataSource) ctx.lookup("xqj/personnel");

9:
10:

javax.xml.xquery.XQConnection conn = xqds.getConnection();

11:
12:

String es = "doc('users.xml')/userlist/user[uname='$xpathname']";

13:

// Xquery

14:

XQPreparedExpression expr = conn.prepareExpression(es);

15:

expr.bindString(new QName("xpathname"), name, null);

16:

XQResultSequence result = expr.executeQuery();

17:

while (result.next()) {

18:

String str = result.getAtomicValue();

19:

if (str.indexOf('>') < 0) {
System.out.println(str);

20:

21:
22:

XQuery
bindXXX 
.

. 
[1] CWE-652 XQuery - http://cwe.mitre.org/data/definitions/652.html
[2] OWASP Top 10 2010 A1 Injection Flaws



25. 
(Reliance on Untrusted Inputs in a Security Decision)
.
.

.

. 
.
, 
.

.

.
- JSP
1:

<%

2:

String username = request.getParameter("username");

3:

String password = request.getParameter("password");

4:

if (username==nill || password==null || !isAuthenticatedUser(usename, password)) {


throw new MyException("");

5:
6:

7:

Cookie userCookie = new Cookie("user",username);

8:

Cookie authCookie = new Cookie("authenticated","1");

9:
10:

response.addCookie(userCookie);

11:

response.addCookie(authCookie);

12:

%>

authenticated. 
,
WAS(Web Application Server) .



- JSP
1:

<%

2:

String username = request.getParameter("username");

3:

String password = request.getParameter("password");

4:

if (username==nill || password==null || !isAuthenticatedUser(usename, password)) {


throw new MyException("");

5:
6:

7:

// .

8:

HttpSession ses = new HttpSession(true);

9:

ses.putValue("user",username);

10:

ses.putValue("authenticated","1");

11:

%>

.

.
[1] CWE-807 - http://cwe.mitre.org/data/definitions/807.html
CWE-247 DNS Lookup- http://cwe.mitre.org/data/definitions/247.html
CWE-302 -- http://cwe.mitre.org/data/definitions/302.html
CWE-784 - http://cwe.mitre.org
/data/definitions/784.html
[2] CWE/SANS Top 25 Most Dangerous Software Errors



2 API
API(Application Programming Interface)    
, 
. API API
.

1. J2EE: 
(J2EE Bad Practices: Direct Management of Connections)
.
J2EE 
J2EE .

. 
J2EE .

.
- JAVA
1:

public class U245 extends

javax.servlet.http.HttpServlet {

private Connection conn;

2:
3:

public void dbConnection(String url, String user, String pw) {

4:

try {

5:

// j2ee .

6:

conn =

7:

DriverManager.getConnection(url, user, pw);

8:

} catch (SQLException e) {

9:

System.err.println("...");
} finally {

10:

11:
12:

(connection).



- JAVA
1:

public class S245 extends

javax.servlet.http.HttpServlet {

private static final String CONNECT_STRING =

2:

"jdbc:ocl:orcl";

3:

public void dbConnection() throws NamingException, SQLException {

4:

Connection conn = null;

5:

try {

6:
7:

// .

8:

InitialContext ctx = new InitialContext();

9:

DataSource datasource = (DataSource) ctx.lookup(CONNECT_STRING);


conn = datasource.getConnection();

10:

} catch (SQLException e) {

11:

12:

} finally {

13:

if ( conn != null )

14:

conn.close();

15:

16:
17:

.

. 
[1] CWE-245 J2EE: - http://cwe.mitre.org/data/definitions/245.html



2. J2EE: (J2EE Bad Practices: Direct Use of Sockets)


.
J2EE , 
, , .

. 
.

.
- JAVA
1:

public class S246 extends

2:

private Socket socket;

javax.servlet.http.HttpServlet {

3:

protected void doGet(HttpServletRequest request,

4:

HttpServletResponse

5:

response) throws ServletException {

6:

try {

7:

// J2EE      (Socket) 
.

socket = new Socket("kisa.or.kr", 8080);

8:

} catch (UnknownHostException e) {

9:

System.err.println("UnknownHostException

10:

System.err.println("IOException

12:

occured");

} finally {

13:

...

14:

15:

16:
17:

occured");

} catch (IOException e) {

11:

doGet (Socket).



- JAVA
1:

public class S246 extends


protected

2:

javax.servlet.http.HttpServlet {

void doGet(HttpServletRequest request,


HttpServletResponse response) throws

3:

ServletException {

4:

ObjectOutputStream oos = null;

5:

ObjectInputStream ois = null;

6:

try {

7:

// WASURL Connection, EJB.

8:

URL url = new URL("http://127.0.0.1:8080/DataServlet");

9:

URLConnection urlConn = url.openConnection();

10:

urlConn.setDoOutput(true);

11:

oos = new ObjectOutputStream(urlConn.getOutputStream());

12:

oos.writeObject("data");

13:

ois = new ObjectInputStream(urlConn.getInputStream());


Object obj = ois.readObject();

14:

} catch (ClassNotFoundException e) {

15:

System.err.println("Class

16:

} catch (IOException e) {

17:

System.err.println("URL

18:

Connection Error occured");

} finally {

19:

20:

21:

22:
23:

Not Found");

.

. 
[1] CWE-246 J2EE: - http://cwe.mitre.org/data/definitions/246.html



3. DNS lookup
(Reliance on DNS Lookups in a Security Decision )
.
DNS . DNS . DNS
, SWDNS 
. DNS, IP 
.

. 
IP DNS .

.
- JAVA
1:

public class U247 extends

HttpServlet {

2:

public void doGet(HttpServletRequest req,

3:

throws ServletException,

HttpServletResponse res)

IOException {

4:

boolean trusted = false;

5:

String ip = req.getRemoteAddr();

6:
7:

// IP .

8:

InetAddress addr = InetAddress.getByName(ip);

9:
10:

// IP(trustme.com).

11:

if (addr.getCanonicalHostName().endsWith("trustme.com") ) {
trusted = true;

12:
13:

14:

if (trusted) {

15:

16:

} else {

17:

18:

19:
20:

DNS . DNS 


.



- JAVA
1:

public class S247 extends

HttpServlet {

2:

public void doGet(HttpServletRequest req, HttpServletResponse

3:

throws ServletException,

4:

res)

IOException {

5:
6:

String ip = req.getRemoteAddr();

7:

if ( ip == null || "".equals(ip) )
return ;

8:
9:

String trustedAddr = "127.0.0.1";

10:
11:

if (ip.equals(trustedAddr) ) {

12:

13:

} else {

14:

15:

16:

17:
18:

DNS lookupIP .

. 
[1] CWE-247 DNS lookup- http://cwe.mitre.org/data/definitions/247.html
[2] SANS Top 25 2010 - (SANS 2010) Porus Defense - CWE ID 807 Reliance on Untrusted
Inputs in a Security Decision



4. J2EE: System.exit() (J2EE Bad PracticesUse of System.exit())


.
J2EE System.exit().

. 
J2EE System.exit.

.
- JAVA
1:

public class U382 extends

HttpServlet {

public void doPost(HttpServletRequest request,

2:

throws ServletException,

3:

HttpServletResponse response)

IOException {

4:
5:

FileHandler handler = new

6:

Logger logger =

7:

logger.addHandler(handler);

8:

try {

FileHandler("errors.log");

Logger.getLogger("com.mycompany");

9:

do_something(logger);

10:

} catch (IOException ase) {


// J2EE System.exit()

11:

System.exit(1);

12:

13:

14:
15:
16:

private void do_something(Logger logger) throws

17:

18:

IOException {

doPost() System.exit().



- JAVA
1:

public class S382 extends

HttpServlet {

public void doPost(HttpServletRequest request,

2:

throws ServletException,

3:

HttpServletResponse response)

IOException {

4:
5:

FileHandler handler = new

6:

Logger logger =

7:

logger.addHandler(handler);

8:

try {

FileHandler("errors.log");

Logger.getLogger("com.mycompany");

9:

do_something(logger);

10:

} catch (IOException ase) {

11:

logger.info("Caught:

12:

// System.exit(1).

" + ase.toString());

// System.exit(1);

13:

14:

15:
16:
17:

private void do_something(Logger logger) throws

18:

19:

IOException {

System.exit()doPost .

. 
[1] CWE-382 J2EE: System.exit() - http://cwe.mitre.org/data/definitions/382.html



5. null (Missing Check for Null Parameter)


.
Java Object.equals(), Comparable.compareTo() Comparator.compare()
null. 
.

. 
Object.equals(), Comparable.compareTo()Comparator.compare() 
null.

.
- JAVA
1:

public class U9201 implements java.util.Comparator {


public int compare(Object o1, Object o2) {

2:
3:

// o1, o2null 

4:

int i1 = o1.hashCode();

5:

int i2 = o2.hashCode();

6:

int ret;

7:

if (i1 > i2) {

8:

else if (i1 == i2) {

ret = 0;

9:

else {

10:

return ret;

ret = -1;

}
}

11:

12:
13:

ret = 1;

null.



- JAVA
1:

public class S9201 implements java.util.Comparator {


public int compare(Object o1, Object o2) {

2:
3:

int ret;

4:

// null .

5:

if (o1 != null && o2 != null) {

6:

int i1 = o1.hashCode();

7:

int i2 = o2.hashCode();

8:

if (i1 > i2) {

9:

else if (i1 == i2) {

ret = 0;

10:

else {

ret = -1;

}
}

} else

11:

ret = -1;

12:

return ret;

13:

14:

15:
16:

ret = 1;

null.

. 
[1] CWE-398 - http://cwe.mitre.org/data/definitions/398.html



6. EJB: (EJB Bad Practices: Use of Sockets)


.
Enterprise JavaBeans(EJB) bean(ServerSocket)
. EJB bean

EJB        

bean ServerSocket
.

. 
EJB .

.
- JAVA
1:
2:

public void function_test() throws IOException {

3:

ServerSocket s = new ServerSocket(1122);

4:

Socket clientSocket = serverSocket.accept();

5:
6:

7:

EJB .

- JAVA
1:
2:

public void function_test() throws IOException {

3:

// EJBserver socket .

4:

// ServerSocket s = new ServerSocket(1122);

8:

// Socket clientSocket = serverSocket.accept();

9:
5:

6:

EJB .

. 
[1] CWE-577 EJB: - http://cwe.mitre.org/data/definitions/577.html



7. equals()hashCode() 
(Object Model Violation: Just one of equals() and hashCode() Defined)
.
Java , Java.
"a.equals(b) == true""a.hashCode() == b.hashCode()" . 
equals()hashCode().

. 
equals()hashCode()hashCode()
equals().

.
- JAVA
1:

public class U581 {

2:

3:

// equals()

4:

public boolean equals(Object obj) {

5:

boolean ret;

6:

if (obj != null) {

7:

int i1 = this.hashCode();

8:

int i2 = obj.hashCode();

9:

if (i1 == i2) {

10:

else {

} else {

11:

ret = false;

12:
13:

14:

return ret;
}

15:

16:
17:

ret = true;

ret = false;

equals()hashCode() .



- JAVA
1:

public class S581 {

2:

3:

// equals()

4:

public boolean equals(Object obj) {

5:

boolean ret;

6:

if (obj != null) {

7:

int i1 = this.hashCode();

8:

int i2 = obj.hashCode();

9:

if (i1 == i2) {

10:

else {

} else {

11:

ret = false;

12:

13:

return ret;

14:
15:

16:

// hashCode()

17:

public int hashCode() {


return new HashCodeBuilder(17, 37).toHashCode();

18:

19:

20:
21:

ret = true;

ret = false;

equals()hashCode() .

. 
[1] CWE-581 equals()hashCode() - http://cwe.mitre.org/data/definitions/581.html



3
. 
. , , , ,
.

1. (Hard-coded Password)
.
SW, 
. 
. 
, SW 
.

. 
.
SW , "-" 
.

.
- JAVA
1:

public class U259 {


private Connection conn;

2:
3:

public Connection DBConnect(String url, String id) {

4:

try {

5:

// password-.

6:

conn =

7:

DriverManager.getConnection(url, id, "tiger");

8:

} catch (SQLException e) {

9:

System.err.println("...");
}

10:

return conn;

11:

12:

13:
14:

        
.



- JAVA
1:

public class S259 {


public Connection connect(Properties props) throws NoSuchAlgorithmException,

2:

NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,


BadPaddingException {
try {

3:
4:

String url = props.getProperty("url");

5:

String id = props.getProperty("id");

6:

String pwd = props.getProperty("passwd");

7:

//, 

8:

if (url != null && !"".equals(url) && id != null &&

9:

&& pwd != null &&

10:

!"".equals(id)

!"".equals(pwd)) {

11:

KeyGenerator kgen = KeyGenerator.getInstance("Blowfish");

12:

SecretKey skey = kgen.generateKey();

13:

byte[] raw = skey.getEncoded();

14:

SecretKeySpec skeySpec = new SecretKeySpec(raw, "Blowfish");

15:
16:

Cipher cipher = Cipher.getInstance("Blowfish");

17:

cipher.init(Cipher.DECRYPT_MODE, skeySpec);

18:

byte[] decrypted_pwd = cipher.doFinal(pwd.getBytes());

19:

pwd = new String(decrypted_pwd);


conn = DriverManager.getConnection(url, id, pwd);

20:

21:

} catch (SQLException e) {

22:

23:

,
.

- JAVA
1:

try {
Connection con = DriverManager.getConnection(url, "scott", "tiger");

2:

......

3:
4:

} catch (SQLException e) {
throw new MyException("DB );

5:
6:

DB Connection , .


.



- JAVA
1:

/* mkstore -wrl /mydir -createCredential MyTNSName some_user some_password */

2:

try {

3:

System.setProperty("oracle.net.tns_admin", "/mydir");

4:

java.util.Properties info = new java.util.Properties();

5:

// DB oracle .

6:

info.put("oracle.net.wallet_location",

7:

"(SOURCE=(METHOD=file)(METHOD_DATA=(DIRECTORY=/mydir)))");

8:

OracleDataSource ds = new OracleDataSource();

9:

ds.setURL("jdbc:oracle:thin:@MyTNSName");

10:

ds.setConnectionProperties(info);
Connection conn = ds.getConnection();

11:
12:

} catch (SQLException e) {
throw new MyException("DB );

13:
14:

mkstoreDB .

. 
[1] CWE-259 - http://cwe.mitre.org/data/definitions/259.html
CWE-321 - http://cwe.mitre.org/data/definitions/321.html
CWE-798 - http://cwe.mitre.org/data/definitions/798.html
[2] SANS Top 25 2010 - (SANS 2010) Porus Defense - CWE ID 798 Use of Hard-coded
Credentials



2. (Improper Authorization)
.
SW
, .

. 

(attack surface).
ACL(Access Control List).
     .  , JAAS Authorization Framework
OWASP ESAPI Access Control .

.
- JAVA
1:

public void f(String sSingleId, int iFlag, String sServiceProvider, String sUid, String sPwd)
{

2:

3:

env.put(Context.INITIAL_CONTEXT_FACTORY, CommonMySingleConst.INITCTX);

4:

env.put(Context.PROVIDER_URL, sServiceProvider);

5:

// LDAP 

6:

env.put(Context.SECURITY_AUTHENTICATION, "none");

7:

env.put(Context.SECURITY_PRINCIPAL, sUid);

8:

env.put(Context.SECURITY_CREDENTIALS, sPwd);

9:

name LDAP 
, . anonymous
binding. 
.
- JAVA
1:

public void f(String sSingleId, int iFlag, String sServiceProvider, String sUid, String sPwd)
{

2:

3:

env.put(Context.PROVIDER_URL, sServiceProvider);

4:

// .

5:

env.put(Context.SECURITY_AUTHENTICATION, "simple");

6:

env.put(Context.SECURITY_PRINCIPAL, sUid);

7:

env.put(Context.SECURITY_CREDENTIALS, sPwd);

8:

IDpassword.



- JSP
1:

<%

2:

String username = request.getParameter("username");

3:

String password = request.getParameter("password");

4:

if (username==nill || password==null || !isAuthenticatedUser(usename, password)) {


throw new Exception("invalid username or password");

5:
6:

7:
8:

String msgId = request.getParameter("msgId");

9:

if ( msgId == null ) {
throw new MyException("");

10:
11:

12:

Message msg = LookupMessageObject(msgId);

13:

if ( msg != null ) {

14:

out.println("From: " + msg.getUserName()");

15:

out.println("Subject: " + msg.getSubField()");

16:

out.println("\n" + msg.getBodyField()");

17:

18:

%>

, . 


.

- JSP
1:

<%

2:

String username = request.getParameter("username");

3:

String password = request.getParameter("password");

4:

if (username==nill || password==null || !isAuthenticatedUser(usename, password)) {


throw new MyException("");

5:
6:

7:
8:

String msgId = request.getParameter("msgId");

9:

if ( msgId == null ) {
throw new MyException("");

10:
11:

12:

Message msg = LookupMessageObject(msgId);

13:
14:

if ( msg != null && username.equals(msg.getUserName()) ) {

15:

out.println("From: " + msg.getUserName()");

16:

out.println("Subject: " + msg.getSubField()");

17:

out.println("\n" + msg.getBodyField()");

18:

} else { throw new MyException("); }

19:

%>

, .



. 
[1] CWE-285 - http://cwe.mitre.org/data/definitions/285.html
CWE-219 - http://cwe.mitre.org/data/definitions/219.html
[2] OWASP Top 10 2010 - (OWASP 2010) A8 Failure to Restrict URL Access
[3] SANS Top 25 2010 - (SANS 2010) Porus Defense - CWE ID 285 Improper Authorization
[4] NIST. "Role Based Access Control and Role Based Security"
[5] M. Howard and D. LeBlanc. "Writing Secure Code". Chapter 4, "Authorization" Page 114;
Chapter 6, "Determining Appropriate Access Control" Page 171. 2nd Edition. Microsoft. 2002



3. (Cross-Site Request Forgery (CSRF))


.
CSRF 
. 

.
, 
GET 
.

. 
form data postingPOST .
OWASP CSRFGuard anti-CSRF .

.
- JAVA
1:

2:

<form name="MyForm" method="get" action="customer.do">

3:

<input type=text name="txt1">

4:

<input type=submit value=">"

5:

</form>

6:

GET  form  URL    GET 


formCSRF .

- JAVA
1:

2:

<form name="MyForm" method="post" action="customer.do">

3:

<input type=text name="txt1">

4:

<input type=submit value=">"

5:

</form>

6:

Post .

. 
[1] CWE-352 - http://cwe.mitre.org/data/definitions/352.html
[2] OWASP Top Ten 2010 Category A5 - Cross-Site Request Forgery(CSRF)
[3] SANS Top 25 2010 - (SANS 2010) Insecure Interaction - CWE ID 352 Cross-Site Request Forgery



4. (Insufficient Session Expiration)


.

.

. 

.

.
- JAVA
1:

public class U613 extends HttpServlet {


public void noExpiration(HttpSession session) {

2:
3:

if (session.isNew()) {

4:

// -1.
session.setMaxInactiveInterval(-1);

5:

6:

7:
8:

-1, . 
.

- JAVA
1:

public class S613 extends HttpServlet {


public void noExpiration(HttpSession session) {

2:
3:

if (session.isNew()) {

4:

// .
session.setMaxInactiveInterval(12000);

5:

6:

7:
8:


.

. 
[1] CWE-613 - http://cwe.mitre.org/data/definitions/613.html



5. : (Password Management: Heap Inspection)


.
 String   .  String 
(immutable), JVM
, . 
, 
.

. 
String , 
. .

.
- JAVA
1:

2:

// private static final long serialVersionUID = 1L;

3:

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

4:
5:

6:
7:

protected void doPost(HttpServletRequest request, HttpServletResponse response) {


String pass = request.getParameter("pass");

8:
9:

if (pass != null) {

10:

if (-1 != pass.indexOf("<"))

11:

System.out.println("bad input");

12:

else {

13:
14:

// .

15:

String str = new String(pass);

16:

17:

} else {

18:

19:

System.out.println("bad

input");

String 
.



- JAVA
1:

2:

// private static final long serialVersionUID = 1L;

3:

protected void doGet(HttpServletRequest request,


HttpServletResponse

4:

5:
6:

response) throws ServletException, IOException {

7:
8:

protected void doPost(HttpServletRequest request, HttpServletResponse response) {

9:

// .

10:

String pass = request.getParameter("psw");

11:

// .

12:

if (pass != null) {
if (-1 != pass.indexOf("<"))

13:

System.out.println("bad input");

14:

else {

15:

// password..

16:

// String str = new String(pass);

17:

18:

} else {

19:
20:

21:

System.out.println("bad input");

(: ),
. 
.

. 
[1] CWE-226 - http://cwe.mitre.org/data/definitions/226.html
[2] OWASP Top 10 2010 - (OWASP 2010) A7 Insecure Cryptographic Storage



6. (Hard-coded Username)
.
SW, 
. 
, 
. , 
SW .

. 
.

.
- JAVA
1:

2:

private Connection conn;

3:
4:

// .

5:

public Connection DBConnect() {

6:

String url = "DBServer";

7:

String id = "scott";

8:

String password = "tiger";

9:

try {

10:

conn = DriverManager.getConnection(url, id, password);

11:
12:

} catch (SQLException e) {

13:

return conn;

14:

, 
. .



- JAVA
1:

2:

private Connection conn;

3:
4:

// .

5:

public Connection DBConnect(String id, String password) {

6:

String url = "DBServer";

7:

try {

8:

String CONNECT_STRING = url + ":" + id + ":" + password;

9:

InitialContext ctx = new InitialContext();

10:

DataSource datasource = (DataSource) ctx.lookup(CONNECT_STRING);

11:

// connection.

12:

conn = datasource.getConnection();

13:
14:

} catch (SQLException e) {

15:

return conn;

16:


. , 
.

. 
[1] CWE-255 - http://cwe.mitre.org/data/definitions/255.html
[2] OWASP Top 10 2010 - (OWASP 2010) A7 Insecure Cryptographic Storage
[3] Security Technical Implementation Guide Version 3 - (STIG 3) APP3210.1 CAT II



7. (Plaintext Storage of Password)


.

.     ,    
. 
.

. 
, 

.
- JAVA
1:

package testbed.unsafe;

2:

import java.sql.*;

3:

import java.util.Properties;

4:

import java.io.*;

5:

public class U256 {


public void f(String url, String name) throws IOException {

6:
7:

Connection con = null;

8:

try {
Properties props = new Properties();

9:
10:

FileInputStream in = new FileInputStream("External.properties");

11:

byte[] pass = new byte[8];

12:

// password .
in.read(pass);

13:

// password DB connection .

14:

con = DriverManager.getConnection(url, name, new String(pass));

15:

con.close();

16:

} catch (SQLException e) {

17:

System.err.println("SQLException Occured ");

18:

} finally {

19:

try {

20:

if (con != null)

21:
22:

con.close();

23:

} catch (SQLException e) {
System.err.println("SQLException Occured ");

24:

25:

26:

27:
28:

String 
. , 



.
- JAVA
1:

package testbed.safe;

2:

import java.sql.*;

3:

import java.util.Properties;

4:

import java.io.*;

5:

public class S256 {


public void f(String[] args) throws IOException {

6:
7:

Connection con = null;

8:

try {
Properties props = new Properties();

9:
10:

FileInputStream in = new FileInputStream("External.properties");

11:

props.load(in);

12:

String url = props.getProperty("url");

13:

String name = props.getProperty("name");


// password, .

14:
15:

String pass = decrypt(props.getProperty("password"));

16:

// .

17:

con = DriverManager.getConnection(url, name, pass);


} catch (SQLException e) {

18:

System.err.println("SQLException Occured ");

19:

} finally {

20:

try {

21:

if (con != null)

22:
23:

con.close();

24:

} catch (SQLException e) {
System.err.println("SQLException Occured ");

25:

26:

27:

28:
29:

.

. 
[1]. CWE-256 - http://cwe.mitre.org/data/definitions/256.html
[2]. J. Viega and G. McGraw. "Building Secure Software: How to Avoid Security Problems
the Right Way". 2002.



8. (Password in Configuration File)


.
. 
, . ,

.

. 
, .

.
- JAVA
1:

package testbed.unsafe;

2:

import java.io.FileInputStream;

3:

import java.io.FileNotFoundException;

4:

import java.io.IOException;

5:

import java.sql.Connection;

6:

import java.sql.DriverManager;

7:

import java.sql.SQLException;

8:

public class U260 {

9:

Connection con = null;

11:

byte[] b = new byte[1024];

12:

boolean result = false;

13:

try {

14:

FileInputStream fs = new FileInputStream("sample.cfg");

15:

// .

16:

fs.read(b);

17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:



public boolean connectTest(String url, String usr) {

10:

// 
String password = new String(b);
// DB .
con = DriverManager.getConnection(url, usr, password);
} catch (FileNotFoundException e) {
System.err.println("File Not Found Exception Occurred!");
} catch (IOException e) {
System.err.println("I/O Exception Occurred!");
} catch (SQLException e) {
System.err.println("SQL Exception Occurred!");
} finally {
try {
if (con != null) {
con.close();

result = true;

31:

32:

} catch (SQLException e) {

33:

System.err.println("SQL Exception Occurred!");

34:

35:

36:

return result;

37:

38:
39:

configuration 
. 
.

- JAVA
1:
2:

public class S260 {


public boolean connectTest(String url, String usr, Key key) {

3:

Connection con = null;

4:

byte[] b = new byte[1024];

5:

boolean result = false;

6:
7:

try {
FileInputStream fs = new FileInputStream("sample.cfg");
if (fs == null || fs.available() <= 0) return false;

8:
9:

// .
int length = fs.read(b);

10:

if (length == 0) {

11:

result = false;

12:
13:

} else {
// .

14:
15:

Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

16:

cipher.init(Cipher.DECRYPT_MODE, key);

17:

byte[] db = cipher.doFinal(b);
// 

18:

String password = new String(db, "utf-8");

19:

// DB

20:

con = DriverManager.getConnection(url, usr, password);

21:
22:
23:
24:
25:
26:
27:
28:
29:
30:

}
} catch (FileNotFoundException e) {
System.err.println("File Not Found Exception Occurred!");
} catch (IOException e) {
System.err.println("I/O Exception Occurred!");
} catch (SQLException e) {
System.err.println("SQL Exception Occurred!");
} catch (NoSuchAlgorithmException e) {
System.err.println("NoSuchAlgorithmException Occurred!");



31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:

} catch (NoSuchPaddingException e) {
System.err.println("NoSuchPaddingException Occurred!");
} catch (InvalidKeyException e) {
System.err.println("InvalidKeyException Occurred!");
} catch (IllegalBlockSizeException e) {
System.err.println("IllegalBlockSizeException Occurred!");
} catch (BadPaddingException e) {
System.err.println("BadPaddingException Occurred!");
} finally {
try {
if (con != null) {
con.close();

42:

result = true; } } catch (SQLException e) {

43:
44:
45:

System.err.println("SQL Exception Occurred!");


} } return result;

} }

(, ),
.

. 
[1] CWE-260 - http://cwe.mitre.org/data/definitions/260.html
[2]. J. Viega and G. McGraw. "Building Secure Software: How to Avoid Security Problems
the Right Way". 2002.



9. (Weak Cryptography for Passwords)


.
SW 
. base64
.

. 

. 128
.

.
- JAVA

1:
2:

public boolean DBConnect() throws SQLException {

3:

String url = "DBServer";

4:

String usr = "Scott";

5:

Connection con = null;

6:

7:

try {

8:

Properties prop = new Properties();

9:

prop.load(new FileInputStream("config.properties"));

10:

11:

// 64bitdecoding.

12:

byte password[] = Base64.decode(prop.getProperty("password"));

13:
14:

// .

15:

con = DriverManager.getConnection(url, usr, password.toString());

16:

} catch (FileNotFoundException e) {

17:

e.printStackTrace();

18:

} catch (IOException e) {

19:

e.printStackTrace();

20:

21:

 base64  configuration   . Basea64 


.



- JAVA
1:

2:

public boolean DBConnect() throws SQLException {

3:

String url = "DBServer";

4:

String usr = "Scott";

5:

Connection con = null;

6:

7:

try {

8:

Properties prop = new Properties();

9:

prop.load(new FileInputStream("config.properties"));

10:

11:

// AES .

12:

String password = decrypt(prop.getProperty("password"));

13:
14:

con = DriverManager.getConnection(url, usr, password);

15:

} catch (FileNotFoundException e) {

16:

e.printStackTrace();

17:

} catch (IOException e) {

18:

e.printStackTrace();

19:

20:

G G }

21:

private static String decrypt(String encrypted) throws Exception {

SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES");

22:
23:

Cipher cipher = Cipher.getInstance("AES");

24:

cipher.init(Cipher.DECRYPT_MODE, skeySpec);

25:

byte[] original = cipher.doFinal(hexToByteArray(encrypted));


return new String(original);

26:
27:

128
.

. 
[1] CWE-261 - http://cwe.mitre.org/data/definitions/261.html
[2] OWASP Top 10 2010 - (OWASP 2010) A7 Insecure Cryptographic Storage
[3] J. Viega and G. McGraw. "Building Secure Software: How to Avoid Security Problems
the Right Way". 2002.



10. 
(Missing Authentication for Critical Function)
. 
         , SW
.

. 
.
().
. OpenSSLESAPI
.

.
- JAVA
1:

public void sendBankAccount(String accountNumber,double balance) {


...

2:
3:

BankAccount account = new BankAccount();

4:

account.setAccountNumber(accountNumber);

5:

account.setToPerson(toPerson);

6:

account.setBalance(balance);

7:

AccountManager.send(account);
...

8:
9:

.

- JAVA
1:

public void sendBankAccount(HttpServletRequest request, HttpSession session,


String accountNumber,double balance) {

2:
3:

...

4:

// credential.

5:

String newUserName = request.getParameter("username");

6:

String newPassword = request.getParameter("password");

7:

if ( newUserName == null || newPassword == null ) {


throw new MyEception(":);

8:
9:

10:
11:

// credential.

12:

String password = session.getValue("password");

13:

String userName = session.getValue("username");

14:



15:

// .
if ( isAuthenticatedUser() && newUserName.equal(userName) &&

16:
17:

newPassword.equal(password) ) {

18:

BankAccount account = new BankAccount();

19:

account.setAccountNumber(accountNumber);

20:

account.setToPerson(toPerson);

21:

account.setBalance(balance);

22:

AccountManager.send(account);

23:

24:

...

25:

.

. 
[1] CWE-306 - http://cwe.mitre.org/data/definitions/306.html
CWE-302 -- http://cwe.mitre.org/data/definitions/302.html
CWE-307 - http://cwe.mitre.org/data/definitions/307.html
CWE-287 - http://cwe.mitre.org/data/definitions/287.html
CWE-602 - http://cwe.mitre.org/data/definitions/602.html
[2] CWE/SANS Top 25 Most Dangerous Software Errors, http://cwe.mitre.org/top25/



11. : 
(Weak Encryption: Insufficient Key Size)
.
. RSA
1024 
Symmetric 128.

. 
1024 .

.
- JAVA
1:

2:

public void target() throws NoSuchAlgorithmException {

3:

KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");

4:

// Key generator

5:

keyGen.initialize(512);
KeyPair myKeys = keyGen.generateKeyPair();

6:
7:

RSA , 


.

- JAVA
1:

2:

public void target() throws NoSuchAlgorithmException {

3:

KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");

4:

// Key generator1024bit.

5:

keyGen.initialize(1024);
KeyPair myKeys = keyGen.generateKeyPair();

6:
7:

1024.

. 
[1] CWE-310 - http://cwe.mitre.org/data/definitions/310.html
[2] OWASP Top 10 2010 - (OWASP 2010) A7 Insecure Cryptographic Storage



12. (Missing Encryption of Sensitive Data)


. 
, SW
.

. 
, , 
, SHA-256.
SW .
   , SSL  HTTPS   Secure
Channel.

.
- JAVA
1:

String username = request.getParameter("username");

2:

String password = request.getParameter("password");

3:

PreparedStatement p=null;

4:

try {

5:

......

6:

if (username==nill || password==null
|| !isAuthenticatedUser(usename, password)) {

7:

throw new MyException("");

8:

9:

p = conn.prepareStatement("INSERT INTO employees VALUES(?,?)");

10:
11:

p.setString(1,username);

12:

p.setString(2,password);
p.execute();

13:

......

14:
15:

DB.

- JAVA
1:

String username = request.getParameter("username");

2:

String password = request.getParameter("password");

3:

PreparedStatement p=null;

4:

try {

5:

......

6:

if (username==nill || password==null

7:
8:



|| !isAuthenticatedUser(usename, password)) {
throw new MyException("");

9:
10:

MessageDigest md = MessageDigest.getInstance("SHA-256");

11:

md.reset();
......

12:
13:

// DB.
password =md.digest(password.getBytes());

14:

p = conn.preparedStatement("INSERT INTO employees VALUES(?,?)");

15:
16:

p.setString(1,username);

17:

p.setString(2,password);
p.execute();

18:

......

19:
20:

.

. 
[1] CWE-311 - http://cwe.mitre.org/data/definitions/311.html
CWE-312 - http://cwe.mitre.org/data/definitions/312.html
CWE-319 - http://cwe.mitre.org/data/definitions/319.html
CWE-614 HTTPS - http://cwe.mitre.org/data/definitions/614.html
[2] CWE/SANS Top 25 Most Dangerous Software Errors, http://cwe.mitre.org/top25/



13. 
(Cleartext Transmission of Sensitive Information)
.
SW
, .

. 
.

.
- JAVA
1:

2:

String getPassword()

3:

return "secret";

4:
5:

void foo() {

6:

try

7:

8:

Socket socket = new Socket("taranis", 4444);

9:

PrintWriter out = new PrintWriter(socket.getOutputStream(),

10:

String password = getPassword();

11:

out.write(password);
} catch (FileNotFoundException e) {

12:

13:
14:

true);

(Plain text).
.



- JAVA
1:

2:

String getPassword()

4:

return "secret_password";

3:

5:
6:

void foo() {
try {

7:
8:

Socket socket = new Socket("taranis", 4444);

9:

PrintStream out = new PrintStream(socket.getOutputStream(), true);

10:

Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");

11:

String password = getPassword();

12:

byte[] encryptedStr = c.update(password.getBytes());


out.write(encryptedStr, 0, encryptedStr.length);

13:

} catch (FileNotFoundException e) {

14:

15:
16:

128
.

. 
[1] CWE-319 - http://cwe.mitre.org/data/definitions/319.html
CWE-311 - http://cwe.mitre.org/data/definitions/311.html
[2] OWASP Top 10 2007 - (OWASP 2007) A9 Insecure Communications



14. (Use of Hard-coded Cryptographic Key)


.

. SW 
. 
, brute-force 
.

. 
.
AES, ARIA, SEED, 3DES , 
RSA 1024. MD4, MD5, SHA1.

.
- JAVA

1:
2:

private Connection con;

3:

4:

public String encryptString (String usr) {

5:

Stringc seed = "68af404b513073584c4b6f22b6c63e6b";

6:

7:

try {

8:

// encrypt.

SecretKeySpec skeySpec = new SecretKeySpec(seed.getBytes(), "AES");

9:
10:
11:

// 

12:

..

13:

} catch (SQLException e) {

14:
15:

16:

return con;

17:

18:

         
.



- JAVA

1:
2:

private Connection con;

3:

4:

public String encryptString (String usr) {

5:

Stringc seed = null;

6:

7:

try {

// .

8:
9:

seed = getPassword("./password.ini");
// .

10:
11:

seed = decrypt(seed);

12:

// encrypt.

13:

// use key coss2

SecretKeySpec skeySpec = new SecretKeySpec(seed.getBytes(), "AES");

14:
15:
16:

// 

17:

..

18:

} catch (SQLException e) {

19:
20:

21:

return con;

22:

23:

24:

        
.

. 
[1] CWE-321 - http://cwe.mitre.org/data/definitions/321.html



15. : RSA
(Weak Encryption: Inadequate RSA Padding)
.
OAEP RSA . RSA 
. 
RSA .

. 
RSA ("RSA/NONE/NoPadding"), 
.

.
- JAVA
1:

2:

public Cipher getCipher() {


Cipher rsa = null;

3:
4:

try {

5:
6:

// RSA NoPadding

7:

rsa = javax.crypto.Cipher.getInstance("RSA/NONE/NoPadding");

8:

} catch (java.security.NoSuchAlgorithmException e) {

9:

return rsa;

10:

RSA .

- JAVA
1:

2:

public Cipher getCipher() {


Cipher rsa = null;

3:
4:

try {

5:

/* paddingRSA. */

6:

rsa =

7:

javax.crypto.Cipher.getInstance("RSA/CBC/PKCS5Padding");

8:

} catch (java.security.NoSuchAlgorithmException e) {

9:

return rsa;

10:

. RSA
PKCS1 Padding PKCS5 Padding 
.



. 
[1] CWE-325 - http://cwe.mitre.org/data/definitions/325.html
[2] OWASP Top 10 2010 - (OWASP 2010) A7 Insecure Cryptographic Storage



16. : 
(Weak Cryptographic Hash: Hardcoded Salt)
.
,
. 
  ,   rainbow    
.

. 
Salt(nonce), 
.

.
- JAVA
1:

2:

public byte[] encrypt(byte[] msg) {

3:

// .

4:

final byte badsalt = (byte) 100;

5:

byte[] rslt = null;

6:

try {

7:
8:

MessageDigest md = MessageDigest.getInstance("SHA-256");

9:

// Salt .

10:

md.update(badsalt);
rslt = md.digest(msg);

11:

} catch (NoSuchAlgorithmException e) {

12:

System.out.println("Exception:

13:

return rslt;

15:
16:

" + e);

14:

, salt
.



- JAVA
1:

2:

public byte[] encrypt(byte[] msg) {


byte[] rslt = null;

3:
4:

try {

5:
6:

SecureRandom prng = SecureRandom.getInstance("SHA256PRNG");

7:

String randomNum = new Integer( prng.nextInt() ).toString();

8:

MessageDigest md = MessageDigest.getInstance("SHA-256");

9:
10:

// .

11:

md.update(randomNum.getBytes());

12:

rslt = md.digest(msg);
} catch (NoSuchAlgorithmException e) {

13:

System.out.println("Exception:

14:
15:

16:

return rslt;
}

17:
18:

" + e);

Salt(nonce), salt
.

. 
[1] CWE-326 - http://cwe.mitre.org/data/definitions/326.html
[2] OWASP Top 10 2010 - (OWASP 2010) A7 Insecure Cryptographic Storage



17. 
(Use of a Broken or Riscky Cryptographic Algorithm)
.
. 
         
. 
, 
. RC2, RC4, RC5, RC6, MD4, MD5, SHA1, DES 
.

. 
AES.

.
- JAVA
1:

2:

public byte[] encrypt(byte[] msg, Key k) {


byte[] rslt = null;

3:
4:

try {

5:
6:

// DES.

7:

Cipher c = Cipher.getInstance("DES");

8:

c.init(Cipher.ENCRYPT_MODE,

9:

rslt = c.update(msg);
} catch (InvalidKeyException e) {

10:

11:
12:

13:

return rslt;
}

14:
15:

k);

DES .



- JAVA

1:

public byte[] encrypt(byte[] msg, Key k) {

2:

byte[] rslt = null;

3:
4:

try {

5:

// DES AES .

6:
7:

Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");

8:

c.init(Cipher.ENCRYPT_MODE,
rslt = c.update(msg);

9:

} catch (InvalidKeyException e) {

10:

11:

12:

return rslt;

13:

14:
15:

k);

AES 128
.

. 
[1] CWE-327 - http://cwe.mitre.org/data/definitions/327.html
[2] OWASP Top 10 2010 - (OWASP 2010) A7 Insecure Cryptographic Storage
[3] SANS Top 25 2010 - (SANS 2010) Porus Defense - CWE ID 327 Use of a Broken or Risky
Cryptographic Algorithm
[4] Bruce Schneier. "Applied Cryptography". John Wiley &Sons. 1996.



18. (Use of Insufficiently Random Values)


.
. 
, SW
.

. 
seed
.

.
- JAVA
1:

2:

public double roledice() {


return Math.random();

3:

4:
5:

java.lang.Math random() seed.

- JAVA
1:

import java.util.Random;

2:

import java.util.Date;

3:

public int roledice() {

4:
5:

Random r = new Random();

6:

// setSeed() rlong.

7:

r.setSeed(new Date().getTime());

8:

// 

9:

return (r.nextInt()%6) + 1;
}

10:
11:

java.util.Random seed. 
Random .

. 
[1] CWE-330 - http://cwe.mitre.org/data/definitions/330.html
[2] SANS Top 25 2009 - (SANS 2009) Porus Defense - CWE ID 330 Use of Insufficiently
Random Values
[3] J. Viega and G. McGraw. "Building Secure Software: How to Avoid Security Problems the Right Way". 2002.



19. : 
(Password Management: Password in Redirect)
.
HTTP HTTP GET . 
, 
. , 
, .

. 
ServeletsendRedirect 
. GET POST
.

.
- JAVA
1:

2:

public void redirect(ServletRequest r, HttpServletResponse response)


throws IOException {

3:
4:

String usr = r.getParameter("username");

5:

String pass = r.getParameter("password");

6:
7:

// HTTP HTTP GET request.

8:

response.sendRedirect("j_security_check?j_username=" + usr + "&j_password=" + pass);

9:

  HTTP (Request) GET    


.



- JAVA
1:

2:

public void redirect(HttpServletRequest request, HttpServletResponse response)


throws IOException {

3:
4:

request.getSession().invalidate();

5:

String usr = request.getParameter("username");

6:

String pass = request.getParameter("password");

7:
8:

// .

9:

if ( usr == null || "".equals(usr)

10:

if ( !pass.matches("") && pass.indexOf("@!#") > 4 && pass.length() > 8 ) {

|| pass == null || "".equals(pass) ) return;

11:
12:

13:

// POST .

14:

String send = "j_security_check?j_username=" + usr + "&j_password=" + pass;


response.encodeRedirectURL(send);

15:
16:

GET POST 
.

. 
[1] CWE-359 - http://cwe.mitre.org/data/definitions/359.html
[2] OWASP Top 10 2010 - (OWASP 2010) A7 Insecure Cryptographic Storage



20. (Weak Password Requirements)


.
, 
, .

. 
.

.
- JAVA
public void doPost(HttpServletRequest request, HttpServletResponse response)

1:

throws IOException, ServletException {

2:
3:

try {

4:
5:

String url = "DBServer";

6:

String usr = "Scott";

7:
8:

// passwd

9:

String passwd = request.getParameter("passwd");

10:

Connection con = DriverManager.getConnection(url, usr, passwd);

11:

con.close();

12:

} catch (SQLException e) {

13:

System.err.println("...");

14:

15:
16:

(passwd)
.

- JAVA
1:

private static final String CONNECT_STRING = "jdbc:ocl:orcl";

2:
3:

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws IOException, ServletException {

4:
5:

try {

6:

request.getSession().invalidate();

7:

String passwd = request.getParameter("passwd");

8:
9:

// passwd

10:

if (passwd == null || "".equals(passwd)) return;



11:
12:

// , 

13:

if (Password.validate(passwd) == false) return;

14:
15:

InitialContext ctx = new InitialContext();

16:

DataSource datasource = (DataSource) ctx.lookup(CONNECT_STRING);

17:

Connection con = datasource.getConnection();

18:

con.close();

19:

} catch (SQLException e) {

20:

System.err.println("...");

21:

} catch (NamingException e) {

22:

System.err.println("...");

23:

24:
25:

(passwd)  (:     8  
), .

. 
[1] CWE-521 - http://cwe.mitre.org/data/definitions/521.html
[2] OWASP Top 10 2010 A3 Broken Authentication Session Management
http://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project



21. : (Cookie Security: Persistent Cookie)


.
.
, 
. , 
, 

. , 
, .

. 
.

.
- JAVA
1:

2:

public void makeCookie(ServletRequest request) {

3:

String maxAge = request.getParameter("maxAge");

4:

if (maxAge.matches("[0-9]+")) {

5:

String sessionID = request.getParameter("sesionID");

6:

if (sessionID.matches("[A-Z=0-9a-z]+")) {

7:

Cookie c = new Cookie("sessionID", sessionID);

8:

// .

9:

c.setMaxAge(Integer.parseInt(maxAge));
}

10:

11:
12:

javax.servlet.http.Cookie.setMaxAge 
.



- JAVA

1:
2:

public void makeCookie(ServletRequest request) {


String maxAge = request.getParameter("maxAge");

3:
4:

5:

if (maxAge == null || "".equals(maxAge)) return;

6:

if (maxAge.matches("[0-9]+")) {

7:

String sessionID = request.getParameter("sesionID");

8:

if (sessionID == null || "".equals(sessionID)) return;

9:

if (sessionID.matches("[A-Z=0-9a-z]+")) {

10:

Cookie c = new Cookie("sessionID", sessionID);

11:

// , .

12:

int t = Integer.parseInt(maxAge);

13:

if (t > 3600) {
t = 3600;

14:
15:

16:

c.setMaxAge(t);
}

17:
18:

19:


, .

. 
[1] CWE-539 - http://cwe.mitre.org/data/definitions/539.html
[2] OWASP Top 10 2010 - (OWASP 2010) A7 Insecure Cryptographic Storage



22. (Multiple Binds to the Same Port)


.
, 
.

. 
UDP 
.

.
- JAVA
1:

2:

final int INPORT = 1711;

3:

void foo () {
try {

4:

java.net.DatagramSocket socket = new java.net.DatagramSocket(INPORT);

5:

socket.setReuseAddress(true);

6:

} catch (SocketException e) { }

7:

8:
9:


.

- JAVA
1:

2:

final int INPORT = 1711;

3:

void foo () {

4:

try {
java.net.DatagramSocket socket = new java.net.DatagramSocket(INPORT);

5:

socket.setReuseAddress(false);

6:

} catch (SocketException e) { }

7:
8:

.

. 
[1] CWE-605 - http://cwe.mitre.org/data/definitions/605.html



23. HTTPS 


(Sensitive Cookie in HTTPS Session without Secure Attribute)
.
HTTPS.

.

. 
HTTPSCookie 
setSecure(true) .
: ()HTTPHTTPHTTPSsetSecure
.

.
- JAVA
1:

2:

private final String ACCOUNT_ID = "account";

3:
4:

public void setupCookies(ServletRequest r,


String acctID =

5:

HttpServletResponse response) {

r.getParameter("accountID");

6:

// 

7:

Cookie c = new Cookie(ACCOUNT_ID, acctID);


response.addCookie(c);

8:
9:

HTTPS, 
.



- JAVA
1:

2:

private final String ACCOUNT_ID = "account";

3:
4:

public void setupCookies(ServletRequest r,

5:

String acctID =

6:

// 

HttpServletResponse response) {

r.getParameter("accountID");

7:

if (acctID == null || "".equals(acctID)) return;

8:

String filtered_ID = acctID.replaceAll("\r", "");

9:
10:

Cookie c = new Cookie(ACCOUNT_ID, filtered_ID);

11:

// .
c.setSecure(true);

12:

response.addCookie(c);

13:
14:

HTTPSCookie
setSecure(true).

. 
[1] CWE-614 HTTPS - http://cwe.mitre.org/data/definitions/614.html
[2] OWASP Top 10 2010 - (OWASP 2010) A9 Insufficient Transport Layer Protection



24. (Password in Comment)


.
. SW 
, SW
. , 
.

. 

.

.
- JAVA
1:

2:

// Password for administrator is "tiger."<-.

3:

public boolean DBConnect() {

4:

String url = "DBServer";

5:

String password = "tiger";

6:

Connection con = null;

7:

try {

8:

con = DriverManager.getConnection(url, "scott", password);

9:

} catch (SQLException e) {

10:

11:
12:


.



- JAVA
1:

2:

// .

3:

public Connection DBConnect(String id, String

4:

String url = "DBServer";

5:

Connection conn = null;

password) {

6:

try {

7:
8:

String CONNECT_STRING = url + ":" + id + ":" + password;

9:

InitialContext ctx = new InitialContext();

10:

DataSource datasource = (DataSource) ctx.lookup(CONNECT_STRING);


conn = datasource.getConnection();

11:

} catch (SQLException e) {

12:

return conn;

13:
14:


.

. 
[1] CWE-615 - http://cwe.mitre.org/data/definitions/615.html
[2] OWASP Top 10 2010 - (OWASP 2010) A7 Insecure Cryptographic Storage
[3] Web Application Security Consortium 24 + 2 - (WASC 24 + 2) Information Leakage



25. 
(Incorrect Permission Assignment for Critical Resource)
. 
SW
, .

. 
, , SW 
.
, 
.

.
- JAVA
1:

// : rw-rw-rw-, : rwxrwxrwx

2:

String cmd = "umask 0";

3:

File file = new File("/home/report/report.txt");

4:

...

5:

Runtime.getRuntime().exec(cmd);

JAVA  API         
umask, /.
- JAVA
1:

// : rw-------, : rwx------

2:

String cmd = "umask 77";

3:

File file = new File("/home/report/report.txt");

4:

...

5:

Runtime.getRuntime().exec(cmd);

, /
umask.

. 
[1] CWE-732 - http://cwe.mitre.org/data/definitions/732.html
CWE-276 - http://cwe.mitre.org/data/definitions/276.html
CWE-277 - http://cwe.mitre.org/data/definitions/277.html
CWE-278 - http://cwe.mitre.org/data/definitions/278.html
CWE-279 -- http://cwe.mitre.org/data/definitions/279.html
CWE-281 - http://cwe.mitre.org/data/definitions/281.html
CWE-285 - http://cwe.mitre.org/data/definitions/281.html
[2] CWE/SANS Top 25 Most Dangerous Software Errors, http://cwe.mitre.org/top25/



4 
          
()()
 .     (dead lock),  
, .

1. : 
(Race Condition: Static Database Connection(dbconn))
.
DB , 
.

. 
DB (race condition)
DB .

.
- JAVA
1:

2:

// DB .

3:

private static Connection conn;

4:

private static final String CONNECT_STRING =

"jdbc:ocl:orcl";

5:
6:

public Connection dbConnection(String url, String

7:

InitialContext ctx;

8:

try {

user, String pw) {

9:

ctx = new InitialContext();

10:

DataSource datasource = (DataSource) ctx.lookup(CONNECT_STRING);

11:

conn = datasource.getConnection();

12:

} catch (NamingException e) {

13:

return conn;

14:

15:

DB (race condition)


.



- JAVA
1:

2:

// DB .

3:

private Connection conn;

4:

private static final String CONNECT_STRING = "jdbc:ocl:orcl";

5:
6:

public Connection dbConnection() {

7:

InitialContext ctx;

8:

try {

9:

ctx = new InitialContext();

10:

DataSource datasource = (DataSource) ctx.lookup(CONNECT_STRING);


conn = datasource.getConnection();

11:

} catch (NamingException e) {

12:

return conn;

13:
14:

15:

(Race condition)DB .

. 
[1] CWE-362 - http://cwe.mitre.org/data/definitions/362.html
[2] SANS Top 25 2010 - (SANS 2010) Insecure Interaction - CWE ID 362 Concurrent Execution
using Shared Resource with Improper Synchronization ('Race Condition')
[3] Java 2 Platform Enterprise Edition Specification, v1.4, Sun Microsystems



2. : (Race Condition: Singleton Member Field)


.
(Servlet), 
.

. 
(race condition)
, . , 
.

.
- JAVA
1:

public class U9404 extends javax.servlet.http.HttpServlet {

2:

// .

3:

private String name;

4:
5:

protected void doPost(HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException {

6:

name = req.getParameter("name");

7:
8:

       ,   . 
, 2
.

- JAVA
1:

public class S9404 extends javax.servlet.http.HttpServlet {

2:

// private String name; <- .

3:

protected void doPost(HttpServletRequest req,

HttpServletResponse res)
throws ServletException, IOException {

9:
4:

// .

5:

String name = req.getParameter("name");


if (name == null ||

6:
7:

"".equals(name)) return; //name = "user";

.

. 
[1] CWE-362 - http://cwe.mitre.org/data/definitions/362.html
[2] SANS Top 25 2010 - (SANS 2010) Insecure Interaction - CWE ID 362 Concurrent Execution
using Shared Resource with Improper Synchronization ('Race Condition')
[3] The Java Servlet Specification, Sun Microsystems



3. : 
(Time-of-check Time-of-use (TOCTOU) Race Condition)
.
.
. 
, , .

. 
(: ), (synchronized)
.
.
thread safe .

.
- JAVA
1:

class FileMgmtThread extends Thread {

2:
3:

private String manageType = "";

4:
5:

public FileMgmtThread (String type) {


manageType = type;

6:
7:

8:
9:
10:

public void run() {


try {
if ( manageType.equals("READ") ) {

11:
12:

File f = new File("Test_367.txt");

13:

if (f.exists()) { // 

14:

BufferedReader br = new BufferedReader(new FileReader(f));

15:

br.close();
}

16:

} else if ( manageType.equals("DELETE") ) {

17:
18:

File f = new File("Test_367.txt");

19:

if (f.exists()) { // 
f.delete();

20:

} else {

21:

22:

23:

24:



25:

} catch (IOException e) {

26:

27:
28:

29:
30:

public class CWE367 {

31:

public static void main(String[] args) {

32:

// .

33:

FileMgmtThread fileAccessThread = new FileMgmtThread("READ");

34:

FileMgmtThread fileDeleteThread = new FileMgmtThread("DELETE");

35:

fileAccessThread.start();

36:

fileDeleteThread.start();
}

37:
38:


, 

. 

.

- JAVA
1:

class FileMgmtThread extends Thread {

2:
3:

private static final String SYNC = "SYNC";

4:
5:

private String manageType = "";

6:
7:

public FileMgmtThread (String type) {


manageType = type;

8:
9:

10:
11:
12:
13:
14:
15:

public void run() {


// synchronized lock
// Thread.
synchronized(SYNC) {
try {

16:

if ( manageType.equals("READ") ) {

17:

File f = new File("Test_367.txt");

18:

if (f.exists()) { // 

19:

BufferedReader br = new BufferedReader(new FileReader(f));

20:

br.close();

21:
22:

}
} else if ( manageType.equals("DELETE") ) {

23:

File f = new File("Test_367.txt");

24:

if (f.exists()) { // 

25:

f.delete();



} else {

26:

27:

28:

29:

} catch (IOException e) {

30:

31:

32:

33:

34:
35:

public class CWE367 {

36:
37:

public static void main(String[] args) {

38:

// .

39:

FileMgmtThread fileAccessThread = new FileMgmtThread("READ");

40:

FileMgmtThread fileDeleteThread = new FileMgmtThread("DELETE");

41:

fileAccessThread.start();

42:

fileDeleteThread.start();

43:

}
}

44:

(, ), 
.

- JAVA
1:

public class MyServlet extends HttpServlet {

2:

String name;

3:

public void doPost ( HttpRequestRequest hreq, HttpResponceServlet hres ) {


name = hreq.getParameter("name");

4:

5:
6:

HttpServet  MyServlet  name  .

name

MyServlet.

1 - JAVA
1:

public class MyServlet extends HttpServlet {


public void doPost ( HttpRequestRequest hreq, HttpResponceServlet hres ) {

2:

// .

3:

String name = hreq.getParameter("name");

4:

...

5:
6:

namedoPost .



2 - JAVA
public class MyClass {

1:
2:

String name;

3:

public void doProcess (HttpRequestRequest hreq ) {

4:

// .
synchronized {

5:

name = hreq.getParameter("name");

6:

...

7:

8:

...

9:
10:

 name     , synchronized  ,
.

. 
[1] CWE-367 : - http://cwe.mitre.org/data/definitions/367.html
[2] SANS Top 25 Most Dangerous Software Errors
[3] Michael Howard, David LeBlanc and John Viega. "24 Deadly Sins of Software

Security".

"Sin 13: Race Conditions." Page 205. McGraw-Hill. 2010


[4] Andrei Alexandrescu. "volatile - Multithreaded Programmer's Best Friend". Dr. Dobb's. 2008-02-01
[5] Steven Devijver. "Thread-safe webapps using Spring"
David Wheeler. "Prevent race conditions". 2007-10-04
[6] Matt Bishop. "Race Conditions, Files, and Security Flaws; or the Tortoise and the Hare Redux". September 1995
[7] Johannes Ullrich. "Top 25 Series - Rank 25 - Race Conditions". SANS Software Security Institute. 2010-03-26



4. J2EE : 
(J2EE Bad Practices Direct Use of Threads)
.
J2EE . 

. , , , .

. 
J2EE.

.
- JAVA
1:

public class U383 extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response)

2:

throws ServletException, IOException {


3:

// Threadbackground.

4:

Runnable r = new Runnable() {

5:

public void run() {


System.err.println("do

6:

};

8:

new Thread(r).start();

9:

10:
11:

something");

7:

J2EE , , , 
.



- JAVA
1:

public class S383 extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response)

2:

throws ServletException, IOException {


3:

// Thread.

4:

// New MyClass().main();

5:
6:

// asyncJAVA Runtime

7:

// async.
Runtime.getRuntime().exec("java AsyncClass");

8:

9:
10:

11:
12:

class AsyncClass {
public static void main(String args[]) {

13:
14:

// Process and store request statistics.

15:

//
System.err.println("do something");

16:

17:
18:


.

. 
[1] CWE-383 J2EE : - http://cwe.mitre.org/data/definitions/383.html
[2] Java 2 Platform Enterprise Edition Specification, v1.4, Sun Microsystems



5. 
(Symbolic Name not Mapping to Correct Object)
.
         
.

. 
.

.
- JAVA
1:

public void f() throws ClassNotFoundException, InstantiationException,

2:

IllegalAccessException {
3:

// Class.forName.

4:

Class c = Class.forName("testbed.unsafe.U386.Add");

5:

Object obj = (Add)c.newInstance();

6:

Add add = (Add) obj;

7:

System.out.println(add.add(3, 5)); // 34

8:
9:

Object obj2 = (Add)Class.forName("testbed.unsafe.Add").newInstance();

10:

Add add2 = (Add) obj2;


System.out.println(add2.add(3, 5)); // 8

11:

12:
13:

class Add {

14:

int add(int x, int y) {

15:

return x + y;

16:

17:

18:
19:

20:
21:

class Add {
int add(int x, int y) {

22:
23:

return (x*x + y*y);

java.lang.Class.forName()(return),
""
.



- JAVA
1:

public void f() throws ClassNotFoundException,

2:

InstantiationException,

3:

IllegalAccessException {

4:

// .

5:

testbed.safe.S386.Add add = new testbed.safe.S386.Add();

6:

System.out.println(add.add(3, 5));

7:

testbed.safe.Add add2 = new testbed.safe.Add();

8:

System.out.println(add2.add(3, 5));
}

9:
10:

class Add {

11:

private int add(int x, int y) {

12:

return x + y;

13:

14:

15:
16:

17:
18:

class Add {
int add(int x, int y) {

19:
20:

return (x*x + y*y);

java.lang.Class.forName , .

. 
[1] CWE-386 - http://cwe.mitre.org/data/definitions/386.html



6. (Double-Checked Locking)
.
(double-checked locking)
, .
, 
, 
.

. 
()
().
.

.
- JAVA
1:

2:

Helper helper;

3:

public Helper MakeHelper() {

4:
5:

// helper null .

6:

if (helper == null) {
synchronized (this) {

7:

if (helper == null) {

8:

helper = new Helper();

9:

10:

11:

12:

return helper;

13:

14:
15:

class Helper {

16:

17:

18:
19:

helper . 
. 
, helper 
.



- JAVA
1:

2:

Helper helper;

3:
4:

// .

5:

public synchronized Helper MakeHelper() {


if (helper == null) {

6:

helper = new Helper();

7:

8:

return helper;

9:

10:
11:

12:
13:

class Helper {

14:
15:

, 
.

. 
[1] CWE-609 - http://cwe.mitre.org/data/definitions/609.html
[2] David Bacon et al.. "The "Double-Checked Locking is Broken" Declaration".
http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html



7. (Uncontrolled Recursion)
.

.  ,  (base case)   
.

. 

.

.
- JAVA
1:

2:

public int factorial(int n) {


// /.

3:

return n * factorial(n - 1);

4:
5:

   ,   /   
.

- JAVA
1:

2:

public int factorial(int n) {

3:

int i;

4:

// .

5:

if (n == 1) {
i = 1;

6:

} else {

7:

i = n * factorial(n - 1);

8:

9:

return i;

10:
11:

.

. 
[1] CWE-674 - http://cwe.mitre.org/data/definitions/674.html



5 
, 
      .    
         
. 
 (  )         
.

1. (Weak Password Requirements)


.
.

. 
.

.
- JAVA
1:

2:

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws IOException, ServletException {

3:

try {

4:
5:

String id = request.getParameter("id");

6:

String passwd = request.getParameter("passwd");

7:

// 
....

8:

} catch (SQLException e) {

9:
10:

         
.



- JAVA
1:

2:

private static final String CONNECT_STRING = "jdbc:ocl:orcl";

3:
4:

public void doPost(HttpServletRequest request, HttpServletResponse

response)

throws IOException, ServletException {

5:

try {

6:
7:

String id = request.getParameter("id");

8:

String passwd = request.getParameter("passwd");

9:
10:

// passwd

11:

if (passwd == null || "".equals(passwd)) return;

12:

if (!passwd.matches("") && passwd.indexOf("@!#")


// passwd , 

13:

14:

} catch (SQLException e) {

15:

catch (NamingException e) {

16:
17:

> 4 && passwd.length() > 8) {

}
}

.

. 
[1] CWE-521 - http://cwe.mitre.org/data/definitions/521.html
[2] OWASP Top Ten 2004 Category A3 - Broken Authentication and Session Management



2. (Information exposure through an error message)


.
SW, , 
. 
.

. 
SW
.

.
- JAVA
1:

2:

public static void main(String[] args) {

3:

String urlString = args[0];

4:

try{

5:

URL url = new URL(urlString);

6:

URLConnection cmx = url.openConnection();


cmx.connect();

7:

8:

catch (Exception e) {

9:
10:

e.printStackTrace();

.

- JAVA
1:

2:

public static void main(String[] args) {

3:

String urlString = args[0];

4:

try{

5:

URL url = new URL(urlString);

6:

URLConnection cmx = url.openConnection();


cmx.connect();

7:

8:

catch (Exception e) {

9:
10:

System.out.println("");

.

. 
[1] CWE-209 - http://cwe.mitre.org/data/definitions/209.html



3. (Detection of Error Condition Without Action)


.
, 
.

. 
(catch).

.
- JAVA
1:

2:

private Connection conn;

3:
4:

public Connection DBConnect(String url, String id, String password) {


try {

5:
6:

String CONNECT_STRING = url

7:

InitialContext ctx = new InitialContext();

8:

DataSource datasource = (DataSource) ctx.lookup(CONNECT_STRING);


conn = datasource.getConnection();

9:

} catch (SQLException e) {

10:
11:

// catch 

12:

} catch (NamingException e) {
// catch 

13:

14:

return conn;

15:
16:

+ ":" + id + ":" + password;

try (catch)
. 
.



- JAVA
1:

2:

private Connection conn;

3:
4:

public Connection DBConnect(String url, String id,

String password) {

try {

5:
6:

String CONNECT_STRING = url + ":" + id + ":" + password;

7:

InitialContext ctx = new InitialContext();

8:

DataSource datasource = (DataSource) ctx.lookup(CONNECT_STRING);


conn = datasource.getConnection();

9:

} catch (SQLException e) {

10:
11:

// Exception catchException.

12:

if ( conn != null ) {
try {

13:

conn.close();

14:

} catch (SQLException e1) {

15:

conn = null;

16:

17:

18:

} catch (NamingException e) {

19:
20:

// Exception catchException.

21:

if ( conn != null ) {
try {

22:

conn.close();

23:

} catch (SQLException e1) {

24:

conn = null;

25:

26:

27:

28:

return conn;

29:
30:

(catch), (Exception).

. 
[1] CWE-390  - http://cwe.mitre.org/data/definitions/390.html
[2] OWASP Top Ten 2004 Category A7 - Improper Error Handling



4. 
(Improper Check for Unusual or Exceptional Conditions)
. 

, .

. 
, , 
.

. 
- JAVA
1:

public void readFromFile(String fileName) {


try {

2:

...

3:
4:

File myFile = new File(fileName);

5:

FileReader fr = new FileReader(myFile);


...

6:

} catch (Exception ex) {...}

7:
8:

fileNameNull File , 
Exception.

- JAVA
1:

public void readFromFile(String fileName) throws FileNotFoundException,


IOException,MyException {

2:

try {

3:

...

4:
5:

// filename
if ( fileName == NULL ) throw new MyException(");

6:
7:

File myFile = new File(fileName);

8:

FileReader fr = new FileReader(myFile);


...

9:
10:

// .
} catch (FileNotFoundException fe) {...}

11:

} catch (IOException ie) {...}

12:
13:

fileName Null   Null     .


.



. 
[1] CWE-754 - http://cwe.mitre.org/data/definitions/754.html
CWE-252 - http://cwe.mitre.org/data/definitions/252.html
CWE-253 - http://cwe.mitre.org/data/definitions/253.html
CWE-273 - http://cwe.mitre.org/data/definitions/273.html
CWE-296 - http://cwe.mitre.org/data/definitions/296.html
CWE-297 -- http://cwe.mitre.org/data/definitions/297.html
CWE-298 - http://cwe.mitre.org/data/definitions/298.html
CWE-299 - http://cwe.mitre.org/data/definitions/299.html
[2] SANS Top 25 Most Dangerous Software Errors, http://www.sans.org/top25-software-errors/
[3] M. Howard, D. LeBlanc, Writing Secure Code, Second Edition, Microsoft Press



6 
, , , , , 
     .    ,
,        , 
.

1. : notify() (Code Correctness: Call to notify())


.
notify()
. .

. 
notify().

.
- JAVA
1:

2:

public synchronized void notifyJob() {

3:

boolean flag = true;

4:

notify();

5:

notify().

- JAVA
1:

2:

public synchronized void notifyJob() {

3:

boolean flag = true;

4:

// notify() .

5:

notify() .

. 
[1] CWE-362 - http://cwe.mitre.org/data/definitions/362.html
CWE-662 - http://cwe.mitre.org/data/definitions/662.html
[2] Sun Microsystems, Inc. Java Sun Tutorial - Concurrency



2. (Improper Resource Shutdown or Release)


.
, (open file descriptor), (heap memory), (socket) . , 
.

. 
finally .

.
- JAVA
1:

2:

public void processFile() throws SQLException {

3:

Connection conn = null;

4:

final String url = "jdbc:mysql://127.0.0.1/example?user=root&password=1234";

5:

try {

6:

Class.forName("com.mysql.jdbc.Driver");

7:

conn = DriverManager.getConnection(url);

8:

9:

// .
conn.close();

10:
11:

} catch (ClassNotFoundException e)

13:

} catch (SQLException e) {
System.err.println("SQLException occured");

14:
15:

System.err.println("ClassNotFoundException occured");

12:

} finally {

16:
17:


JDBC . 
.



- JAVA
1:

2:

public void processFile() throws SQLException {

3:

Connection conn = null;

4:

String url = "jdbc:mysql://127.0.0.1/example?user=root&password=1234";

5:

try {

6:

Class.forName("com.mysql.jdbc.Driver");

7:

conn = DriverManager.getConnection(url);

8:

9:

} catch (ClassNotFoundException e) {
System.err.print("error");

10:
11:

} catch (SQLException e) {
System.err.print("error");

12:
13:

} finally {

14:

15:

// close().

16:

conn.close();

17:

         finally
.

. 
[1] CWE-404 - http://cwe.mitre.org/data/definitions/404.html
[2] SANS Top 25 2009 - (SANS 2009) Risky Resource Management - CWE ID 404 Improper
Resource Shutdown or Release



3. (NULL Pointer Dereference)


.
'NULL'
. NULL , 
.

. 
(reference)
.

.
- JAVA
1:

2:

public void f() {

3:

String cmd = System.getProperty("cmd");

4:

// cmdnull.

5:

cmd = cmd.trim();

6:

System.out.println(cmd);

7:

"cmd" , 
"cmd" , cmdtrim()
.

- JAVA
1:

2:

public void f() {

3:

String cmd = System.getProperty("cmd");

4:

// cmdnull.

5:

if (cmd != null) {

6:

cmd = cmd.trim();

7:

System.out.println(cmd);

8:
9:

} else System.out.println("null command");

cmd.

. 
[1] CWE-476 - http://cwe.mitre.org/data/definitions/476.html



4. : serialPersistentFields
(Code Correctness: Incorrect serialPersistentFields Modifier)
.
serialPersistentFieldsprivate static final.
public.

. 
serialPersistentFieldsprivate, static, final.

.
- JAVA
1:

class List implements Serializable {

2:

public ObjectStreamField[] serialPersistentFields =

3:

{ new ObjectStreamField("myField", List.class) };


4:

serialPersistentFieldsprivate, static, final.

- JAVA
1:

class List implements

Serializable {

private static final ObjectStreamField[] serialPersistentFields =

2:

{ new ObjectStreamField("myField", List.class) };

3:
4:

serialPersistentFieldsprivate, static, final.

. 
[1] CWE-485 - http://cwe.mitre.org/data/definitions/485.html
[2] Sun Microsystems, Inc. Java Sun Tutorial



5. : Thread.run() (Code Correctness: Call to Thread.run())


.
  start()  run()    , 
run() run()  . , 
, start() run()
run() .

. 
run() start().

.
- JAVA
1:

protected void cwe_572() {

2:
3:

Thread thr = new PrintThread();

4:

// run() .
thr.run();

5:

6:
7:

}
class PrintThread extends Thread {

8:

public void run() {

9:

System.out.println("CWE 572 TEST");

10:

start() run() .

- JAVA
1:

protected void cwe_572() {

2:
3:

Thread thr = new PrintThread();

4:

// .
thr.start();

5:

6:

7:

8:

class PrintThread extends Thread {


public void run() {

9:
10:

System.out.println("CWE 572

TEST");

start() .

. 
[1] CWE-572 : Thread.run() - http://cwe.mitre.org/data/definitions/572.html



6. : 
(Code Correctness: Non-Synchronized Method Overrides Synchronized Method)
.
, (synchronized) 
(override), 
(synchronized) .

. 
(synchronized) , 
synchronized .

.
- JAVA
1:

public class U9627 {


public synchronized void synchronizedMethod() {

2:

for (int i=0; i<10; i++)

3:
4:

5:

6:

System.out.print(i);

7:
8:

public class Foo extends U9627 {

9:

// .

10:

public void synchronizedMethod() {


for (int i=0; i<20; i++)

11:
13:

System.out.print(i);

12:

(synchronized) 
(override)



- JAVA
1:

public class S9627 {


public synchronized void synchronizedMethod() {

2:

for (int i=0; i<10; i++)

3:
4:

5:

6:

System.out.print(i);

7:
8:

public class Foo extends S9627 {


public synchronized void

9:

System.out.print(i);

11:
12:

synchronizedMethod() {

for (int i=0; i<20; i++)

10:

(synchronized)     (synchronized)


. 
[1] CWE-665 - http://cwe.mitre.org/data/definitions/665.html
[2] Sun Microsystems, Inc. Bug ID: 4294756 Javac should warn if synchronized method is
overridden with a non synchronized



7. (Allocation of Resources Without Limits or Throttling)


. 
, 
, .

. 
, .
.
. 
Pool(Thread Pool, Connection Pool ).

.
- JAVA
1:

Connection conn = null;

2:

PreparedStatement pstmt = null;

3:

try {

4:

conn=getConnection();

5:

...

6:

pstmt = conn.prepareStatement("SELECT * FROM employees


where name=?");

7:
8:

...

9:

conn.close();

10:
11:

pstmt.close();
}catch (SQLException ex) {...}

close()   , open  dangling resource 


. .



- JAVA
1:

Connection conn = null;

2:

PreparedStatement pstmt = null;

3:

try {
conn=getConnection();

4:
5:

...

6:

pstmt = conn.prepareStatement("SELECT * FROM employees


where name=?");

7:

...

8:

}catch (SQLException ex) {...}

9:
10:

// finally.

11:

finally {
if ( conn!= null ) try { conn.close(); } catch (SQLException e){...}

12:

if ( pstmt!= null ) try { pstmt.close(); } catch (SQLException e){...}

13:
14:

finally,
finally.

. 
[1] CWE-400 - http://cwe.mitre.org/data/definitions/400.html
CWE-774 - http://cwe.mitre.org/data/definitions/774.html
CWE-789 - http://cwe.mitre.org/data/definitions/789.html
CWE-770 - http://cwe.mitre.org/data/definitions/770.html
[2] M. Howard and D. LeBlanc. "Writing Secure Code". Chapter 17, "Protecting Against Denial
of Service Attacks" Page 517. 2nd Edition. Microsoft. 2002
[3] J. Antunes, N. Ferreira Neves and P. Verissimo. "Detection and Prediction of
Resource-Exhaustion Vulnerabilities". Proceedings of the IEEE International



7
       ,  

. 
.

1. (Data Leak Between Sessions)


.
(singleton) (race condition)
. (servlet)
.

. 
HttpServlet . 
.

.
- JAVA
1:

public class U488 extends HttpServlet {

2:

private String name;

3:

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

4:
5:

name = request.getParameter("name");

6:

out.println(name + ", thanks for visiting!");

7:

8:
9:

, out.println(...)
name = ... 
(name).



- JAVA
1:

public class S488 extends HttpServlet {


protected void doPost(HttpServletRequest request, HttpServletResponse response)

2:

throws ServletException, IOException {

3:
4:

// .

5:

String name = request.getParameter("name");

6:

if (name == null || "".equals(name)) return;


out.println(name + ", thanks for visiting!");

7:

8:
9:

.

. 
[1] CWE-488 - http://cwe.mitre.org/data/definitions/488.html



2. (Leftover Debug Code)


.
. , 
.

. 
J2EEmain() . 
, main() .

.
- JAVA
1:

public class U489 extends HttpServlet {

2:

protected void doGet(HttpServletRequest request, ) throws { }

3:

protected void doPost(HttpServletRequest request, ) throws { }

4:

// main().

5:

public static void main(String args[]) {


System.err.printf("Print debug

6:
7:

8:

code");

J2EEmain() .

- JAVA
1:

public class S489 extends HttpServlet {

2:

protected void doGet(HttpServletRequest request, ) throws { }

3:

protected void doPost(HttpServletRequest request, ) throws { }

4:
5:

// .

J2EEmain() .

. 
[1] CWE-489 - http://cwe.mitre.org/data/definitions/489.html



3. 
(Use of Inner Class Containing Sensitive Data)
.

. (static) , (local)
(anonymous) .

. 
private . 
, , (static) 
(local) (anonymous) .

.
- JAVA
1:

public final class U492 extends Applet {

2:

// .

3:

public class urlHelper {

4:

String secret;

urlHelper helper = new urlHelper();

5:
6:

String openData = secret;

, 
, .

- JAVA
1:

public class S492 extends Applet {

2:

// (static) private .

3:

public static class urlHelper { ... }

4:

String secret;
urlHelper helper = new urlHelper(secret);

5:
6:

7:

private 
.

. 
[1] CWE-492    - http://cwe.mitre.org/data/definitions/492.html



4. Final 
(Critical Public Variable Without Final Modifier)
.
publicfinal, 
. .

. 
public final.

.
- JAVA
1:

public final class U493 extends Applet {

2:

// price final, price.

3:

public static float price = 500;

4:

public float getTotal(int count) {

5:

return price * count;

6:
7:

8:

price final, , getTotal()


.

- JAVA
1:

public final class S493

extends Applet {

2:

// final .

3:

public static final float price = 500;

4:

public float getTotal(int count) {

5:

return price * count; // price 

6:

7:
8:

public final .

. 
[1] CWE-493 Final - http://cwe.mitre.org/data/definitions/493.html



5. private -
(Private Array-Typed Field Returned From A Public Method)
.
privatepublic(return), 
.

. 
privatepublic.
, public 
.

.
- JAVA
1:

// private publicreturn

2:

private String[] colors;

3:

public String[] getColors() {

4:

return colors;

colorsprivatepublicgetColors() 
reference. .

- JAVA
1:

2:

private String[] colors;

3:

// private, , public 
.

4:

public String[] getColors() {

5:

String[] ret = null;

6:

if ( this.colors != null ) {

7:

ret = new String[colors.length];

8:

for (int i = 0; i < colors.length; i++) {

ret[i] = this.colors[i];

9:

return ret;

10:
11:

12:

private , private 


.

. 
[1] CWE-495 private -- http://cwe.mitre.org/data/definitions/495.html



6. private -
(Public Data Assigned to Private Array-Typed Field)
.
publicprivate , private
.

. 
publicprivate .

.
- JAVA
1:

2:

// userRoles private, publicsetUserRoles(),


public .

3:

private String[] userRoles;

4:
5:

public void setUserRoles(String[] userRoles) {


this.userRoles = userRoles;

6:
7:

8:

userRoles private, publicsetUserRoles(),


public .

- JAVA
1:

2:

// private member.

3:

private String[] userRoles;

4:
5:

public void setUserRoles(String[] userRoles) {

6:

this.userRoles = new String[userRoles.length];

7:

for (int i = 0; i < userRoles.length; ++i)


this.userRoles[i] = userRoles[i];

8:
9:
10:

reference, ""private private


.

. 
[1] CWE-496 private -- http://cwe.mitre.org/data/definitions/496.html



7. (Information Leak of System Data)


.
, 
.

. 
.

.
- JAVA
1:

2:

public void f() {

3:

try {

4:

catch (IOException e) {

5:

// printf(e.getMessage()).

g();

System.err.printf(e.getMessage());

6:

7:
8:

9:

private void g() throws IOException {

10:

getMessage()
.

- JAVA
1:

2:

public void f() {

3:

try {

4:

catch (IOException e) {

5:

// end user.
}

7:
9:
10:

System.err.println("IOException Occured");

6:
8:

g();

}
private void g() throws IOException {


.

. 
[1] CWE-497 - http://cwe.mitre.org/data/definitions/497.html



8. (Use of Dynamic Class Loading)


.
. 
.

. 
.

.
- JAVA
1:

2:

public void f() {

3:

// 

4:

String classname = System.getProperty("customClassName");

5:

try {

6:

Class clazz = Class.forName(classname);

7:

System.out.println(clazz);

8:
9:

} catch (ClassNotFoundException e) {

.

- JAVA
1:

2:

public void f() {

3:

// .

4:

TestClass tc = new TestClass();

5:
6:

System.out.println(tc);

. 
.

. 
[1] CWE-545 - http://cwe.mitre.org/data/definitions/545.html



2 
1
SQL(Dynamic SQL) : SQL, 
 DBSQL.
(Mutex) : 
, (critical section)
.
(Sandbox) : (Executable File)
.
(Servlet) : (Java Servlet)
.
(Struts) : 2 .
SQL(Static SQL) : SQL
.
 : , 
.
(Whitelist) : (Black List), IP 


.
(Hash) : (),
(message digest function)()
()''.
Advanced Encryption Standard (AES) : 
DES, (NIST)52001
11(FIPS 197).
Big Endian : 
.
DES : DES(Data Encryption Standard)
64,
64, 64. (Brute Force)
.
LDAP(Lightweight Directory Access Protocol) : TCP/IP 



.
Little Endian : 
.
MultipartRequest : O'reilly
.
OAEP(Optimal Asymmetric Encryption Padding) : BellareRogaway
RSApadding scheme
Pool : , 
, 
 .
Private key : 

Public key : , 
, 
.
SHA(Secure Hash Algorithm) : .
RC5 : 1994RSA SecurityRonald Rivest.
Synchronized : JAVA
Umask : .
Wraparound : int longMSB(Most
Significant Bit), .



2
ACL : Access Control List
AES : Advanced Encryption Standard
CSRF : Cross-Site Request Forgery
CWE : Common Weakness Enumeration
DES : Data Encryption Standard
ESAPI : Enterprise Security API
HTML : Hyper Text Markup Language
HTTPS : Hypertext Transfer Protocol over Secure Socket Layer
JAAS : Java Authentication and Authorization Service
JDBC : Java Database Connectivity
LDAP : Lightweight Directory Access Protocol
MSB : Most Significant Bit
OAEP : Optimal Asymmetric Encryption Padding
OWASP : Open Web Application Security Project
RSA : Ron Rivest, Adi Shamir, Leonard Adleman
SHA : Secure Hash Algorithm
SQL : Structured Query Language
OpenSSL : Open Secure Socket Layer
URL : Uniform Resource Locator
XSS : Cross-Site Scripting
WAS : Web Application Server



$





42-




















-%"1

-%"1







































"1*







DISPPU+BJM

%/4MPPLVQ





HFUMPHJO








































34"

































































































<1> C




CWE-ID

SQL

CWE-89



CWE-121



CWE-122



CWE-23



CWE-36



CWE-78

LDAP

CWE-90

LDAP

CWE-90

CWE-99



CWE-125



CWE-15

CWE-114



CWE-124



CWE-125



CWE-129



CWE-170

CWE-190



CWE-194



CWE-196



API

CWE-242

chroot Jail

CWE-243

DNS lookup

CWE-247

:

CWE-251

getlogin()

CWE-558

CWE-259

CWE-285



CWE-255



CWE-ID



CWE-256

CWE-260



CWE-261



CWE-266



CWE-272

: 

CWE-310



CWE-321

: RSA

CWE-325

: 

CWE-326



CWE-327



CWE-330



CWE-605



CWE-615



CWE-732

: 

CWE-367



CWE-386



CWE-674



CWE-209



CWE-754



CWE-195



CWE-398



CWE-404

CWE-476



CWE-562



CWE-730

CWE-ID

: 

CWE-730

: 

CWE-730



CWE-770



CWE-489

1 C 
1 
. 
        
,         
.

1. SQL (SQL Injection)


.
SQL . 
(Query) 
DB.

. 
SQL , 
. .

.
- C
1:

#include <stdlib.h>

2:

#include <sql.h>

3:

void U51000089_1(SQLHSTMT sqlh)

4:

{
char *query = getenv("query_string");

5:

SQLExecDirect(sqlh, query, SQL_NTS);

6:
7:

SQL . "name' OR 'a'='a"


WHERE .

- C
1:

#include <sql.h>

2:

void S51000089_1(SQLHSTMT sqlh)

3:

{
char *query_items = "SELECT * FROM items";

4:

SQLExecDirect(sqlh, query_items, SQL_NTS);

5:
6:

.

.
[1] CWE-89 SQL - http://cwe.mitre.org/data/definitions/89.html
[2] OWASP Top 10 2010 - (OWASP 2010) A1 Injection
[3] SANS Top 25 2010 - (SANS 2010) Insecure Interaction

2. (Stack-based Buffer Overflow)


.
(, )
.

. 
.
.
.
(bounds checking).
strcpy().

.
- C
1:

void manipulate_string(char* string) {

2:

char buf[24];

3:

ctrcpy(buf, string);

4:

5:

, strcpy() 
. 
.

- C
1:

void manipulate_string(char* string) {

2:

char buf[24];

3:

/* buf. */

4:

if (strlen(string < sizeof(buf))


strncpy(buf, string, sizeof(buf)-1);

5:

/* null*/

6:

buf[sizeof(buf)-1] = '\0';

7:
8:

9:

(string)buf. strncpy() 
buf, buf'\0'.

.
[1] CWE-121 - http://cwe.mitre.org/data/definitions/121.html

3. (Heap-based Buffer Overflow)


.
(, malloc() )
, 
.

. 
.
.
.
(bounds checking).
strlcpy().

.
- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <string.h>

4:

#define BUFSIZE 10

5:

int main(char **argv)

6:

{
char *dest = NULL;

7:
8:

dest = (char *)malloc(BUFSIZE);

9:

10:

strcpy(dest, argv[1]);

11:

12:

free(dest);

13:

return 0;

14:

, strcpy() 


.

- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <string.h>

4:

#define BUFSIZE 10

5:

int main(int argc, char **argv)

6:

7:

char *dest = NULL;

8:

dest = (char *)malloc(BUFSIZE);

9:
10:

strlcpy(dest, argv[1], BUFSIZE);

11:

12:

free(dest);
return 0;

13:
14:

     strlcpy()    .
(strlcpy() null.)

.
[1] CWE-122 - http://cwe.mitre.org/data/definitions/122.html

4. (Relative Path Traversal)


.
, 
, 
.
. 
"..". ".."

.

. 

.

.
- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <unistd.h>

4:

#include <string.h>

5:

void f()

6:

7:

/* */

8:

char* rName = getenv("reportName");

9:

char buf[30];

10:

strncpy(buf, "/home/www/tmp/", 30);

11:

strncat(buf, rName, 30);


unlink(buf);

12:
13:

reportName/home/www/tmp
, reportName../../../etc/passwd
.

- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <unistd.h>

4:

#include <string.h>

5:

void f()

6:

{
/* */

7:
8:

char buf[30];

9:

strncpy(buf, "/home/www/tmp/", 30);

10:

strncat(buf, "report", 30);


unlink(buf);

11:
12:


.

.
[1] CWE-23 -http://cwe.mitre.org/data/definitions/23.html
[2] CWE-22 - http://cwe.mitre.org/data/definitions/22.html
[3] OWASP Top 10 2010 - (OWASP 2010) A4 Insecure Direct Object Reference
[4] SANS Top 25 2010 - (SANS 2010) Risky Resource Management

5. (Absolute Path Traversal)


.

. 
. . (1) 
. (2) 
. , 
.

. 
.

.
- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <unistd.h>

4:

void f()

5:

6:

/* */

7:

char* rName = getenv("reportName");


unlink(rName);

8:
9:

reportName 
().

- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <unistd.h>

4:

void f()

5:

6:

/* */

7:

unlink("/home/www/tmp/report");

8:

.

.
[1] CWE-36 - http://cwe.mitre.org/data/definitions/36.html

[2] CWE-22 - http://cwe.mitre.org/data/definitions/22.html


[3] OWASP Top 10 2010 - (OWASP 2010) A4 Insecure Direct Object Reference
[4] SANS Top 25 2010 - (SANS 2010) Risky Resource Management

6. 
(Improper Neutralization of Special Elements Used in an OS
Command (OS Command Injection))
.
. 

. 
, .

. 
system() 
. , 
.

.
- C
1:

#include <stdio.h>

2:

#include <unistd.h>

3:

#include <limits.h>

4:

int main(int argc, char **argv)

5:

6:

char arg[80];

7:

char cat[] = "cat ";

8:

char *command;

9:

size_t commandLength;
/* */

10:
11:

fgets(arg,80,stdin);

12:

commandLength = strlen(cat) + strlen(arg) + 1;

13:

command = (char *) malloc(commandLength);

14:

strncpy(command, cat, commandLength);

15:

strncat(command, argv[1], (commandLength - strlen(cat))

16:

);

17:

system(command);
return 0;

18:
19:

. 
catWrapper"Story.txt; ls"Story.txt 
. 
, 
.



- C
1:

#include <stdio.h>

2:

#include <unistd.h>

3:

int main(int argc, char **argv)

4:

5:

char arg[80];

6:

char cat[] = "cat ";

7:

char *command;

8:

size_t commandLength;

9:

fgets(arg,80,stdin);
/* */

10:
1:

if (strpbrk(arg,";\"'."))

11:

{
exit(1);

12:
13:

14:

commandLength = strlen(cat) + strlen(arg) + 1;

15:

if(commandLength < 20) {


command = (char *) malloc(commandLength);

16:
17:

18:

strncpy(command, cat, commandLength);

19:

strncat(command, argv[1], (commandLength - strlen(cat)) );

20:

system(command);
return 0;

21:
22:

strpbrk() .

.
[1] CWE-78 - http://cwe.mitre.org/data/definitions/78.html
[2] OWASP Top 10 2010 - (OWASP 2010) A1 Injection
[3] SANS Top 25 2010 - (SANS 2010) Insecure Interaction



7. LDAP (LDAP Injection)


.
SW, LDAP

.

. 
LDAP .

.
- C
1:

#include <stdio.h>

2:

#include <ldap.h>

3:

#define FIND_DN ""

4:

int main()

5:

6:

char* filter = getenv("filter_string");

7:

int rc;

8:

LDAP *ld = NULL;

9:

LDAPMessage* result;
rc = ldap_search_ext_s(ld, FIND_DN, LDAP_SCOPE_BASE, filter, NULL, 0, NULL, NULL,

10:

LDAP_NO_LIMIT, LDAP_NO_LIMIT, &result);


return 0;

11:
12:

getenv() LDAP . 


'|'
.



- C
1:

#include <stdio.h>

2:

#include <ldap.h>

3:

#define FIND_DN ""

4:

int main()

5:

6:

char* filter = "(manager=admin)";

7:

int rc;

8:

LDAP *ld = NULL;

9:

LDAPMessage* result;
rc = ldap_search_ext_s( ld, FIND_DN, LDAP_SCOPE_BASE, filter, NULL, 0, NULL,

10:

NULL, LDAP_NO_LIMIT, LDAP_NO_LIMIT, &result);


return 0;

11:
12:

.

.
[1] CWE-90 LDAP - http://cwe.mitre.org/data/definitions/90.html
[2] OWASP Top 10 2010 - (OWASP 2010) A1 Injection
[3] SANS Top 25 2009 - (SANS 2009) Insecure Interaction - CWE ID 116 Improper
Encoding or Escaping of Output



8. LDAP (LDAP Manipulation)


.
LDAP LDAP 
LDAP . LDAP
.

. 
.
.

.
- C
1:

#include <stdio.h>

2:

#include <ldap.h>

3:

#define MAX 256

4:

int LDAPbind(LDAP *ld, FILE *file, char *password, char *dn)

5:

6:

char base[MAX];

7:

char manager[MAX-10];

8:

int rc;

9:

LDAPMessage* result;

10:

fgets(manager,sizeof(manager),file);

11:

snprintf(base, sizeof(base), "(user=%s)", manager);

12:

ldap_simple_bind_s(ld, manager, password);

13:

rc = ldap_search_ext_s( ld, base, LDAP_SCOPE_BASE, "manager=m1", NULL, 0, NULL,

14:

return rc;

NULL, LDAP_NO_LIMIT, LDAP_NO_LIMIT, &result);


15:

managersnprintf() LDAP 
. .



- C
1:

#include <stdio.h>

2:

#include <ldap.h>

3:

#define MAX 256

4:

int LDAPbind(LDAP *ld, char *username, char *password, char *dn) {


int rc;

5:
6:

LDAPMessage* result;

7:

ldap_simple_bind_s(ld, username, password);

8:

rc = ldap_search_ext_s( ld, "ou=NewHires", LDAP_SCOPE_BASE, "manager=m1", NULL,

9:

return rc;

0, NULL, NULL, LDAP_NO_LIMIT, LDAP_NO_LIMIT, &result);


10:

.

.
[1] CWE-90 LDAP - http://cwe.mitre.org/data/definitions/90.html
[2] OWASP Top 10 2004 - (OWASP 2004) A1 Unvalidated Input



9. (Resource Injection)
.
SW
. 
.

. 
connect() .

.
- C
1:

#include <stdio.h>

2:

#include <netinet/in.h>

3:

#include <stdlib.h>

4:

#include <string.h>

5:

int main()

6:

{
char* rPort = getenv("rPort");

7:
8:

struct sockaddr_in serv_addr;

9:

int sockfd = 0;

10:

char buf[25]

11:

strcpy(buf, rPort, 25);

12:

if (connect(sockfd,(struct sockaddr *)&buf,sizeof(serv_addr)) < 0) {


exit(1);

13:

14:

return 0;

15:
16:

getenv("rPort").
.



- C
1:

#include <stdio.h>

2:

#include <netinet/in.h>

3:

#include <stdlib.h>

4:

#include <string.h>

5:

int main()

6:

7:

char* rPort = getenv("rPort");

8:

struct sockaddr_in serv_addr;

9:

int sockfd = 0;

10:

char buf[25];

11:

if(strcmp(rPort,"") < 0)

12:

{
printf("bad input");

13:

14:
15:

strncpy(buf, rPort, 25);

16:

if (connect(sockfd,(struct sockaddr *)&buf,sizeof(serv_addr)) < 0) {


exit(1);

17:
18:

19:

return 0;

20:


.

.
[1] CWE-99 - http://cwe.mitre.org/data/definitions/99.html
[2] OWASP Top 10 2010 - (OWASP 2010) A4 Insecure Direct Object Reference



10. (Out-of-Bounds Read:Off-by-One)


.
1. C 
1
.

. 
.

.
- C
1:

int u9119()

2:

3:

int i;

4:

int sum = 0;

5:

int buf[10];
for(i=0; i < 10; i++)

6:
7:

{
sum += i;

8:
9:

10:

sum = buf[i];

11:

/* 10*/

12:

return 0;
}

13:

10.

- C
1:

int main()

2:

3:

int i;

4:

int sum = 0;

5:

int buf[10];

6:

for(i = 0; i < 10; i++)

7:

{
sum += i;

8:
9:

10:

sum = buf[i-1];

11:

return 0;

12:

-1



.

.
[1] CWE-125 - http://cwe.mitre.org/data/definitions/125.html
[2] CWE-129 - http://cwe.mitre.org/data/definitions/129.html
[3] CWE-131 - http://cwe.mitre.org/data/definitions/131.html
[4] CWE-193 - http://cwe.mitre.org/data/definitions/193.html
[5] CWE-805 - http://cwe.mitre.org/data/definitions/805.html
[6] OWASP Top 10 2004 - (OWASP 2004) A5 Buffer Overflow
[7] SANS Top 25 2010 - (SANS 2010) Risky Resource Management



11. 
(External Control of System or Cofiguration Setting)
.
. 
, .

. 
sethostid() .

.
- C
1:

#include <stdlib.h>

2:

#include <unistd.h>

3:

main(int argc, char *argv[])

4:

{
sethostid(atol(argv[1]));

5:
6:

ID. 
sethostid() 
. ID

.

- C
1:

#include <stdlib.h>

2:

#include <unistd.h>

3:

main(int argc, char *argv[])

4:

{
sethostid(0xC0A80101);

5:
6:

ID.

.
[1] CWE-15 - http://cwe.mitre.org/data/definitions/15.html
[2] OWASP Top 10 2004 - (OWASP 2004) A1 Unvalidated Input



12. (Process Control)


.

, .

. 
.
.

.
- C
1:

#include <stdio.h>

2:

#include <dlfcn.h>

3:

int main()

4:

5:

char *filename;

6:

int *handle;

7:

filename = getenv("SHAREDFILE");

8:

/* RRLD_LAZY: */
if ((handle = dlopen(filename, RTLD_LAZY)) != NULL)

9:
10:

11:

exit(1);

12:

13:

...

14:

return 0;

15:

dlopen() filename.



- C
1. #include <stdio.h>
2. #include <dlfcn.h>
3. int main()
4. {
5.

char *filename;

6.

int *handle;

7.

/* */
filename = "/usr/lib/hello.so";

8.
9.

if ((handle = dlopen(filename, RTLD_LAZY)) != NULL);

10.

11.

exit(1);

12.

13.

...

14.

return 0;

15. }

.

.
[1] CWE-114 - http://cwe.mitre.org/data/definitions/114.html
[2] OWASP Top 10 2010 - (OWASP 2010) A4 Insecure Direct Object Reference



13. 
(Boundary Beginning Violation ('Buffer Underwrite'))
.
.

.

. 

.

.
- C
1:

int main()

2:

3:

int a[10];

4:

a[-1] = 0;

5:

return 0;

6:

.

- C
1:

int main()

2:

3:

int a[10];

4:

a[0] = 0;
return 0;

5:
6:

.

.
[1] CWE-124 - http://cwe.mitre.org/data/definitions/124.html



14. (Out-of-Bounds Read)


.
. 
. 
. 
.

. 
. 
.

.
- C
1:

int main()

2:

3:

int a[3] = {1,2,3};

4:

int b = a[3];
return 0;

5:
6:

.

- C
1:

int main() {

2:

int a[3] = {1,2,3};

3:

int b = a[2];
return 0;

4:
5:

.

.
[1] CWE-125 - http://cwe.mitre.org/data/definitions/125.html
[2] CWE-129 - http://cwe.mitre.org/data/definitions/129.html
[3] CWE-131 - http://cwe.mitre.org/data/definitions/131.html
[4] CWE-805 - http://cwe.mitre.org/data/definitions/805.html
[5] OWASP Top 10 2004 - (OWASP 2004) A5 Buffer Overflow
[6] SANS Top 25 2010 - (SANS 2010) Risky Resource Management



15. (Unchecked Array Indexing)


.
.
0 ,
. 
, 
, .

. 
, 
.
, '>' '>='.

.
- C
1:

int getsizes(int sock, int count, int *sizes) {

2:

char buf[BUFFER_SIZE];

3:

int ok;

4:

int num, size;

5:
6:

while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0){

7:

if (hasDotInBuffer(buf))
break;

8:

else if (sscanf(buf,"%d %d", &num, &size) == 2)

9:

sizes[num-1] = size;

10:

11:

...

12:
13:

numsizes size
. 
.



- C
int getsizes(int sock, unsigned int MAXCOUNT, int *sizes) {

1:
2:

char buf[BUFFER_SIZE];

3:

int ok;

4:

int num, size;

5:

while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0){

6:

if (hasDotInBuffer(buf)) break;

7:

// bufnum, size.

8:

if (sscanf(buf,"%d %d", &num, &size) == 2){

9:
10:

// num.
if (num > 0 && num <= MAXCOUNT)

11:

sizes[num-1] = size;

12:

else { printf("); return(FAIL); }

13:

14:

15:

...

16:
17:

buf num .

.
[1] CWE-129 - http://cwe.mitre.org/data/definitions/129.html
CWE-120 - http://cwe.mitre.org/data/definitions/120.html
[2] SANS Top 25 2010 - (SANS 2010) Risky Resource Management - CWE ID 805 Buffer
Access with Incorrect Length Value
[3] M. Howard and D. LeBlanc. "Writing Secure Code". Chapter 5, "Public Enemy #1: The
Buffer Overrun" Page 127. 2nd Edition. Microsoft. 2002
[4] M. Howard, D. LeBlanc and J. Viega. "24 Deadly Sins of Software Security".
"Sin 5: Buffer Overruns." Page 89. McGraw-Hill. 2010



16. (Improper Null Termination)


.
C, . 
. 
, (1) 
(2) strncpy() 
. 
, 
.

. 
read(), readlink()strcpy(), strcat(), strlen() .
strlcpy()strlcat() .

.
- C
1:

#include <stdio.h>

2:

#include <string.h>

3:

#include <unistd.h>

4:

#define MAXLEN 1024

5:

extern char *inputbuf;

6:

extern int cfgfile;

7:

void f() {

8:

char buf[MAXLEN];

9:

read(cfgfile, inputbuf, MAXLEN);


strcpy(buf, inputbuf);

10:
11:

read() inputbuf .


strcpy() 
.



- C
1:

#include <stdio.h>

2:

#include <string.h>

3:

#include <unistd.h>

4:

#include <string.h>

5:

#define MAXLEN 1024

6:

extern char *inputbuf;

7:

extern int cfgfile;

8:

void f() {
char buf[MAXLEN];

9:
10:

read(cfgfile, inputbuf, MAXLEN);

11:

strlcpy(buf, inputbuf, MAXLEN);

12:

read() MAXLENstrcpy()
.

.
[1] CWE-170 - http://cwe.mitre.org/data/definitions/170.html
[2] CWE-665 - http://cwe.mitre.org/data/definitions/665.html
[3] OWASP Top 10 2004 - (OWASP 2004) A5 Buffer Overflow
[4] SANS Top 25 2010 - (SANS 2010) Risky Resource Management - CWE ID 665
Improper Initialization



17. (Integer Overflow)


.
. 

. 
, 
.

. 
Signed , 
. , 
unsigned 
.

.
- C
1:

#include <stdlib.h>

2:

void* intAlloc(int size, int reserve)

3:

{
void *rptr;

4:
5:

size += reserve;

6:

rptr = malloc(size * sizeof(int));


if (rptr == NULL)

7:
8:

exit(1);

9:

return rptr;

10:

Signed intmalloc() , 


overflow.



- C
1:

#include <stdlib.h>

2:

void* intAlloc(int size, int reserve)

3:

4:

void *rptr;

5:

unsigned s;

6:

size += reserve;

7:

s=size* sizeof(int);

8:

if(s<0)

9:

return NULL;

10:

rptr = malloc(s);

11:

if (rptr == NULL)

12:

exit(1);
return rptr;

13:
14:

malloc() unsigned
integer overflow .

.
[1] CWE-190 - http://cwe.mitre.org/data/definitions/190.html
[2] OWASP Top 10 2004 - (OWASP 2004) A1 Unvalidated Input
[3] SANS Top 25 2010 - (SANS 2010) Risky Resource Management



18. (Unexpected Sign Extension)


.

. ,
. , unsigned
.

. 

.

.
- C
1:

extern int info[256];

2:

int f(int id)

3:

4:

short s;

5:

unsigned sz;

6:

/* intshort*/

7:

s = id;

8:

if (s > 256) return 0;

9:

/* unsigned*/
sz = s;

10:

return info[sz];

11:

12:

4int (id)2short (s)


4unsigned .

- C
1:

extern int info[256];

2:

int f(int id)

3:

4:

int s;

5:

unsigned sz;

6:

s = id;

7:

if (s > 256 || s < 0)

8:

return 0;

9:

sz = (unsigned) s;

10:

return info[sz];

11:




.

.
[1] CWE-194 - http://cwe.mitre.org/data/definitions/194.html



19. 
(Unsigned to Signed Conversion Error)
.
(unsigned integer)(signed integer)
. 
.

. 
signed intunsigned int.

.
- C
1:

#include <stdlib.h>

2:

#include <string.h>

3:

extern int initialized, chunkSize;

4:

int chunkSz()

5:

{
if (!initialized) return -1;

6:

return chunkSize;

7:
8:

9:

void* chunkCpy(void *dBuf, void *sBuf)

10:

11:

unsigned size;

12:

size = chunkSz();
return memcpy(dBuf, sBuf, size);

13:
13:

chunkSz() chunkSize-1
. chunkCpy memcpy
. sizeunsigned-1
.



- C
1:

#include <stdlib.h>

2:

#include <string.h>

3:

extern int initialized, chunkSize;

4:

int chunkSz()

5:

{
if (! initialized) return -1;

6:

return chunkSize;

7:
8:

9:

void* chunkCpy(void *dBuf, void *sBuf)

10:

11:

int size;

12:

size = chunkSz();

13:

f (size < 0) return NULL;


return memcpy(dBuf, sBuf, (unsigned)size);

14:
15:

chunkSz() signed int 


signed intunsigned int. 
signed int.

.
[1] CWE-196 - http://cwe.mitre.org/data/
definitions/196.html



2 API
API(Application Programming Interface)    
    ,      
. API API
.

1. (Use of Inherently Dangerous Function)


.
. 
, 
. , gets() , 
. , .

. 
         .
(: gets )

.
- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#define BUFSIZE 100

4:

void f() {

5:

char buf[BUFSIZE];

6:

gets(buf);

7:

buf BUFSIZE  gets()     buf 


.

- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#define BUFSIZE 100

4:

void f() {
char buf[BUFSIZE];

5:
8:

/* buf */

9:

fgets(buf, BUFSIZE, stdin);

6:



gets() fgets() .

.
[1] CWE-242 - http://cwe.mitre.org/data/definitions/242.html
[2] CWE-676 - http://cwe.mitre.org/data/definitions/676.html
[3] OWASP Top 10 2004 - (OWASP 2004) A5 Buffer Overflow



2. chroot Jail
(Creation of chroot Jail Without Change Working Directory)
.
chroot 
.
chroot         
. 
, 
.

. 
chroot() chdir("/")
.

.
- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <unistd.h>

4:

void f(FILE *network) {

5:

FILE *localfile;

6:

char filename[80], buf[80];

7:

int len;

8:
9:

chroot("/var/ftproot");

10:
11:

fgets(filename, sizeof(filename), network);

12:

localfile = fopen(filename, "r");

13:

while ((len = fread(buf, 1, sizeof(buf), localfile)) != EOF) {


fwrite(buf, 1, sizeof(buf), network);

14:
15:

16:

fclose(localfile);

17:

 ftp  , ftp     /var/ftproot 


. 
"../../etc/passwd" 
.



- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <unistd.h>

4:

void f(FILE *network) {

5:

FILE *localfile;

6:

char filename[80], buf[80];

7:

int len;

8:

chroot("/var/ftproot");

9:
10:
11:

/* */

12:

chdir("/");

13:

fgets(filename, sizeof(filename), network);

14:
15:

localfile = fopen(filename, "r");

16:

while ((len = fread(buf, 1, sizeof(buf), localfile)) != EOF) {


fwrite(buf, 1, sizeof(buf), network);

17:
18:

19:

fclose(localfile);

20:

chroot() chdir("/")
.

.
[1] CWE-243 chroot Jail - http://cwe.mitre.org/data/
definitions/243.html



3. DNS lookup
(Reliance on DNS Lookups in a Security Decision )
.
DNS DNS . DNS
, DNS SW
. DNS, IP 
.

. 
DNS IP 
DNS .

- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <string.h>

4:

#include <netdb.h>

5:

#include <sys/socket.h>

6:

#include <netinet/in.h>

7:

#include <arpa/inet.h>

8:

int decision(char *ip_addr_string) {

9:

struct hostent *hp;

10:

struct in_addr myaddr;

11:

char *tHost = "trustme.trusty.com";

12:

myaddr.s_addr = inet_addr(ip_addr_string);

13:
14:

/* IPDNS */

15:

hp = (struct hostent *)gethostbyaddr((char *) &myaddr, sizeof(struct in_addr), AF_INET);

16:

if (hp && !strncmp(hp->h_name, tHost, sizeof(tHost)))

17:

{
return 1; // true

18:
19:

20:

else {
return 0; // false

21:

22:
23:

gethostbyaddr IPDNS 


. DNS .



- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <string.h>

4:

#include <netdb.h>

5:

#include <sys/socket.h>

6:

#include <netinet/in.h>

7:

#include <arpa/inet.h>
int decision(char *ip_addr_string) {

8:
9:
10:

/* IP */

11:

char *tHost = "143.258.12.34";

12:

if (ip_addr_string &&; !strncmp(ip_addr_string, tHost, sizeof(tHost))) {


return 1; // true

13:
14:

15:

else {
return 0; // false

16:

17:
18:

IP DNS 
.

.
[1] CWE-247 DNS lookup- http://cwe.mitre.org/data/definitions/247.html
[2] SANS Top 25 2010 - (SANS 2010) Porus Defense - CWE ID 807 Reliance on
Untrusted Inputs in a Security Decision



4. :(Often Misused: String Management)


.
. 
.

. 
_mbsXXX()

.
- C
1:

#include <mbstring.h>

2:

void f(char *str1, char *str2) {


_mbscpy(str1, str2);

3:
4:

_mbsXXX()
. 
.

- C
1:

#include <mbstring.h>

2:

void f(char *str1, char *str2, unsigned size) {


_mbscpy_s(str1, size, str2);

3:
4:

        
_mbscpy_s().

.
[1] CWE-251 :- http://cwe.mitre.org/data/definitions/251.html
[2] CWE-176 Unicode - http://cwe.mitre.org/data/definitions/176.html
[3] OWASP Top 10 2004 - (OWASP 2004) A5 Buffer Overflow



5. getlogin()
(Use of getlogin() in Multithreaded Application)
.
. 
. getlogin() 
. 
.

. 
getlogin() getlogin_r() .

.
- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <unistd.h>

4:

#include <sys/types.h>

5:

#include <pwd.h>

6:

int isTrustedGroup(int);

7:

int f() {

8:

struct passwd *pwd = getpwnam(getlogin());

9:

if (isTrustedGroup(pwd->pw_gid))
return 1; // allow

10:

else

11:

return 0; // deny

12:
13:

getlogin(). getlogin()
. 
.



- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <unistd.h>

4:

#include <sys/types.h>

5:

#include <pwd.h>

6:

#define MAX 100

7:

int isTrustedGroup(int);

8:

int f() {

9:

char id[MAX];

10:

struct passwd *pwd;

11:

if (getlogin_r(id, MAX) != 0)
return 0;

12:
13:

pwd = getpwnam(id);

14:

if (isTrustedGroup(pwd->pw_gid))
return 1; // allow

15:
16:

else
return 0; // deny

17:
18:

getlogin_r() .

.
[1] CWE-558 getlogin() - http://cwe.mitre.org/data/definitions/558.html
[2] SANS Top 25 2010 - (SANS 2010) Porus Defense - CWE ID 807 Reliance on
Untrusted Inputs in a Security Decision



3
. 
. , , , ,
.

1. (Hard-coded Password)
.
SW, 
.

. 
, SW 
.

. 
.

.

.
- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <string.h>

4:

#include <sqlext.h>

5:

int dbaccess(char *server, char *user) {

6:

SQLHENV henv;

7:

SQLHDBC hdbc;

8:

SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);

9:

SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);

10:

/* asdf".*/

11:

SQLConnect(hdbc, (SQLCHAR*) server, strlen(server), user, strlen(user), "asdf", 4);

12:

return 0;

13:

.



- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <string.h>

4:

#include <sqlext.h>

5:

int dbaccess(char *server, char *user, char *passwd) {

6:

SQLHENV henv;

7:

SQLHDBC hdbc;

8:

SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);

9:

SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);

10:

SQLConnect(hdbc, (SQLCHAR*) server, strlen(server), user, strlen(user), passwd,

11:

strlen(passwd) );

12:

SQLFreeHandle(SQL_HANDLE_DBC, hdbc);

13:

SQLFreeHandle(SQL_HANDLE_ENV, henv);
return 0;

14:
15:

, 
.

.
[1] CWE-259 - http://cwe.mitre.org/data/definitions/259.html
[2] CWE-798 - http://cwe.mitre.org/data/definitions/798.html
[3] OWASP Top 10 2010 - (OWASP 2010) A7 Insecure Cryptographic Storage
[4] SANS Top 25 2010 - (SANS 2010) Porus Defense



2. (Improper Authorization)
.
SW
, .

. 

(attack surface).
ACL(Access Control List).

.
- C
1:

#define FIND_DN "uid=han,ou=staff,dc=example,dc=com"

2:
3:

int searchData2LDAP(LDAP *ld, char *username) {

4:

unsigned long rc;

5:

char filter[20];

6:

LDAPMessage *result;

7:

8:

snprintf(filter, sizeof(filter),"(name=%s)",username);

9:

/* LDAP */

10:

rc = ldap_search_ext_s(ld, FIND_DN, LDAP_SCOPE_BASE, filter, NULL, 0, NULL,

11:

NULL, LDAP_NO_LIMIT, LDAP_NO_LIMIT, &result);


return rc;

12:
13:

, LDAP . 


username.



- C
1:

#define FIND_DN "uid=han,ou=staff,dc=example,dc=com"

2:
3:

int searchData2LDAP(LDAP *ld, char *username, char *password) {

4:

unsigned long rc;

5:

char filter[20];

6:

LDAPMessage *result

7:

8:

/* username*/

9:

if ( ldap_simple_bind_s(ld, username, password) != LDAP_SUCCESS ) {


printf(");

10:

return(FAIL);

11:
12:

13:

/* username*/

14:

if ( strcmp(username,getLoginName()) != 0 ) {

15:

printf(");

16:

return(FAIL);

17:

18:

snprintf(filter, sizeof(filter), "(name=%s)", username);

19:

rc = ldap_search_ext_s(ld, FIND_DN, LDAP_SCOPE_BASE, filter, NULL, 0, NULL, NULL,


LDAP_NO_LIMIT, LDAP_NO_LIMIT, &result);

20:

21:

return rc;

22:

LDAP username, username.

.
[1] CWE-285 - http://cwe.mitre.org/data/definitions/285.html
CWE-219 - http://cwe.mitre.org/data/definitions/219.html
[2] OWASP Top 10 2010 - (OWASP 2010) A8 Failure to Restrict URL Access
[3] SANS Top 25 2010 - (SANS 2010) Porus Defense - CWE ID 285 Improper Authorization
[4] NIST. "Role Based Access Control and Role Based Security"
[5] M. Howard and D. LeBlanc. "Writing Secure Code". Chapter 4, "Authorization" Page
114; Chapter 6, "Determining Appropriate Access Control" Page 171. 2nd Edition.
Microsoft. 2002



3. (Hard-coded Username)
.
, 
.
, 
. 
, SW 
.

. 

.

.
- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <string.h>

4:

#include <sqlext.h>

5:

int dbaccess(char *server, char *passwd)

6:

{
SQLHENV henv;

7:
8:

SQLHDBC hdbc;

9:

SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);

10:

SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);

11:

SQLConnect(hdbc,

12:

(SQLCHAR*) server,

13:

(SQLSMALLINT) strlen(server),

14:

/**/

15:

"root",
4,

16:
17:

passwd,

18:

strlen(passwd));
return 0;

19:
20:

. 
.



- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <string.h>

4:

#include <sqlext.h>

5:

int dbaccess(char *server, char *user, char *passwd)

6:

7:

SQLHENV henv;

8:

SQLHDBC hdbc;

9:

SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);

10:

SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);

11:

SQLConnect(hdbc,

12:

(SQLCHAR*) server,

13:

strlen(server),

14:

user,

15:

strlen(user),

16:

passwd,
strlen(passwd));

17:

return 0;

18:
19:

.

.
[1] CWE-255 - http://cwe.mitre.org/data/definitions/255.html
[2] OWASP Top 10 2010 - (OWASP 2010) A7 Insecure Cryptographic Storage



4. (Plaintext Storage of Password)


.

. , 
. 
.

. 
.

.
- C
1:

int dbaccess()

2:

3:

FILE *fp; char *server = "DBserver";

4:

char passwd[20];

5:

char user[20];

6:

SQLHENV henv;

7:

SQLHDBC hdbc;

8:

fp = fopen("config", "r");

9:

fgets(user, sizeof(user), fp);

10:

fgets(passwd, sizeof(passwd), fp);

11:

fclose(fp);

12:

SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);

13:

SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);

14:

SQLConnect(hdbc,

15:

(SQLCHAR*) server,

16:

(SQLSMALLINT) strlen(server),

17:

(SQLCHAR*) user,

18:

(SQLSMALLINT) strlen(user),

19:

/* */

20:

(SQLCHAR*) passwd,

21:

(SQLSMALLINT) strlen(passwd)

22:

return 0;

23:

);

. 
.



- C
int dbaccess()

1:
2:

3:

FILE *fp;

4:

char *server = "DBserver";

5:

char passwd[20];

6:

char user[20];

7:

char *verifiedPwd;

8:

SQLHENV henv;

9:

SQLHDBC hdbc;

10:

fp = fopen("config", "r");

11:

fgets(user, sizeof(user), fp);

12:

fgets(passwd, sizeof(passwd), fp);

13:

fclose(fp);

14:

verifiedPwd = verify(passwd);

15:

SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);

16:

SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);

17:

SQLConnect(hdbc,

18:

(SQLCHAR*) server,

19:

(SQLSMALLINT) strlen(server),

20:

(SQLCHAR*) user,

21:

(SQLSMALLINT) strlen(user),

22:

/* */

23:

(SQLCHAR*) verifiedPwd,

24:

(SQLSMALLINT) strlen(verifiedPwd )
);

25:
26:

return 0;

27:

.

.
[1] CWE-256 - http://cwe.mitre.org/data/definitions/256.html
[2] J. Viega and G. McGraw. "Building Secure Software: How to Avoid Security
Problems the Right Way". 2002.



5. (Password in Configuration File)


.
. 
, 
. 
.

. 
, 
.

.
- C
1:

int dbaccess()

2:

3:

FILE *fp;

4:

char *server = "DBserver";

5:

char passwd[20];

6:

char user[20];

7:

SQLHENV henv;

8:

SQLHDBC hdbc;

9:

fp = fopen("config", "r");

10:

fgets(user, sizeof(user), fp);

11:

fgets(passwd, sizeof(passwd), fp);

12:

fclose(fp);

13:

SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);

14:

SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);

15:

SQLConnect(hdbc,

16:

(SQLCHAR*) server,

17:

(SQLSMALLINT) strlen(server),

18:

(SQLCHAR*) user,

19:

(SQLSMALLINT) strlen(user),

20:

(SQLCHAR*) passwd,

21:

(SQLSMALLINT) strlen(passwd)

22:

);

23:

return 0;

24:

config 
. 
.



- C
int dbaccess()

1:
2:

3:

FILE *fp;

4:

char *server = "DBserver";

5:

char passwd[20];

6:

char user[20];

7:

char *verifiedPwd;

8:

SQLHENV henv;

9:

SQLHDBC hdbc;

10:

fp = fopen("config", "r");

11:

fgets(user, sizeof(user), fp);

12:

fgets(passwd, sizeof(passwd), fp);

13:

fclose(fp);

14:

verifiedPwd = verify(passwd);

15:

SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);

16:

SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);

17:

SQLConnect(hdbc,

18:

(SQLCHAR*) server,

19:

(SQLSMALLINT) strlen(server),

20:

(SQLCHAR*) user,

21:

(SQLSMALLINT) strlen(user),

22:

(SQLCHAR*) passwd,

23:

(SQLSMALLINT) strlen(passwd)
);

24:
25:

return 0;

26:

(, ),
.

.
[1] CWE-260 - http://cwe.mitre.org/data/definitions/260.html
[2] J. Viega and G. McGraw. "Building Secure Software: How to Avoid Security
Problems the Right Way". 2002.



6. (Weak Cryptography for Passwords)


.
.
SW 
. base64
.

. 
.

.
- C
1:

char *base64_decode(char*);

2:

int dbaccess(char *user, char *cpasswd)

3:

4:

char *server = "DBserver";

5:

char *passwd;

6:

SQLHENV henv;

7:

SQLHDBC hdbc;

8:

SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);

9:

SQLAllocHandle(SQL_HANDLE_DBC, henv, &;hdbc);

10:

/* */

11:

passwd = base64_decode(cpasswd);

12:

SQLConnect(hdbc,

13:

(SQLCHAR*) server,

14:

(SQLSMALLINT) strlen(server),

15:

(SQLCHAR*) user,

16:

(SQLSMALLINT) strlen(user),

17:

(SQLCHAR*) passwd,
(SQLSMALLINT) strlen(passwd));

18:
19:

Base64.



- C
1:

int dbaccess(char *user, char *cpasswd, RSA *rsa)

2:

3:

char *server = "DBserver";

4:

unsigned char *passwd;

5:

SQLHENV henv;

6:

SQLHDBC hdbc;

7:

SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &;henv);

8:

SQLAllocHandle(SQL_HANDLE_DBC, henv, &;hdbc);

9:

/* */

10:

RSA_private_decrypt(strlen(cpasswd), cpasswd, passwd, rsa, RSA_PKCS1_PADDING );

11:

SQLConnect(hdbc,

12:

(SQLCHAR*) server,

13:

(SQLSMALLINT) strlen(server),

14:

(SQLCHAR*) user,

15:

(SQLSMALLINT) strlen(user),

16:

(SQLCHAR*) passwd,
(SQLSMALLINT) strlen(passwd));

17:
18:

.

.
[1] CWE-261 - http://cwe.mitre.org/data/definitions/261.html
[2] OWASP Top 10 2010 - (OWASP 2010) A7 Insecure Cryptographic Storage



7. (Incorrect Privilege Assignment)


.
SWSW
.

. 
.

.
- C
1:

#include <stdio.h>

2:

#include <sys/types.h>

3:

#include <unistd.h>

4:

char buf[100];

5:

char *privilegeUp()
{

6:

FILE *fp;

7:
8:

/* UID */

9:

seteuid(0);
fp = fopen("/etc/passwd", "r");

10:

fgets(buf, sizeof(buf), fp);

11:
12:

/* UID*/

13:

seteuid(getuid());
fclose(fp);

14:

return buf;

15:
16:

17:
18:

int main()

19:

20:

printf(".\n");

21:

char *buffer=privilegeUp();

22:

printf("%s.\n",buffer);
return 0;

23:
24:


.



- C
1:

#include <stdio.h>

2:

#include <sys/types.h>

3:

#include <unistd.h>
char buf[100];

4:
5:

char *privilegeUp()

6:

7:

FILE *fp;

8:

/* . */

9:

fp = fopen("/etc/passwd", "r");
fgets(buf, sizeof(buf), fp);

10:
11:

fclose(fp);

12:

return buf;
}

13:
14:

int main()

15:

16:

printf(".\n");

17:

char *buffer;

18:

buffer=privilegeUp();

19:

printf("%s.\n",buffer);

20:

return 0;

21:

.

.
[1] CWE-266 - http://cwe.mitre.org/data/definitions/266.html



8. (Least Privilege Violation)


.
SW
, . 
.

. 
.

.
- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <fcntl.h>

4:

#include <sys/types.h>

5:

#include <unistd.h>

6:

#define AAP_HOME "/var/tmp"


char buf[100];

7:

char *privilegeDown()

8:
9:

10:

FILE *fp;

11:

/* root */
cchroot(APP_HOME);

12:
13:

chdir("/");

14:

fopen("important_file", "r");

15:

fgets(buf, sizeof(buf), fp);

16:

fclose(fp);
return buf;

17:
18:

chroot()root setuid()
.



- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <fcntl.h>

4:

#include <sys/types.h>

5:

#include <unistd.h>

6:

#define AAP_HOME "/var/tmp"

7:

char buf[100];

8:

char *privilegeDown()

9:

10:

FILE *fp;

11:

chroot(APP_HOME);

12:

chdir("/");

13:

fp=fopen("important_file", "r");

14:

fgets(buf, sizeof(buf), fp);

15:

/* */

16:

seteuid(1);
fclose(fp);

17:
18:

return buf;

19:

chroot() seteuid()
.

.
[1] CWE-272 - http://cwe.mitre.org/data/definitions/272.html



9. : 
(Weak Encryption: Insufficient Key Size)
.
. 
RSA 1024 bit 
.

. 
1024 bit .

.
- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <openssl/rsa.h>

4:

#include <openssl/evp.h>

5:

EVP_PKEY *RSAKey()

6:

7:

EVP_PKEY *pkey;

8:

RSA *rsa;

9:

/* 512bit*/

10:

rsa = RSA_generate_key(512, 35, NULL, NULL);

11:

if (rsa == NULL)
{

12:
13:

printf("Error\n");

14:

return NULL;

15:

}
pkey = EVP_PKEY_new();

16:
17:

EVP_PKEY_assign_RSA(pkey, rsa);

18:

return pkey;

19:

RSA_generate_key()     512 bit .  


1024 bit .



- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <openssl/rsa.h>

4:

#include <openssl/evp.h

5:

EVP_PKEY *RSAKey()

6:

7:

EVP_PKEY *pkey;

8:

RSA *rsa;
/* 1024Bit .*/

9:
10:

rsa = RSA_generate_key(1024, 35, NULL, NULL);

11:

if (rsa == NULL)
{

12:
13:

printf("Error\n");

14:

return NULL;
}

15:
16:

EVP_PKEY *pkey = EVP_PKEY_new();

17:

EVP_PKEY_assign_RSA(pkey, rsa);
return pkey;

18:
19:

RSA_generate_key()     1024 bit  


.

.
[1] CWE-310 - http://cwe.mitre.org/data/definitions/310.html
[2] OWASP Top 10 2010 - (OWASP 2010) A7 Insecure Cryptographic Storage



10. (Use of Hard-coded Cryptographic Key)


.

.

. 
.

.
- C
1:

extern char *salt;

2:

typedef int SQLSMALLINT;

3:

int dbaccess(char *user, char *passwd)

4:

5:

char *server = "DBserver";

6:

char *cpasswd;

7:

SQLHENV henv;

8:

SQLHDBC hdbc;

9:

SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);

10:

SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);

11:

cpasswd = crypt(passwd, salt);

12:

/* */

13:

if (strcmp(cpasswd, "68af404b513073582b6c63e6b") != 0) {

14:

printf("Incorrect password\n");

15:

return -1;

16:

17:

18:
19:

. 
.



- C
1:

extern char *salt;

2:

typedef int SQLSMALLINT;

3:

char* getPassworld() {

4:

static char* pass="password";

5:

return pass;

6:

7:

int dbaccess(char *user, char *passwd)

8:

9:

char *server = "DBserver";

10:

char *cpasswd;

11:

char* storedpasswd;

12:

SQLHENV henv;

13:

SQLHDBC hdbc;

14:

SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);

15:

SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);

16:

cpasswd = crypt(passwd, salt);

17:

storedpasswd = getPassword();

18:

if (strcmp(cpasswd, storedpasswd) != 0)

19:

20:

printf("Incorrect password\n");

21:

SQLFreeHandle(SQL_HANDLE_DBC, &hdbc);

22:

SQLFreeHandle(SQL_HANDLE_ENV, &henv);

23:

return -1;

24:

25:
26:

,
.

.
[1] CWE-321 - http://cwe.mitre.org/data/definitions/321.html



11. : RSA
(Weak Encryption: Inadequate RSA Padding)
.
RSA        . 
NO_PADDING.

. 
RSA_pubic_encrypt()RSA_NO_PADDING .

.
- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <openssl/rsa.h>

4:

#define MAX_TEXT 512

5:

void RSAEncrypt(char *text, int size)

6:

7:

char out[MAX_TEXT];

8:

RSA *rsa_p = RSA_new();

9:

/* RSANO_PADDING*/

10:

RSA_public_encrypt(size, text, out, rsa_p, RSA_NO_PADDING);


}

11:

RSA NO_PADDING
. RSA_pubic_encrypt()RSA_NO_PADDING
.

- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <openssl/rsa.h>

4:

#define MAX_TEXT 512

5:

void RSAEncrypt(char *text, int size)

6:

7:

char out[MAX_TEXT];

8:

RSA *rsa_p = RSA_new();


RSA_public_encrypt(size, text, out, rsa_p, RSA_PKCS1_OAEP_PADDING);

9:
10:

RSA_NO_PADDING .



.
[1] CWE-325 - http://cwe.mitre.org/data/definitions/325.html
[2] OWASP Top 10 2010 - (OWASP 2010) A7 Insecure Cryptographic Storage



12. : 
(Weak Cryptographic Hash: Hardcoded Salt)
.
. 
, 
. ,
rainbow .

. 
crypt() salt.

.
- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <unistd.h>

4:

#define MAX_TEXT 100

5:

void hardSalt(const char *text)

6:

{
char *out;

7:
8:

/* salt*/

9:

out = (char*) crypt(text, "xp");


}

10:

crypt()salt. 
.

- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <unistd.h>

4:

#define MAX_TEXT 100

5:

void hardSalt(const char *text, const char *os)

6:

7:

char *out;

8:

out = (char *) crypt(text, os);

9:

salt
.



.
[1] CWE-326 - http://cwe.mitre.org/data/definitions/326.html
[2] OWASP Top 10 2010 - (OWASP 2010) A7 Insecure Cryptographic Storage



13. 
(Use of a Broken or Riscky Cryptographic Algorithm)
.

. , RC2, RC4, RC5, RC6, MD4, MD5, SHA1, DES 
, 
.

. 
3-DES, AES.

.
- C
1:

#include <stdio.h>

2:

#include <string.h>

3:

#include <memory.h>

4:

#include <openssl/evp.h>

5:

#include <openssl/pem.h>

6:

#include <openssl/rsa.h>

7:

void encryption_init()

8:

{
EVP_CIPHER_CTX ctx;

9:
10:

EVP_CIPHER_CTX_init(&ctx);

11:

/* DES */

12:

EVP_EncryptInit(&ctx, EVP_des_ecb(), NULL, NULL);

13:

14:

DES . 3-DES, AES 


.



- C
1:

#include <stdio.h>

2:

#include <string.h>

3:

#include <memory.h>

4:

#include <openssl/rsa.h>

5:

void encryption_init(unsigned char *key, unsigned char *iv)

6:

7:

EVP_CIPHER_CTX ctx;

8:

EVP_CIPHER_CTX_init(&ctx);
/*AES */

9:

EVP_EncryptInit(&ctx, EVP_aes_128_cbc(), key, iv);

10:

11:
12:

DES 3-DES, AES .

.
[1] CWE-327 - http://cwe.mitre.org/data/definitions/327.html
[2] OWASP Top 10 2010 - (OWASP 2010) A7 Insecure Cryptographic Storage
[3] SANS Top 25 2010 - (SANS 2010) Porus Defense



14. (Use of Insufficiently Random Values)


.
. 
, SW
.

. 
seed.

.
- C
1:

#include <stdafx.h>

2:

#include <stdio.h>

3:

#include <stdlib.h>

4:

#include <time.h>

5:

int main(void)

6:

{
int count = 0;

7:
8:

int temp;

9:

printf("\n%s\n%s\n",

10:

"Some randomly distributed integers will be printed.",

11:

"How many do you want to see? ");

12:

/* srand()seed.*/

13:

srand( 100 );

14:

while ( 1 )
{

15:

if ( count % 6 == 0) printf("%s", "\n");

16:
17:

temp = rand()%101;

18:

if( temp != 100 )


count++;

19:

else

20:
21:

break;

22:

printf("%5d", temp );
}

23:

printf("\n100: %d \n" , count );

24:

return 0;

25:
26:

  1)seed   2) seed  3)


seed.



- C
1:

#include <stdafx.h>

2:

#include <stdio.h>

3:

#include <stdlib.h>

4:

#include <time.h>

5:

int main(void)

6:

7:

int count = 0;

8:

int temp;

9:

int randNum = 0;
printf("\n%s\n%s\n",

10:
11:

"Some randomly distributed integers will be printed.",

12:

"How many do you want to see? ");

13:

printf("%s\n", "Init random number : ");

14:

/**/

15:

randNum = getch();

16:

while ( 1 ) {

17:

if ( count % 6 == 0)

18:

printf("%s", "\n");

19:

/*seed*/

20:

srand(randNum);
temp = rand()%101;

21:

if( temp != 100 )

22:

count++;

23:

else

24:

break;

25:

printf("%5d", temp );

26:

27:

printf("\n100: %d \n" , count );

28:

return 0;

29:
30:

seed.

.
[1] CWE-330 - http://cwe.mitre.org/data/definitions/330.html
[2] OWASP Top 10 2010 - (OWASP 2010) A7 Insecure Cryptographic Storage
[3] SANS Top 25 2009 - (SANS 2009) Porus Defense



15. (Multiple Binds to the Same Port)


.

.
, 
         
.

. 
SO_REUSEADDRINADDR_ANY.

.
- C
1:

#include <stdio.h>

2:

#include <sys/types.h>

3:

#include <sys/socket.h>

4:

#include <netinet/in.h>

5:

void bind_socket(void) {

6:

int server_sockfd;

7:

int server_len;

8:

struct sockaddr_in server_address;

9:

int optval;

10:

unlink("server_socket");

11:

server_sockfd = socket(AF_INET, SOCK_STREAM, 0);

12:

optval = 1;

13:

setsockopt(server_sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval);

14:

server_address.sin_family = AF_INET;

15:

server_address.sin_port = 21;
server_address.sin_addr.s_addr = htonl(INADDR_ANY);

16:
17:

/* SO_REUSEADDRINADDR_ANY*/
server_len = sizeof(struct sockaddr_in);

18:

bind(server_sockfd, (struct sockaddr *) &server_address, server_len);

19:
20:

SO_REUSEADDR, INADDR_ANY
.



- C
1:

#include <stdio.h>

2:

#include <sys/types.h>

3:

#include <sys/socket.h>

4:

#include <netinet/in.h>

5:

void bind_socket(void) {
int server_sockfd;

6:
7:

int server_len;

8:

struct sockaddr_in server_address;

9:

unlink("server_socket");

10:

server_sockfd = socket(AF_INET, SOCK_STREAM, 0);

11:

server_address.sin_family = AF_INET;

12:

server_address.sin_port = 21;

13:

server_address.sin_addr.s_addr = htonl(INADDR_ANY);

14:

server_len = sizeof(struct sockaddr_in);


bind(server_sockfd, (struct sockaddr *) &server_address, server_len);

15:
16:

closesocket(server_sockfd);

17:

SO_REUSEADDRINADDR_ANY
.

.
[1] CWE-605 - http://cwe.mitre.org/data/definitions/605.html



16. (Password in Comment)


.
. SW 
, (Reverse Engineering)
.

. 
.

.
- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

/* default password is "abracadabra". */

4:

int verifyAuth(char *ipasswd, char *orgpasswd)

5:

6:

char* admin="admin";

7:

if (strncmp(ipasswd, orgpasswd, sizeof(ipasswd)) != 0) {


printf("Authetication Fail!\n");

8:

9:

return admin;

10:

11:

.
- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

/* */
int verifyAuth(char *ipasswd, char *orgpasswd)

4:
5:

{
char* admin="admin";

6:
7:

if (strncmp(ipasswd, orgpasswd, sizeof(ipasswd)) != 0) {


printf("Authetication Fail!\n");

8:
9:

10:

return admin;

11:

, .

.
[1] CWE-615 - http://cwe.mitre.org/data/definitions/615.html
[2] OWASP Top 10 2010 - (OWASP 2010) A7 Insecure Cryptographic Storage



17. 
(Incorrect Permission Assignment for Critical Resource)
. 
SW
, .

. 
, , SW 
.
, 
.

.
- C
1:

// : rw-rw-rw-, : rwxrwxrwx

2:

umask(0);

3:

FILE *out = fopen("important_file", "w");

4:

if (out) {
fprintf(out, "\n");

5:

fclose(out);

6:
7:

umask, 
/.

- C
1:

umask(077); // : rw-------, : rwx------

2:

FILE *out = fopen("important_file", "w");

3:

if (out) {
fprintf(out, "\n");

4:

fclose(out);

5:
6:

, 
umask.

. 
[1] CWE-732 - http://cwe.mitre.org/data/definitions/732.html
CWE-276 - http://cwe.mitre.org/data/definitions/276.html
CWE-277 - http://cwe.mitre.org/data/definitions/277.html
CWE-278 - http://cwe.mitre.org/data/definitions/278.html



CWE-279 -- http://cwe.mitre.org/data/definitions/279.html


CWE-281 - http://cwe.mitre.org/data/definitions/281.html
CWE-285 - http://cwe.mitre.org/data/definitions/281.html
[2] CWE/SANS Top 25 Most Dangerous Software Errors, http://cwe.mitre.org/top25/



4 
          
. 
.

1. : 
(Time-of-check Time-of-use (TOCTOU) Race Condition)
.
, 
.

, , 
, .

. 
. .
(mutex).

.
- C
1:

#include <stdio.h>

2:

#include <unistd.h.>

3:

void file_operation(char* file)

4:

5:

/* */

6:

if(!access(file,W_OK))

7:

{
f = fopen(file,"w+");

8:

operate(f);

9:

10:
11:

else {

12:

fprintf(stderr,"Unable to open file %s.\n",file);


}

13:
14:

access() fopen() 



.



- C
1:

#include <stdio.h>

2:

#include <unistd.h>

3:

void file_operation(char* file)

4:

5:

char *file_name;

6:

int fd;

7:

/* , open(), mode. */

8:

fd = open( file_name, O_WRONLY | O_CREAT | O_EXCL, S_IRWXU);

9:

if (fd == -1) {

10:

11:

/* chmod fchmod, openfd. */


if (fchmod(fd, S_IRUSR) == -1)

12:

13:

14:
15:

close(fd);

16:

, .

- C
1:

void f(pthread_mutex_t *mutex) {

2:

... ...

3:

pthread_mutex_lock(mutex);

4:

/* */

5:

pthread_mutex_unlock(mutex);
... ...

6:
7:

pthread_mutex_lock(). pthread_mutex_lock()
mutex, 
.

- C
1:

int f(pthread_mutex_t *mutex) {


int result;

2:
3:

// mutex 

4:

result = pthread_mutex_lock(mutex);

5:

if (0 != result)
return result;

6:
7:

/* */

8:

return pthread_mutex_unlock(mutex);

9:



lock.

.
[1] CWE-367 : - http://cwe.mitre.org/data/definitions/367.html
[2] CWE-362 : Race Condition - http://cwe.mitre.org/data/definitions/362.html
[3] SANS Top 25 2010 - (SANS 2010) Insecure Interaction
[4] Michael Howard, David LeBlanc and John Viega. "24 Deadly Sins of Software

Security".

"Sin 13: Race Conditions." Page 205. McGraw-Hill. 2010


[5] Andrei Alexandrescu. "volatile - Multithreaded Programmer's Best Friend". Dr. Dobb's. 2008-02-01
[6] Steven Devijver. "Thread-safe webapps using Spring"
David Wheeler. "Prevent race conditions". 2007-10-04
[7] Matt Bishop. "Race Conditions, Files, and Security Flaws; or the Tortoise and the Hare Redux". September 1995
[8] Johannes Ullrich. "Top 25 Series - Rank 25 - Race Conditions". SANS Software Security Institute. 2010-03-26



2. 
(Symbolic Name not Mapping to Correct Object)
.
. 

.

. 
.

.
- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

int main(int argc, char* argv[])

4:

5:

char* file;

6:

FILE *f;

7:

/* 
*/

8:

if(!access(file,W_OK))

9:

10:

f = fopen(file,"w+");

11:

operate(f);

12:

13:

14:

else {
fprintf(stderr,"Unable to open file %s.\n",file);

15:
16:

TOCTOU (KCWE-367)
. , access() fopen()
.



- C
1:

#include <stdio.h>

2:

#include <unistd.h>

3:

#include <string.h>

4:

int main (int argc, char* argv[])

5:

{
char* filename;

6:
7:

/* */

8:

if(mkstemp(filename))

9:

{
FILE* tmp = fopen(filename,"wb+");

10:
11:

while((recv(sock,recvbuf,DATA_SIZE, 0) > 0) && (amt!=0))

12:

amt = fwrite(recvbuf,1,DATA_SIZE,tmp);
}

13:
14:

.

.
[1] CWE-386 - http://cwe.mitre.org/data/
definitions/386.html



3. (Uncontrolled Recursion)
.

.
: (lazy evaluation 
) (base case)
. "data flow 
" ,

. , 
stackprogram counter, 
stack 
.

. 

.

.
- C
1:

#include <stdio.h>

2:

#include <unistd.h>

3:

#include <string.h>

4:

int fac(n) {

5:

return n*fac(n-1);

6:

.

- C
1:

#include <stdio.h>

2:

#include <unistd.h>

3:

#include <string.h>

4:

int fac(n) {
if (n <= 0)

5:

return 1;

6:

else

7:
8:

return n*fac(n-1);

9:

.



.
[1] CWE-674 - http://cwe.mitre.org/data/definitions/674.html



5
          
.

1. 
(Information exposure through an error message)
.
SW, , 
. 
.

. 
SW
.

.
- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <string.h>

4:

int main (int argc, char* argv[])

5:

6:

char* path=getenv("MYPATH");

7:

/* */

8:

fprintf(stderr,path);
return 0;

9:
10:

(MYAPTH) 
.



- C
1:

##include <stdio.h>

2:

#include <stdlib.h>

3:

#include <string.h>

4:

int main (int argc, char* argv[])

5:

{
char* path=getenv("MYPATH");

6:

return 0;

7:
8:

.

.
[1] CWE-209 - http://cwe.mitre.org/data/definitions/209.html



2. 
(Improper Check for Unusual or Exceptional Conditions)
. 

, .

. 
, , 
.

. 
- C
1:

char fromBuf[10], toBuf[10];

2:

fgets(fromBuf, 10, stdin);

3:

strcpy(toBuf, fromBuf);

4:

......

buf 10'\0', 
'\0'strcpy().

- C
1:

char fromBuf[10], toBuf[10];

2:

char *retBuf = fgets(fromBuf, 10, stdin);

3:

// .

4:

if ( retBuf != fromBuf ) {

5:

println(");

6:

return;

7:

8:

strcpy(toBuf, fromBuf);

9:

...

fgets() , strcpy()


.

. 
[1] CWE-754 - http://cwe.mitre.org/data/definitions/754.html
CWE-252 - http://cwe.mitre.org/data/definitions/252.html
CWE-253 - http://cwe.mitre.org/data/definitions/253.html
CWE-273 - http://cwe.mitre.org/data/definitions/273.html



CWE-296      - http://cwe.mitre.org/data/definitions/296.html
CWE-297  -   - http://cwe.mitre.org/data/definitions/297.html
CWE-298 - http://cwe.mitre.org/data/definitions/298.html
CWE-299 - http://cwe.mitre.org/data/definitions/299.html
[2] SANS Top 25 Most Dangerous Software Errors, http://www.sans.org/top25-software-errors/
[3] M. Howard, D. LeBlanc, Writing Secure Code, Second Edition, Microsoft Press



6 
, , , , , 
     .    ,
,        , 
.

1. 
(Signed to Unsigned Conversion Error)
.
(signed integer)(unsigned integer)
. 
, SW.

. 
.



- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <string.h>

4:

#define BUFSIZE 100

5:

unsigned int len(char *s)

6:

7:

unsigned int l = 0;

8:

if (s == NULL)

9:

{
return -1;

10:

11:

l = strnlen(s, BUFSIZE-1);

12:

return l;

13:
14:

15:

int main(int argc, char **argv)

16:

17:

char buf[BUFSIZE];

18:

unsigned int l = 0;

19:

l = len(argv[1]);

20:

strncpy(buf, argv[1], l);

21:

buf[l] = '\0';

22:

printf("last character : %c\n", buf[l-1]);

23:

return 0;

24:
25:

len()NULL-1
unsigned intint4byte4,294,967,295(0xffffffff) . 

.



- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <string.h>

4:

#define BUFSIZE 100

5:

unsigned int len(char *s)

6:

7:

unsigned int l = 0;

8:

if (s == NULL) {

9:

return 0;

10:

11:

l = strnlen(s, BUFSIZE-1);

12:

return l;

13:

14:

int main(int argc, char **argv)

15:

{
char buf[BUFSIZE];

16:
17:

unsigned int l = 0;

18:

l = len(argv[1]);

19:

if (l > 0) {

20:

strncpy(buf, argv[1], l);

21:

buf[l] = '\0';

22:

printf("last character : %c\n", buf[l-1]);


}

23:

return 0;

24:
25:

len() NULL-1 0


0strncpy() .

.
[1] CWE-195 - http://cwe.mitre.org/data/definitions/195.html



2. (Type Mismatch: Integer to Character)


.
(character).
4byte1byte
. 
SW.

. 
.

.
- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

char f(char bc)

4:

{
return bc;

5:
6:

7:

char char_type()

8:

9:

char bA;

10:

int iB;

11:

iB = 24;

12:

bA = iB;

12:

f(iB);

13:

printf("int = %d char = %d\n", iB, bA);


return iB;

13:
14:

1 byte charint/charoverflow. 


.



- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

int f(int bc)

4:

5:

return bc;

6:

7:

int char_type()

8:

{
int bA;

9:
10:

int iB;

11:

iB = 24;

12:

bA = iB;

13:

f(iB);

14:

printf("int = %d char = %d\n", iB, bA);

15:

return iB;

16:

.

.
[1] CWE-398 - http://cwe.mitre.org/data/definitions/398.html



3. (Improper Resource Shutdown or Release)


.
.
 ,      (open file descriptor),  (heap
memory), (socket) .  
. 

.

. 
.

.
- C
1:

2:

void sqlDB()

3:

4:

SQLHANDLE env_hd, con_hd;

5:

SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env_hd);


SQLAllocHandle(SQL_HANDLE_DBC, env_hd, &con_hd);

6:
7:

8:

void serverSock()
struct sockaddr_in serverAddr;

9:

struct sockaddr *server = (struct sockaddr *)(&serverAddr);

10:
11:

int listenFd = socket(AF_INET, SOCK_STREAM, 0);

12:

bind(listenFd, server, sizeof(serverAddr));

13:

listen(listenFd, 5);

14:

while (1) {

15:

int connectFd = accept(listenFd, (struct sockaddr *) NULL, NULL);


shutdown(connectFd, 2);

16:

17:
18:

ODBC APIenvironment, dbconnection 


.



- C
1:

2:

void sqlDB()

3:

{
SQLHANDLE env_hd, con_hd;

4:
5:

SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &;env_hd);

6:

SQLAllocHandle(SQL_HANDLE_DBC, env_hd, &;con_hd);

7:

SQLFreeHandle(SQL_HANDLE_DBC, con_hd);

8:

SQLFreeHandle(SQL_HANDLE_ENV, env_hd);

9:

10:

void serverSock()

11:

{
struct sockaddr_in serverAddr;

12:
13:

struct sockaddr *server = (struct sockaddr *)(&serverAddr);

14:

int listenFd = socket(AF_INET, SOCK_STREAM, 0);

15:

bind(listenFd, server, sizeof(serverAddr));

16:

listen(listenFd, 5);

17:

while (1) {

18:

int connectFd = accept(listenFd, (struct sockaddr *) NULL, NULL);

19:

shutdown(connectFd, 2);
close(connectFd);

20:

21:
22:

shutdown(listenFd, 2);

23:

close(listenFd);

24:

ODBC APIenvironment, dbconnection 


.

.
[1] CWE-404 - http://cwe.mitre.org/data/definitions/404.html
[2] OWASP Top 10 2004 - (OWASP 2004) A9 Application Denial of Service
[3] SANS Top 25 2009 - (SANS 2009) Risky Resource Management



4. (NULL Pointer Dereference)


.

.
'NULL'
. NULL
. NULL , 
.

. 
NULL
crash . 
.

.
- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <string.h>

4:

#define BUFSIZE 100

5:

int main() {
char *p = NULL;

6:
7:

char cgi_home[BUFSIZE];

8:

p = getenv("CGI_HOME");

9:

strncpy(cgi_home, p, BUFSIZE-1);

10:

cig_home[BUFSIZE-1] = '\0';
return 0;

11:
12:

CGI_HOME" getenv() NULL


. NULL.



- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <string.h>

4:

#define BUFSIZE 100

5:

int main() {
char *p = NULL;

6:
7:

char cgi_home[BUFSIZE];

8:

p = getenv("CGI_HOME");

9:

if (p == NULL) {
exit(1);

10:
11:

12:

strncpy(cgi_home, p, BUFSIZE-1);

13:

cig_home[BUFSIZE-1] = '\0';

14:

return 0;

15:

strncpy()   getenv()    NULL  


.

.
[1] CWE-476 - http://cwe.mitre.org/data/definitions/476.html
[2] OWASP Top 10 2004 - (OWASP 2004) A9 Application Denial of Service



5. (Return of Stack Variable Address)


.
.
. 

. . 
, 
.

. 
. 

.

.
- C
1:

char *rpl() {
char p[10];

2:
3:

/* */

4:

return p;

5:

6:

int main() {

7:

char *p;

8:

p = rpl();

9:

*p = '1';
return 0;

10:
11:

name 
.



- C
1:

#include <stdlib.h>

2:

#include <string.h>

3:

char *rpl() {

4:

char p[10];

5:

int size = 10;

6:
7:

if( size < 20 ) {


/* , 
*/

8:

char *buf = (char *)malloc(size);

9:

if (!buf)

10:

exit(1);

11:

memcpy(buf,p,10);

12:

}
return buf;

13:
14:

int main()

15:

16:

char *p;

17:

p = rpl();

18:

*p = '1';

19:

free(p);

20:

return 0;

21:

.

.
[1] CWE-562 - http://cwe.mitre.org/data/definitions/562.html
[2] OWASP Top 10 2004 - (OWASP 2004) A9 Application Denial of Service



6. (Code Correctness: Macro Misuse)


.
. 
 .

. 
.

. 
.

.
- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <pthread.h>

4:

void routine(void *i)

5:

6:

int j = (*(int*)(i))++;

7:

8:

void helper() {

9:

int a = 0;

10:

pthread_cleanup_push (routine, ((void*)&a));

11:

pthread_cleanup_push()pthread_clenaup_pop()
. .

- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <pthread.h>

4:

void routine(void *i)

5:

6:

int j = (*(int*)(i))++;

7:

8:

void helper() {

9:

int a = 0;

10:

pthread_cleanup_push (routine, ((void*)&a));

11:

pthread_cleanup_pop (1);

12:



pthread_cleanup_push()pthread_clenaup_pop() .

.
[1] CWE-730 OWASP Top Ten 2004 Category A9 - http://cwe.mitre.org/data/definitions/730.html



7. : 
(Code Correctness:Memory Free on Stack Variable)
.
.

. 
, 
.

.
- C
1:

#include stdlib.h

2:

int main() {

3:

char p[10];

4:

/* */

5:

free(p);
return 0;

6:
7:

.

- C
1:

#include stdlib.h

2:

int main() {

3:

char p[10];
return 0;

4:
5:

   Call Stack     
.

.
[1] CWE-730 OWASP Top Ten 2004 Category A9 - http://cwe.mitre.org/data/definitions/730.html



8. : 
(Code Correctness: Premature thread Termination)
.
, 
. 
pthread_join()

. , ,
          .
PTHREADpthread_detach()(detach)
attribute"" 
.

. 
joindetach.

.
- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <pthread.h>

4:

int th_worker(void *data)

5:

{
int a = *(int *)data;

6:

return a + 100;

7:
8:

9:

int run_thread1(void)

10:

11:

pthread_t th;

12:

int status, a = 1;

13:

if (pthread_create(&th, NULL, (void*(*)(void*))th_worker, (void *)&a) < 0) {

14:

perror("thread create error: ");

15:

exit(0);

16:

17:

printf("Return without waiting for child thread\n");


return 0;

18:
19:

joindetach.



- C
1:

#include <stdio.h>

2:

#include <stdlib.h>

3:

#include <pthread.h>

4:

int th_worker(void *data)

5:

{
int a = *(int *)data;

6:

return a + 100;

7:
8:

}
int run_thread1(void)

9:
10:

11:

pthread_t th;

12:

int status, a = 1;
if (pthread_create(&th, NULL, (void*(*)(void*))th_worker, (void *)&a) < 0) {

13:
14:

perror("thread create error: ");

15:

exit(0);

16:

17:

printf("Return after waiting for child thread\n");

18:

pthread_join(th, (void**)&status);

19:

return 0;

20:

pthread_join()       .
pthread_create() pthread_join()
.

. 
[1] CWE-730 OWASP Top Ten 2004 Category A9 - http://cwe.mitre.org/data/definitions/730.html



9. (Allocation of Resources Without Limits or Throttling)


. 
, 
, .

. 
, .
.
. 
Pool(Thread Pool, Connection Pool ).

.
- C
1:

int processMessage(char **message)

2:

3:

char *body;

4:

int length = getMessageLength(message[0]);

5:

if (length > 0) {

6:

body = &message[1][0];

7:

processMessageBody(body);
......

8:

9:

else {......}

10:

11:

Body, 
Body, .

- C
1:

int processMessage(char **message)

2:

3:

char *body;

4:

unsigned int length = getMessageLength(message[0]);

5:

// .
if (length > 0 && length < MAX_LENGTH) {

6:
7:

body = &message[1][0];

8:

processMessageBody(body);
......

9:

10:

else {......}

11:
12:



unsigned int, 


.

. 
[1] CWE-400 - http://cwe.mitre.org/data/definitions/400.html
CWE-774 - http://cwe.mitre.org/data/definitions/774.html
CWE-789 - http://cwe.mitre.org/data/definitions/789.html
CWE-770 - http://cwe.mitre.org/data/definitions/770.html
[2] M. Howard and D. LeBlanc. "Writing Secure Code". Chapter 17, "Protecting Against Denial
of Service Attacks" Page 517. 2nd Edition. Microsoft. 2002
[3] J. Antunes, N. Ferreira Neves and P. Verissimo. "Detection and Prediction of
Resource-Exhaustion Vulnerabilities". Proceedings of the IEEE International



7
       ,  

. 
.

1. (Leftover Debug Code)


, 
.

. 
main
.

. 
- C
1:

int main(int argc,char** argv) {


println("Debug Info...");

2:
3:

main()println() 
.

- C
1:

// main().

2:

......

main().

. 
[1] CWE-489 - http://cwe.mitre.org/data/definitions/489.html
[2] M. Howard and D. LeBlanc. "Writing Secure Code". Page 505. 2nd Edition. Microsoft.
2002



2 
1
SQL(Dynamic SQL) : SQL, 
 DBSQL.
(Mutex) : 
, (critical section)
.
(Sandbox) : (Executable File)
.
SQL(Static SQL) : SQL
.
 : , 
.
(Whitelist) : (Black List), IP 


.
(Hash) : (),
(message digest function)()
()''.
Advanced Encryption Standard (AES) : 
DES, (NIST)52001
11(FIPS 197).
Big Endian : 
.
DES : DES(Data Encryption Standard)
64,
64, 64. (Brute Force)
.
LDAP(Lightweight Directory Access Protocol) : TCP/IP 
.
Little Endian : 
.



OAEP(Optimal Asymmetric Encryption Padding) : BellareRogaway


RSApadding scheme
Private key : 

Public key : , 
, 
.
SHA(Secure Hash Algorithm) : .
RC5 : 1994RSA SecurityRonald Rivest.
Umask : .



2
ACL : Access Control List
AES : Advanced Encryption Standard
CSRF : Cross-Site Request Forgery
CWE : Common Weakness Enumeration
DES : Data Encryption Standard
ESAPI : Enterprise Security API
HTML : Hyper Text Markup Language
HTTPS : Hypertext Transfer Protocol over Secure Socket Layer
JAAS : Java Authentication and Authorization Service
JDBC : Java Database Connectivity
LDAP : Lightweight Directory Access Protocol
MSB : Most Significant Bit
OAEP : Optimal Asymmetric Encryption Padding
OWASP : Open Web Application Security Project
RSA : Ron Rivest, Adi Shamir, Leonard Adleman
SHA : Secure Hash Algorithm
SQL : Structured Query Language
OpenSSL : Open Secure Socket Layer
URL : Uniform Resource Locator
XSS : Cross-Site Scripting
WAS : Web Application Server



"OESPJE+"7"












"1*


OVMM




FRVBMT
IBTI$PEF























































QSJWBUF


QSJWBUF
















<1> Android-JAVA




CWE-ID



CWE-23



CWE-36

null 

CWE-398

equals()hashCode() 

CWE-581



CWE-319



CWE-327



CWE-330







: 

CWE-367



CWE-674



CWE-209



CWE-390

CWE-476

private -

CWE-495

private -

CWE-496



CWE-497

API



1 Android-JAVA 
1 
. 
        
,         
.

1. (Relative Path Traversal)


.
 , 
, 
, .

. 
. 
, replaceAll() 
(",/,\).

.
- Android-JAVA
1:

2:

public void f(Properties request) {

3:

4:

String name = request.getProperty("filename");

5:

if( name != null ) {

6:

File file = new File("/usr/local/tmp/" + name);

7:

file.delete();
}

8:

9:
10:

(name). name
../../../rootFile.txt
.

- Android-JAVA
1:

2:

public void f(Properties request) {

3:

4:

String name = request.getProperty("user");

5:

if ( name != null && !"".equals(name) ) {

6:

name = name.replaceAll("/", "");

7:

name = name.replaceAll("\\", "");

8:

name = name.replaceAll(".", "");

9:

name = name.replaceAll("&", "");

10:

name = name + "-report";

11:

File file = new File("/usr/local/tmp/" + name);

12:

if (file != null) file.delete();


}

13:

14:
15:

Null, (name)
(/, \\, &, . )replaceAll
.

. 
[1] CWE-23 - http://cwe.mitre.org/data/definitions/23.html
[2] OWASP Top 10 2010 - (OWASP 2010) A4 Insecure Direct Object Reference
[3] SANS Top 25 2010 - (SANS 2010) Risky Resource Management, Rank 7 CWE ID 22:
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')

2. (Absolute Path Traversal)


.

. ,

. , , 
.

. 
replaceAll ,

.

.
- Android-JAVA
1:

2:

public void onCreate(Bundle savedInstanceState) {

3:

super.onCreate(savedInstanceState);

4:

File file = new File(android.os.Environment.getExternalStorageDirectory(), "inputFile");

5:

try {

6:

InputStream is = new FileInputStream(file);

7:

Properties props = new Properties();

8:
9:

props.load(is);
String name = props.getProperty("filename");

10:

G file = new File("/usr/local/tmp/" + name);

11:

G file.delete();

12:

is.close();

13:

} catch (IOException e) {

14:

Log.w("Error", "", e);

15:

16:

, 
, .

- Android-JAVA
1:

2:

public void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);

3:
4:

File file = new File(android.os.Environment.getExternalStorageDirectory(), "inputFile");

5:

try {

6:
7:

InputStream is = new FileInputStream(file);

8:

Properties props = new Properties();

9:

props.load(is);

10:

String name = props.getProperty("filename");

11:

if (name.indexOf("/") <0) {

12:

G G G file = new File(name);

13:

G G G file.delete();
}G

14:
15:

G G G G is.close();

16:

G } catch (IOException e) {

17:

Log.w("Error", "", e);

18:

19:

, "\"
"/"
.

. 
[1] CWE-36 - http://cwe.mitre.org/data/definitions/36.html
[2] OWASP Top 10 2010 - (OWASP 2010) A4 Insecure Direct Object Reference
[3] SANS Top 25 2010 - Risky Resource Management, Rank 7 CWE ID 22: Improper Limitation
of a Pathname to a Restricted Directory ('Path Traversal')

2 API
API(Application Programming Interface)    
, 
. API API
.

1. null (Missing Check for Null Parameter)


.
Java Object.equals(), Comparable.compareTo() Comparator.compare()
null. 
.

. 
Object.equals(), Comparable.compareTo()Comparator.compare() 
null.

.
- Android-JAVA
1:

public void onCreate(Bundle savedInstanceState) {

2:

super.onCreate(savedInstanceState);

3:

4:

5:

public boolean equals(Object object)

6:

7:

return (toString().equals(object.toString()));

8:

null.

- Android-JAVA
1:

public void onCreate(Bundle savedInstanceState) {

2:

super.onCreate(savedInstanceState);

3:

4:

5:

public boolean equals(Object object)

6:

{
if(object != null)

7:
8:

return (toString().equals(object.toString()));

else return false ;

9:
10:

null.

. 
[1] CWE-398 - http://cwe.mitre.org/data/definitions/398.html

2. equals()hashCode() 
(Object Model Violation: Just one of equals() and hashCode() Defined)
.
Java , Java.
"a.equals(b) == true""a.hashCode() == b.hashCode()" . 
equals()hashCode().

. 
equals()hashCode()hashCode()
equals().

.
- Android-JAVA

1:
2:

public void onCreate(Bundle savedInstanceState) {

3:

super.onCreate(savedInstanceState);

4:

5:

6:

public boolean equals(Object obj) {

7:

if (obj == null)

8:

return false;

9:

int i1 = this.hashCode();

10:

int i2 = obj.hashCode();

11:
12:

if (i1 == i2)

13:

return true;

14:

else

15:

return false;

16:

equals()hashCode() .

- Android-JAVA

1:
2:

public boolean equals(Object obj) {

3:

if (obj == null)

4:

return false;

5:

int i1 = this.hashCode();

6:

int i2 = obj.hashCode();

7:

8:

if (i1 == i2)

9:

return true;

10:

else

11:

return false;

12:

13:

public int hashCode() {

14:

return new HashCodeBuilder(17, 37).toHashCode();

15:

equals()hashCode() .

. 
[1] CWE-581 equals()hashCode() - http://cwe.mitre.org/data/definitions/581.html

3
. 
. , , , ,
.

1. 
(Cleartext Transmission of Sensitive Information)
.
SW
, .

. 
.

.
- Android-JAVA
1:

2:

public void onCreate(Bundle savedInstanceState) {

3:

int port = 443;

4:

String hostname = "hostname";

5:

Socket socket = new Socket(hostname, port);

6:

InputStream in = socket.getInputStream();

7:

OutputStream out = socket.getOutputStream();

8:

// Read from in and write to out...

9:

in.close();

10:

out.close();G

11:

.
.

- Android-JAVA
1:

2:

public void onCreate(Bundle savedInstanceState) {

3:

int port = 443;

4:

String hostname = "hostname";


SocketFactory socketFactory = SSLSocketFactory.getDefault();

5:
6:

G Socket socket = socketFactory.createSocket(hostname, , port);

7:

InputStream in = socket.getInputStream();

8:

G OutputStream out = socket.getOutputStream();

9:

G // Read from in and write to out...

10:

G in.close();

11:

G out.close();G

12:

128
.

. 
[1] CWE-319 -http://cwe.mitre.org/data/definitions/319.html
[2] OWASP Top 10 2007 - (OWASP 2007) A9 Insecure Communications



2. 
(Use of a Broken or Riscky Cryptographic Algorithm)
.
. 
         
. 
, 
. RC2, RC4, RC5, RC6, MD4, MD5, SHA1, DES 
.

. 
AES.

.
- Android-JAVA
1:

2:

public byte[] encrypt(byte[] msg, Key k) {


byte[] rslt = null;

3:
4:

try {

5:
6:

// DES.

7:

Cipher c = Cipher.getInstance("DES");

8:

c.init(Cipher.ENCRYPT_MODE,

9:

rslt = c.update(msg);
} catch (InvalidKeyException e) {

10:

11:
12:

13:

return rslt;
}

14:
15:

k);

DES .



- Android-JAVA

1:

public byte[] encrypt(byte[] msg, Key k) {

2:

byte[] rslt = null;

3:
4:

try {

5:

// DES AES .

6:
7:

Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");

8:

c.init(Cipher.ENCRYPT_MODE,
rslt = c.update(msg);

9:

} catch (InvalidKeyException e) {

10:

11:

12:

return rslt;

13:

14:
15:

k);

AES 128
.

. 
[1] CWE-327 - http://cwe.mitre.org/data/definitions/327.html
[2] OWASP Top 10 2010 - (OWASP 2010) A7 Insecure Cryptographic Storage
[3] SANS Top 25 2010 - (SANS 2010) Porus Defense - CWE ID 327 Use of a Broken or Risky
Cryptographic Algorithm
[4] Bruce Schneier. "Applied Cryptography". John Wiley &Sons. 1996.



3. (Use of Insufficiently Random Values)


.
. 
, SW
.

. 
seed
.

.
- Android-JAVA
1:

2:

public double roledice() {


return Math.random();

3:

4:
5:

java.lang.Math random() seed.

- Android-JAVA
1:

import java.util.Random;

2:

import java.util.Date;

3:

public int roledice() {

4:
5:

Random r = new Random();

6:

// setSeed() rlong.

7:

r.setSeed(new Date().getTime());

8:

// 

9:

return (r.nextInt()%6) + 1;
}

10:
11:

java.util.Random seed. 
Random .

. 
[1] CWE-330 - http://cwe.mitre.org/data/definitions/330.html
[2] SANS Top 25 2009 - (SANS 2009) Porus Defense - CWE ID 330 Use of Insufficiently
Random Values
[3] J. Viega and G. McGraw. "Building Secure Software: How to Avoid Security Problems the Right Way". 2002.



4. (Files under Global Access)


.
      (MODE_WORLD_READABLE,
MODE_WORLD_WRITABLE).

. 
.

.
- Android-JAVA
1:

public void onCreate(Bundle savedInstanceState) {

2:

super.onCreate(savedInstanceState);

3:

try {

4:

FileOutputStream fOut = openFileOutput("test", MODE_WORLD_READABLE);

5:

OutputStreamWriter out1 = new OutputStreamWriter(fOut);

6:

out1.write("Hello World");

7:

out1.close();

8:

fOut.close();

9:

} catch (Throwable t) {

10:

11:

MODE_WORLD_READABLE.

- Android-JAVA
1:

public void onCreate(Bundle savedInstanceState) {

2:

super.onCreate(savedInstanceState);

3:

try {

4:

G FileOutputStream fOut = openFileOutput("test", MODE_PRIVATE);

5:

OutputStreamWriter out1 = new OutputStreamWriter(fOut);

6:

out1.write("Hello World");

7:

out1.close();

8:

fOut.close();

9:

} catch (Throwable t) {

10:

11:

MODE_PRIVATE.

. 
[1] http://developer.android.com/index.html
[2] ,



5. 
(Exported Access to Components)
.
manifest.xml android:exported="true"
. 

. (resolver)
System ID
.

. 
.

.
- Android-JAVA
1:

<?xml version="1.0" encoding="utf-8"?>

2:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

3:

package="com.example.android.samplesync"

android:versionCode="1"

an-

droid:versionName="1.0">
4:

5:

<application android:icon="@drawable/icon" android:label="@string/label">

6:

<service android:name=".syncadapter.SyncService" android:exported="true">

7:

<intent-filter>

8:

<action android:name="android.content.SyncAdapter"/>

9:

</intent-filter>

10:

<meta-data android:name="android.content.SyncAdapter"

11:

android:resource="@xml/syncadapter"/>

12:

<meta-data android:name="android.provider.CONTACTS_STRUCTURE"

13:

android:resource="@xml/contacts"/>

14:

</service>

15:

</application>

16:

<uses-sdk android:minSdkVersion="5"/>

17:

</manifest>

SyncService   android:exported="true"    
.



- Android-JAVA
1:

<?xml version="1.0" encoding="utf-8"?>

2:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

3:

package="com.example.android.samplesync"

android:versionCode="1"

an-

droid:versionName="1.0">
4:

5:

<application android:icon="@drawable/icon" android:label="@string/label">

6:

<service android:name=".syncadapter.SyncService" android:exported="false">

7:

<intent-filter>

8:

<action android:name="android.content.SyncAdapter"/>

9:

</intent-filter>

10:

<meta-data android:name="android.content.SyncAdapter"

11:

android:resource="@xml/syncadapter"/>

12:

<meta-data android:name="android.provider.CONTACTS_STRUCTURE"

13:

android:resource="@xml/contacts"/>

14:

</service>

15:

</application>

16:

<uses-sdk android:minSdkVersion="5"/>

17:

</manifest>

android:exported "false""false"
.

. 
[1] http://developer.android.com/index.html
[2] ,



6. 
(Access Control Bypass using Share User ID)
.
Manifest.xml  manifest  android:sharedUserId   



. 
.

. 
.

.
- Android-JAVA
1:

2:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

3:

package="com.example.android.apis"

4:

android:versionCode="1"

5:

android:versionName="1.0"

6:

android:sharedUserId="android.uid.developer1">

Manifest.xml  manifest  android:sharedUserId   


sharedUserId 
.

- Android-JAVA
1:

2:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

3:

package="com.example.android.apis"

4:

android:versionCode="1"

5:

android:versionName="1.0">

6:

<!-- android:sharedUserId="android.uid.developer1" . -->G

Manifest.xml manifest android:sharedUserId ,


.

. 
[1] http://developer.android.com/index.html
[2] ,



4 
          
()()
 .

    (dead lock),  

, .

1. : 
(Time-of-check Time-of-use (TOCTOU) Race Condition)
.
.
. 
, , .

. 
(: ), 
.

.
- Android-JAVA
1:

public class UA367 extends Activity {


@override

2:
3:
4:

super.onCreate(savedInstanceState);

5:

G FileAccessThread fileAccessThread = new FileAccessThread();

6:

FileDeleteThread fileDeleteThread = new FileDeleteThread();

7:

fileAccessThread.start();

8:

fileDeleteThread.start();

9:

10:

11:

12:

class FileAccessThread extends Thread {

13:
14:

try {
File f = new File("Test_367.txt");

16:

if (f.exists()) { // 

17:

BufferedReader br = new BufferedReader(new FileReader(f));

18:

br.close();

20:
21:

public void run() {

15:

19:



public void onCreate(Bundle savedInstanceState) {

}
} catch(FileNotFoundException e) {
System.out.println("Exception Occurred") ; //

} catch(IOException e) {

22:

System.out.println("Exception Occurred") ; //

23:

24:
25:

26:
27:

class FileDeleteThread extends Thread {


public void run() {

28:

try {

29:
30:

File f = new File("Test_367.txt");

31:

if (f.exists()) { // 
f.delete();

32:

33:

} catch(FileNotFoundException e) {

34:

System.out.println("Exception Occurred") ; //

35:

} catch(IOException e) {

36:

System.out.println("Exception Occurred") ; //

37:

38:

39:
40:


, 
. 
.

- Android-JAVA
1:

public class SA367 extends ActivityG {

2:

public void onCreate(Bundle savedInstanceState) {

3:

super.onCreate(savedInstanceState);

4:

5:

FileAccessThread fileAccess = new FileAccessThread();

6:

Thread first = new Thread(fileAccess);

7:

Thread second = new Thread(fileAccess);

8:

Thread third = new Thread(fileAccess);

9:

Thread fourth = new Thread(fileAccess);

10:

first.start();

11:

second.start();

12:

third.start();

13:

fourth.start();

14:

15:

16:

17:

class FileAccessThread implements Runnable {G

18:

public synchronized void run() {G



19:

G G try {G

20:

File f = new File("Test.txt");G

21:

if (f.exists()) { // G

22:

G G G Thread.sleep(100);G // G

23:

G G G BufferedReader br = new BufferedReader(new FileReader(f));


System.out.println(br.readLine());G

24:
25:

G G G br.close();G // 

26:

G G G f.delete();G

27:

G }

28:

G G } catch (IOException e) {//

29:

System.err.println("IOException occured");

30:

G G }G

31:

}G

32:

(, ), 
.

. 
[1] CWE-367 : - http://cwe.mitre.org/data/definitions/367.html



2. (Uncontrolled Recursion)
.

 . ,  (base case)   
.

. 

.

.
- Android-JAVA
1:

2:

public int factorial(int n) {


// /.

3:

return n * factorial(n - 1);

4:
5:

   ,   /   
.

- Android-JAVA
1:

2:

public int factorial(int n) {

3:

int i;

4:

// .

5:

if (n == 1) {
i = 1;

6:

} else {

7:

i = n * factorial(n - 1);

8:

9:

return i;

10:
11:

.

. 
[1] CWE-674 - http://cwe.mitre.org/data/definitions/674.html



5 
, 
      .    
         
. 
 (  )         
.

1. (Information exposure through an error message)


.
SW, , 
. 
.

. 
SW
.

.
- Android-JAVA
1:

2:

public void onCreate(Bundle savedInstanceState) {

3:

super.onCreate(savedInstanceState);

4:

try{ throw new IOException(); }


catch (IOException e) {

5:
6:

e.printStackTrace();

.
- Android-JAVA
1:

2:

public void onCreate(Bundle savedInstanceState) {

3:

super.onCreate(savedInstanceState);

4:

try{
throw new IOException();

5:

6:

catch (IOException e) {

7:
8:

System.out.println("");

.

. 
[1] CWE-209 - http://cwe.mitre.org/data/definitions/209.html



2. (Detection of Error Condition Without Action)


.
, 
.

. 
(catch).

.
- Android-JAVA
1:

2:

private Connection conn;

3:
4:

public Connection DBConnect(String url, String id, String password) {


try {

5:
6:

String CONNECT_STRING = url

7:

InitialContext ctx = new InitialContext();

8:

DataSource datasource = (DataSource) ctx.lookup(CONNECT_STRING);


conn = datasource.getConnection();

9:

} catch (SQLException e) {

10:
11:

// catch 

12:

} catch (NamingException e) {
// catch 

13:

14:

return conn;

15:
16:

+ ":" + id + ":" + password;

try (catch)
. 
.



- Android-JAVA
1:

2:

private Connection conn;

3:
4:

public Connection DBConnect(String url, String id,

String password) {

try {

5:
6:

String CONNECT_STRING = url + ":" + id + ":" + password;

7:

InitialContext ctx = new InitialContext();

8:

DataSource datasource = (DataSource) ctx.lookup(CONNECT_STRING);


conn = datasource.getConnection();

9:

} catch (SQLException e) {

10:
11:

// Exception catchException.

12:

if ( conn != null ) {
try {

13:

conn.close();

14:

} catch (SQLException e1) {

15:

conn = null;

16:

17:

18:

} catch (NamingException e) {

19:
20:

// Exception catchException.

21:

if ( conn != null ) {
try {

22:

conn.close();

23:

} catch (SQLException e1) {

24:

conn = null;

25:

26:

27:

28:

return conn;

29:
30:

(catch), (Exception).

. 
[1] CWE-390  - http://cwe.mitre.org/data/definitions/390.html
[2] OWASP Top Ten 2004 Category A7 - Improper Error Handling



6 
, , , , , 

     .    ,
,        , 
.

1. (NULL Pointer Dereference)


.
'NULL'
. NULL , 
.

. 
(reference)null

.
- Android-JAVA
1:

2:

public void f(boolean b) {

3:

String cmd = System.getProperty("cmd");

4:

// cmdnull.

5:

cmd = cmd.trim();

6:
7:

System.out.println(cmd);

"cmd" , "cmd"


, cmdnulltrim() .

- Android-JAVA
1:

2:

public void f(boolean b) {

3:

String cmd = System.getProperty("cmd");

4:

// cmdnull.

5:

if (cmd != null) { md = cmd.trim();


System.out.println(cmd);

6:
7:
8:

} else System.out.println("null command");

cmd.

. 
[1] CWE-476 - http://cwe.mitre.org/data/definitions/476.html



7
       ,  

. 
.

1. private -
(Private Array-Typed Field Returned From A Public Method)
.
privatepublic(return), 
.

. 
privatepublic.
, public 
.

.
- Android-JAVA
1:

// private publicreturn

2:

private String[] colors;

3:

public String[] getColors() {

return colors;

colorsprivatepublicgetColors() 
reference. .



- Android-JAVA
1:

private String[] colors;

2:

// private, , public .

3:

public void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);

4:

String[] newColors = getColors();

5:
6:

7:

public String[] getColors() {

8:

String[] ret = null;

9:

if ( this.colors != null ) {
ret = new String[colors.length];

10:

for (int i = 0; i < colors.length; i++) {

11:

return ret;

13:
14:

ret[i] = this.colors[i];

12:

private , private 


.

. 
[1] CWE-495 private -- http://cwe.mitre.org/data/definitions/495.html



2. private -
(Public Data Assigned to Private Array-Typed Field)
.
publicprivate , private
.

. 
publicprivate .

.
- Android-JAVA
1:

2:

// userRoles private, publicsetUserRoles(),


public .

3:

private String[] userRoles;

4:
5:

public void setUserRoles(String[] userRoles) {


this.userRoles = userRoles;

6:
7:

8:

userRoles private, publicsetUserRoles(),


public .

- Android-JAVA
1:

2:

// private member.

3:

private String[] userRoles;

4:
5:

public void setUserRoles(String[] userRoles) {

6:

this.userRoles = new String[userRoles.length];

7:

for (int i = 0; i < userRoles.length; ++i)


this.userRoles[i] = userRoles[i];

8:
9:
10:

reference, ""private private


.

. 
[1] CWE-496 private -- http://cwe.mitre.org/data/definitions/496.html



3. (Information Leak of System Data)


.
, 
.

. 
.

.
- Android-JAVA
1:

2:

public void f() {

3:

try {

4:

catch (IOException e) {

5:

// printf(e.getMessage()).

g();

System.err.printf(e.getMessage());

6:

7:
8:

9:

private void g() throws IOException {

10:

getMessage()
.

- Android-JAVA
1:

2:

public void f() {

3:

try {

4:

catch (IOException e) {

5:

// end user.
}

7:
9:
10:

System.err.println("IOException Occured");

6:
8:

g();

}
private void g() throws IOException {


.

. 
[1] CWE-497 - http://cwe.mitre.org/data/definitions/497.html



2 
1
Advanced Encryption Standard (AES) : 
DES, (NIST)52001
11(FIPS 197).
DES : DES(Data Encryption Standard)
64,
64, 64. (Brute Force)
.
Manifest : , XML
Synchronized : JAVA



2
ACL : Access Control List
AES : Advanced Encryption Standard
CSRF : Cross-Site Request Forgery
CWE : Common Weakness Enumeration
DES : Data Encryption Standard
ESAPI : Enterprise Security API
HTML : Hyper Text Markup Language
HTTPS : Hypertext Transfer Protocol over Secure Socket Layer
JAAS : Java Authentication and Authorization Service
JDBC : Java Database Connectivity
LDAP : Lightweight Directory Access Protocol
MSB : Most Significant Bit
OAEP : Optimal Asymmetric Encryption Padding
OWASP : Open Web Application Security Project
RSA : Ron Rivest, Adi Shamir, Leonard Adleman
SHA : Secure Hash Algorithm
SQL : Structured Query Language
OpenSSL : Open Secure Socket Layer
URL : Uniform Resource Locator
XSS : Cross-Site Scripting
WAS : Web Application Server



SW 

SW 

20116
20116

(http://www.mopas.go.kr)
(Tel: 02-2279-8494)

< >

.

www.mopas.go.kr

02) 2100-3633, 2927

www.kisa.or.kr

02) 405-5118

You might also like