language
stringclasses 10
values | tag
stringclasses 34
values | vulnerability_type
stringlengths 4
68
β | description
stringlengths 7
146
β | vulnerable_code
stringlengths 14
1.96k
| secure_code
stringlengths 18
3.21k
|
---|---|---|---|---|---|
JAVA | 보μκΈ°λ₯ | λΆμ μ ν μ μμλͺ
νμΈ | νλ‘κ·Έλ¨, λΌμ΄λΈλ¬λ¦¬, μ½λμ μ μμλͺ
μ λν μ ν¨μ± κ²μ¦μ΄ μ μ νμ§ μμ 곡격μμ μ
μμ μΈ μ½λκ° μ€ν κ°λ₯ν 보μμ½μ | File f = new File(downloadedFilePath);
JarFile jf = new JarFile(f); | File f = new File(downloadedFilePath);
JarFile jf = new JarFile(f, true);
Enumeration<JarEntry> ens = jf.entries();
while (ens.hasMoreElements()) {
JarEntry en = ens.nextElement();
if (!en.isDirectory()) {
if (en.toString().equals(path)) {
byte[] data = readAll(jar.getInputStream(en), en.getSize());
CodeSigner[] signers = en.getCodeSigners();
...
}
}
}
jf.close(); |
C | 보μκΈ°λ₯ | λΆμ μ ν μΈμ¦μ μ ν¨μ± κ²μ¦ | μΈμ¦μμ λν μ ν¨μ± κ²μ¦μ΄ μ μ νμ§ μμ λ°μνλ 보μμ½μ | if ((cert = SSL_get_peer_certificate(ssl)) && host)
foo=SSL_get_verify_result(ssl);
if ((X509_V_OK==foo) || X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN==foo))
// μ체 μλͺ
λ μΈμ¦μμΌ μ μλ€. | private boolean verifySignature(X509Certificate toVerify, X509Certificate signingCert) {
/* κ²μ¦νλ €λ νΈμ€νΈ μΈμ¦μ(toVerify)μ CAμΈμ¦μ(signing Cert)μ DN(Distinguished
Name)μ΄ μΌμΉνλμ§ μ¬λΆλ₯Ό νμΈνλ€.*/
if (!toVerify.getIssuerDN().equals(signingCert.getSubjectDN())) return false;
try {
// νΈμ€νΈ μΈμ¦μκ° CAμΈμ¦μλ‘ μλͺ
λμλμ§ νμΈνλ€.
toVerify.verify(signingCert.getPublicKey());
// νΈμ€νΈ μΈμ¦μκ° μ ν¨κΈ°κ°μ΄ λ§λ£λμλμ§ νμΈνλ€.
toVerify.checkValidity();
return true;
} catch (GeneralSecurityException verifyFailed) {
return false;
}
} |
C, JAVA | 보μκΈ°λ₯ | λΆμ μ ν μΈμ¦μ μ ν¨μ± κ²μ¦ | μΈμ¦μμ λν μ ν¨μ± κ²μ¦μ΄ μ μ νμ§ μμ λ°μνλ 보μμ½μ | cert = SSL_get_peer_certificate(ssl);
if (cert && (SSL_get_verify_result(ssl)==X509_V_OK)) {
/* CN μ νμΈνμ§ μμμ§λ§ μ λ’°νκ³ μ§ννλ€. μ΄λ΄ κ²½μ°, 곡격μκ° Common Nameμ
www.attack.comμΌλ‘ μ€μ νμ¬ μ€κ°μ 곡격μ μ¬μ©ν κ²½μ° λ°μ΄ν°κ° μ€κ°μμ 볡νΈν λκ³ μμμ
νμ§νμ§ λͺ»νλ€. */
} | private boolean verifySignature(X509Certificate toVerify, X510Certificate signingCert) {
/* κ²μ¦νλ €λ νΈμ€νΈ μΈμ¦μ(toVerify)μ CAμΈμ¦μ(signing Cert)μ DN(Distinguished
Name)μ΄ μΌμΉνλμ§ μ¬λΆλ₯Ό νμΈνλ€.*/
if (!toVerify.getIssuerDN().equals(signingCert.getSubjectDN())) return false;
try {
// νΈμ€νΈ μΈμ¦μκ° CAμΈμ¦μλ‘ μλͺ
λμλμ§ νμΈνλ€.
toVerify.verify(signingCert.getPublicKey());
// νΈμ€νΈ μΈμ¦μκ° μ ν¨κΈ°κ°μ΄ λ§λ£λμλμ§ νμΈνλ€.
toVerify.checkValidity();
return true;
} catch (GeneralSecurityException verifyFailed) {
return false;
}
} |
JAVA | 보μκΈ°λ₯ | μ¬μ©μ νλλμ€ν¬μ μ μ₯λλ μΏ ν€λ₯Ό ν΅ν μ 보λ
ΈμΆ | μΏ ν€(μΈμ
ID, μ¬μ©μ κΆνμ 보 λ± μ€μμ 보)λ₯Ό μ¬μ©μ νλλμ€ν¬μ μ μ₯λμ΄ μ€μμ λ³΄κ° λ
ΈμΆ κ°λ₯ν 보μμ½μ | Cookie loginCookie = new Cookie("rememberme", "YES");
// μΏ ν€μ λ§λ£μκ°μ 1λ
μΌλ‘ κ³Όλνκ² κΈΈκ² μ€μ νκ³ μμ΄ μμ νμ§ μλ€.
loginCookie.setMaxAge(60*60*24*365);
response.addCookie(loginCookie); | Cookie loginCookie = new Cookie("rememberme", "YES");
// μΏ ν€μ λ§λ£μκ°μ ν΄λΉ κΈ°λ₯μ λ§μΆ° μ΅μλ‘ μ¬μ©νλ€.
loginCookie.setMaxAge(60*60*24);
response.addCookie(loginCookie); |
C# | 보μκΈ°λ₯ | μ¬μ©μ νλλμ€ν¬μ μ μ₯λλ μΏ ν€λ₯Ό ν΅ν μ 보λ
ΈμΆ | μΏ ν€(μΈμ
ID, μ¬μ©μ κΆνμ 보 λ± μ€μμ 보)λ₯Ό μ¬μ©μ νλλμ€ν¬μ μ μ₯λμ΄ μ€μμ λ³΄κ° λ
ΈμΆ κ°λ₯ν 보μμ½μ | HttpCookie cookie = Request.Cookies.Get(βExampleCookieβ);
// μΏ ν€μ λ§λ£μκ°μ 1λ
μΌλ‘ κ³Όλνκ² κΈΈκ² μ€μ νκ³ μμ΄ μμ νμ§ μλ€.
cookie.Expires = DateTime.Now.AddMinutes(60.0*24.0*365.0);
Response.Cookies.Add(cookie); | HttpCookie cookie = Request.Cookies.Get(βExampleCookieβ);
// μΏ ν€μ λ§λ£μκ°μ ν΄λΉ κΈ°λ₯μ λ§μΆ° μ΅μλ‘ μ¬μ©νλ€.
cookie.Expires = DateTime.Now.AddMinutes(10d);
Response.Cookies.Add(cookie); |
JAVA | 보μκΈ°λ₯ | μ£Όμλ¬Έ μμ ν¬ν¨λ μμ€ν
μ£Όμμ 보 | μμ€μ½λ μ£Όμλ¬Έμ μΈμ¦μ 보 λ± μμ€ν
μ£Όμμ λ³΄κ° ν¬ν¨λμ΄ μμ€μ½λ λ
ΈμΆ μμ£Όμμ 보λ λ
ΈμΆ κ°λ₯ν 보μμ½μ | // μ£Όμλ¬ΈμΌλ‘ DBμ°κ²° ID, ν¨μ€μλμ μ€μν μ 보λ₯Ό λ
ΈμΆμμΌ μμ νμ§ μλ€.
// DBμ°κ²° root / a1q2w3r3f2!@
con = DriverManager.getConnection(URL, USER, PASS); | // ID, ν¨μ€μλλ±μ μ€μ μ 보λ μ£Όμμ ν¬ν¨ν΄μλ μλλ€.
con = DriverManager.getConnection(URL, USER, PASS); |
C# | 보μκΈ°λ₯ | μ£Όμλ¬Έ μμ ν¬ν¨λ μμ€ν
μ£Όμμ 보 | μμ€μ½λ μ£Όμλ¬Έμ μΈμ¦μ 보 λ± μμ€ν
μ£Όμμ λ³΄κ° ν¬ν¨λμ΄ μμ€μ½λ λ
ΈμΆ μμ£Όμμ 보λ λ
ΈμΆ κ°λ₯ν 보μμ½μ | // μ£Όμλ¬ΈμΌλ‘ DBμ°κ²° ID, ν¨μ€μλμ μ€μν μ 보λ₯Ό λ
ΈμΆμμΌ μμ νμ§ μλ€.
// DBμ°κ²° root / a1q2w3r3f2!@
conn = customGetConnection(USER, PASS); | // ID, ν¨μ€μλλ±μ μ€μ μ 보λ μ£Όμμ ν¬ν¨ν΄μλ μλλ€.
conn = customGetConnection(USER, PASS); |
C | 보μκΈ°λ₯ | μ£Όμλ¬Έ μμ ν¬ν¨λ μμ€ν
μ£Όμμ 보 | μμ€μ½λ μ£Όμλ¬Έμ μΈμ¦μ 보 λ± μμ€ν
μ£Όμμ λ³΄κ° ν¬ν¨λμ΄ μμ€μ½λ λ
ΈμΆ μμ£Όμμ 보λ λ
ΈμΆ κ°λ₯ν 보μμ½μ | /* password is "admin" */
/* passwd is "admin" */
int verfiyAuth(char *ipasswd, char *orgpasswd) {
char *admin = "admin";
if(strncmp(ipasswd, oprgpasswd, sizeof(ipasswd)) != 0) {
printf("Authentication Fail! \n");
}
return admin; | int verfiyAuth(char *ipasswd, char *orgpasswd) {
char *admin = "admin";
if(strncmp(ipasswd, oprgpasswd, sizeof(ipasswd)) != 0) {
printf("Authentication Fail! \n");
}
return admin;
} |
JAVA | 보μκΈ°λ₯ | μνΈ μμ΄ μΌλ°©ν₯ ν΄μ¬ν¨μ μ¬μ© | μνΈλ₯Ό μ¬μ©νμ§ μκ³ μμ±λ ν΄μ¬ κ°μΌλ‘λΆν° 곡격μκ° λ―Έλ¦¬ κ³μ°λ λ μΈλ³΄μ° ν
μ΄λΈμ μ΄μ©νμ¬ ν΄μ¬ μ μ© μ΄μ μλ³Έ μ 보λ₯Ό 볡μκ°λ₯ν 보μμ½μ
* μνΈ: ν΄μ¬ μ μ©νκΈ° μ νλ¬ΈμΈ μ μ‘μ 보μ λ§λΆμΈ 무μλ―Έν λ°μ΄ν° | public String getPasswordHash(String password) throws Exception {
MessageDigest md = MessageDigest.getInstance("SHA-256");
// ν΄μ¬μ μνΈλ₯Ό μ μ©νμ§ μμ μμ νμ§ μλ€.
md.update(password.getBytes());
byte byteData[] = md.digest();
StringBuffer hexString = new StringBuffer();
for (int i=0; i<byteData.length i++) {
String hex=Integer.toHexString(0xff & byteData[i]);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
} | public String getPasswordHash(String password, byte[] salt) throws Exception {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(password.getBytes());
// ν΄μ¬ μ¬μ© μμλ μλ¬Έμ μ°Ύμ μ μλλ‘ μνΈλ₯Ό μ¬μ©νμ¬μΌ νλ€.
md.update(salt);
byte byteData[] = md.digest();
StringBuffer hexString = new StringBuffer();
for (int i=0; i<byteData.length i++) {
String hex=Integer.toHexString(0xff & byteData[i]);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString()
} |
C# | 보μκΈ°λ₯ | μνΈ μμ΄ μΌλ°©ν₯ ν΄μ¬ν¨μ μ¬μ© | μνΈλ₯Ό μ¬μ©νμ§ μκ³ μμ±λ ν΄μ¬ κ°μΌλ‘λΆν° 곡격μκ° λ―Έλ¦¬ κ³μ°λ λ μΈλ³΄μ° ν
μ΄λΈμ μ΄μ©νμ¬ ν΄μ¬ μ μ© μ΄μ μλ³Έ μ 보λ₯Ό 볡μκ°λ₯ν 보μμ½μ
* μνΈ: ν΄μ¬ μ μ©νκΈ° μ νλ¬ΈμΈ μ μ‘μ 보μ λ§λΆμΈ 무μλ―Έν λ°μ΄ν° | static void HashWithoutSalt()
{
// ν΄μ¬μ μνΈλ₯Ό μ μ©νμ§ μμ μμ νμ§ μλ€.
var bytes = new byte[100];
(new Random()).NextBytes(bytes);
var source = bytes;
var sha256 = new SHA256CryptoServiceProvider();
sha256.ComputeHash(source);
} | static void HashWithSalt(int saltLength)
{
// ν΄μ¬μ μνΈλ₯Ό μ μ©νμ¬ μλ¬Έμ μ°Ύμ μ μκ² νλ€.
var bytes = new byte[100];
(new Random()).NextBytes(bytes);
var source = bytes;
var sha256 = new SHA256CryptoServiceProvider();
byte[] saltBytes = GenerateRandomCryptographicBytes(saltLength);
List<byte> sourceWithSaltBytes = new List<byte>();
sourceWithSaltBytes.AddRange(source);
sourceWithSaltBytes.AddRange(sourceWithSaltBytes);
sha256.ComputeHash(sourceWithSaltBytes.ToArray());
} |
C | 보μκΈ°λ₯ | μνΈ μμ΄ μΌλ°©ν₯ ν΄μ¬ν¨μ μ¬μ© | μνΈλ₯Ό μ¬μ©νμ§ μκ³ μμ±λ ν΄μ¬ κ°μΌλ‘λΆν° 곡격μκ° λ―Έλ¦¬ κ³μ°λ λ μΈλ³΄μ° ν
μ΄λΈμ μ΄μ©νμ¬ ν΄μ¬ μ μ© μ΄μ μλ³Έ μ 보λ₯Ό 볡μκ°λ₯ν 보μμ½μ
* μνΈ: ν΄μ¬ μ μ©νκΈ° μ νλ¬ΈμΈ μ μ‘μ 보μ λ§λΆμΈ 무μλ―Έν λ°μ΄ν° | void GenerateHash(char* data)
{
char[512] hashedData = {0 };
//μνΈ κ° λΆλΆμ΄ NULL λ‘ λμ΄μμ΄ λ€μ΄κ°μ§ μλλ€.
MD5HashAlgorithm( data, hashedData, NULL );
...
} | void GenerateHash(char* data, char* salt)
{
char hashedData[512] = {0 };
MD5HashAlgorithm( data, hashedData, salt );
...
} |
JAVA | 보μκΈ°λ₯ | λ¬΄κ²°μ± κ²μ¬ μλ μ½λ λ€μ΄λ‘λ | μμ€μ½λ λλ μ€ννμΌμ λ¬΄κ²°μ± κ²μ¬ μμ΄ λ€μ΄λ‘λ λ°μ μ€ννλ κ²½μ°, 곡격μμ μ
μμ μΈ μ½λκ° μ€ν κ°λ₯ν 보μμ½μ | URL[] classURLs = new URL[] { new URL("file:subdir/") };
URLClassLoader loader = new URLClassLoader(classURLs);
Class loadedClass = Class.forName("LoadMe", true, loader); | // 곡κ°ν€ λ°©μμ μνΈν μκ³ λ¦¬μ¦κ³Ό λ©μ»€λμ¦μ μ΄μ©νμ¬ μ μ‘νμΌμ λν μκ·Έλμ²λ₯Ό μμ±νκ³
νμΌμ λ³μ‘°μ 무λ₯Ό νλ¨νλ€. μλ²μμλ Private Keyλ₯Ό κ°μ§κ³ MyClassλ₯Ό μνΈννλ€.
String jarFile = "./download/util.jar";
byte[] loadFile = FileManager.getBytes(jarFile);
loadFile = encrypt(loadFile, privateKey);
// jarFileNameμΌλ‘ μνΈνλ νμΌμ μμ±νλ€.
FileManager.createFile(loadFile, jarFileName);
// ν΄λΌμ΄μΈνΈμμλ νμΌμ λ€μ΄λ‘λ λ°μ κ²½μ° Public Keyλ‘ λ³΅νΈννλ€.
URL[] classURLs = new URL[] { new URL("http://filesave.com/download/util.jar") };
URLConnection conn = classURLs.openConnection();
InputStream is = conn.getInputStream();
// μ
λ ₯ μ€νΈλ¦Όμ jarFileλͺ
μΌλ‘ νμΌμ μΆλ ₯νλ€.
FileOutputStream fos = new FileOutputStream(new File(jarFile));
While (is.read(buf) != -1) {
......
}
byte[] loadFile = FileManager.getBytes(jarFile);
loadFile = decrypt(loadFile, publicKey);
// 볡νΈνλ νμΌμ μμ±νλ€.
FileManager.createFile(loadFile, jarFile);
URLClassLoader loader = new URLClassLoader(classURLs);
Class loadedClass = Class.forName("MyClass", true, loader); |
C# | 보μκΈ°λ₯ | λ¬΄κ²°μ± κ²μ¬ μλ μ½λ λ€μ΄λ‘λ | μμ€μ½λ λλ μ€ννμΌμ λ¬΄κ²°μ± κ²μ¬ μμ΄ λ€μ΄λ‘λ λ°μ μ€ννλ κ²½μ°, 곡격μμ μ
μμ μΈ μ½λκ° μ€ν κ°λ₯ν 보μμ½μ | public override bool DownloadFile()
{
var url = "https://www.somewhere.untrusted.com";
var desDir = "D:/DestinationPath";
string fileName = Path.GetFileName(url);
string descFilePath = Path.Combine(desDir, fileName);
try
{
WebRequest myre = WebRequest.Create(url);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
try
{
byte[] fileData;
// νμΌ λ¬΄κ²°μ± κ²μ¬ μμ΄ λ€μ΄λ‘λ
using (WebClient client = new WebClient())
{
fileData = client.DownloadData(url);
}
using (FileStream fs = new FileStream(descFilePath, FileMode.OpenOrCreate))
{
fs.Write(fileData, 0, fileData.Length);
}
return true;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
} | public override bool DownloadFile()
{
var url = "https://www.somewhere.untrusted.com";
var desDir = "D:/DestinationPath";
string fileName = Path.GetFileName(url);
string descFilePath = Path.Combine(desDir, fileName);
try
{
WebRequest myre = WebRequest.Create(url);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
try
{
byte[] fileData;
using (WebClient client = new WebClient())
{
fileData = client.DownloadData(url);
}
// ν΄μ¬ κ° λ±μ μ¬μ©νμ¬ λ€μ΄λ‘λ λ°μ νμΌ λ¬΄κ²°μ± κ²μ¬
CheckIntegrity(fileData);
using (FileStream fs = new FileStream(descFilePath,
FileMode.OpenOrCreate))
{
fs.Write(fileData, 0, fileData.Length);
}
return true;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
} |
C | 보μκΈ°λ₯ | λ¬΄κ²°μ± κ²μ¬ μλ μ½λ λ€μ΄λ‘λ | μμ€μ½λ λλ μ€ννμΌμ λ¬΄κ²°μ± κ²μ¬ μμ΄ λ€μ΄λ‘λ λ°μ μ€ννλ κ²½μ°, 곡격μμ μ
μμ μΈ μ½λκ° μ€ν κ°λ₯ν 보μμ½μ | void foo() {
/* ... */
hFile = CreateFile((LPCWSTR)data,GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
InternetQueryDataAvailable(m_hURL, &dwSize,0,0);
InternetReadFile(m_hURL, lpBuffer, dwSize, &dwRead);
WriteFile(hFile, lpBuffer, dwRead, &dwWritten, NULL);
/* ... */ | void foo() {
/* ... */
hFile = CreateFile((LPCWSTR)data,GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);
InternetQueryDataAvailable(m_hURL, &dwSize,0,0);
bool result = InternetReadFile(m_hURL, lpBuffer, dwSize, &dwRead);
if, lp( result == true) {
WriteFile(hFileBuffer, dwRead, &dwWritten, NULL);
}
/* ... */
} |
JAVA | 보μκΈ°λ₯ | λ°λ³΅λ μΈμ¦μλ μ ν κΈ°λ₯ λΆμ¬ | μΈμ¦ μλ μλ₯Ό μ ννμ§ μμ 곡격μκ° λ°λ³΅μ μΌλ‘ μμ κ°μ μ
λ ₯νμ¬ κ³μ κΆνμ νλ κ°λ₯ν 보μμ½μ | private static final String SERVER_IP = "127.0.0.1";
private static final int SERVER_PORT = 8080;
private static final int FAIL = -1;
public void login() {
String username = null;
String password = null;
Socket socket = null;
int result = FAIL;
try {
socket = new Socket(SERVER_IP, SERVER_PORT);
//μΈμ¦ μ€ν¨μ λν΄ μ νμ λμ§ μμ μμ νμ§ μλ€.
while (result == FAIL) {
...
result = verifyUser(username, password);
} | private static final String SERVER_IP = "127.0.0.1";
private static final int SERVER_PORT = 8080;
private static final int FAIL = -1;
private static final int MAX_ATTEMPTS = 5;
public void login() {
String username = null;
String password = null;
Socket socket = null;
int result = FAIL;
int count = 0;
try {
socket = new Socket(SERVER_IP, SERVER_PORT);
// μΈμ¦ μ€ν¨ λ° μλ νμμ μ νμ λμ΄ μμ νλ€.
while (result == FAIL && count < MAX_ATTEMPTS) {
...
result = verifyUser(username, password);
count++;
} |
C | 보μκΈ°λ₯ | λ°λ³΅λ μΈμ¦μλ μ ν κΈ°λ₯ λΆμ¬ | μΈμ¦ μλ μλ₯Ό μ ννμ§ μμ 곡격μκ° λ°λ³΅μ μΌλ‘ μμ κ°μ μ
λ ₯νμ¬ κ³μ κΆνμ νλ κ°λ₯ν 보μμ½μ | int validateUser(char *host, int port) {
int socket = openSocketConnection(host, port);
if (socket < 0) {
printf("Unable to open socket connection");
return(FAIL);
}
int isValidUser = 0;
char nm[NAME_SIZE];
char pw[PSWD_SIZE];
// μΈμ¦μλ νμλ₯Ό μ ννκ³ μμ§ μλ€.
while (isValidUser==0) {
if (getNextMsg(socket, nm, NAME_SIZE) > 0) {
if (getNextMsg(socket, pw, PSWD_SIZE) > 0) {
isValidUser = AuthenticateUser(nm, pw);
}
}
}
return(SUCCESS);
} | #define MAX_ATTEMPTS 5
int validateUser(char *host, int port) {
......
// μ°μμ μΈ μ¬μ©μ μΈμ¦ μλμ λν νμλ₯Ό μ ν
int count = 0;
while ((isValidUser==0) && (count<MAX_ATTEMPTS)) {
if (getNextMsg(socket, nm, NAME_SIZE) > 0) {
if (getNextMsg(socket, pw, PSWD_SIZE) > 0) {
isValidUser = AuthenticateUser(nm, pw);
}
}
count++;
}
if (isValidUser) {
return(SUCCESS);
} else {
return(FAIL);
}
} |
C# | 보μκΈ°λ₯ | λ°λ³΅λ μΈμ¦μλ μ ν κΈ°λ₯ λΆμ¬ | μΈμ¦ μλ μλ₯Ό μ ννμ§ μμ 곡격μκ° λ°λ³΅μ μΌλ‘ μμ κ°μ μ
λ ₯νμ¬ κ³μ κΆνμ νλ κ°λ₯ν 보μμ½μ | // λ‘κ·ΈμΈ μ€ν¨ μ μλ¬΄λ° μ μ½μ΄ μμ
override protected void OnLoginError(EventArgs e)
{
//do nothing
} | override protected void OnLoginError(EventArgs e)
{
// μ°μμ μΈ μ¬μ©μ μΈμ¦ μλμ λν νμλ₯Ό μ ν
if(ViewState["LoginErrors"] == null)
ViewState["LoginErrors"] = 0;
int ErrorCount = (int)ViewState["LoginErrors"] + 1;
ViewState["LoginErrors"] = ErrorCount;
if((ErrorCount > 3) && Login1.PasswordRecoveryUrl !=
string.Empty)
Response.Redirect(Login1.PasswordRecoveryUrl);
} |
JAVA | μκ° λ° μν | κ²½μ쑰건: κ²μ¬μμ κ³Ό μ¬μ©μμ (TOCTOU) | λ©ν° νλ‘μΈμ€ μμμ μμμ κ²μ¬νλ μμ κ³Ό μ¬μ©νλ μμ μ΄ λ¬λΌμ λ°μνλ 보μμ½μ | class FileMgmtThread extends Thread {
private String manageType = "";
public FileMgmtThread (String type) {
manageType = type;
}
// λ©ν°μ°λ λ νκ²½μμ 곡μ μμμ μ¬λ¬νλ‘μΈμ€κ° μ¬μ©νμ¬ λμμ μ κ·Όν κ°λ₯μ±μ΄ μμ΄ μμ
νμ§ μλ€.
public void run() {
try {
if (manageType.equals("READ")) {
File f = new File("Test_367.txt");
if (f.exists()) {
BufferedReader br
= new BufferedReader(new FileReader(f));
br.close();
}
} else if (manageType.equals("DELETE")) {
File f = new File("Test_367.txt");
if (f.exists()) {
f.delete();
} else { β¦ }
}
} catch (IOException e) { β¦ }
}
}
public class CWE367 {
public static void main (String[] args) {
FileMgmtThread fileAccessThread = new FileMgmtThread("READ");
FileMgmtThread fileDeleteThread = new FileMgmtThread("DELETE");
// νμΌμ μ½κΈ°μ μμ κ° λμμ μνλμ΄ μμ νμ§ μλ€.
fileAccessThread.start();
fileDeleteThread.start();
}
} | class FileMgmtThread extends Thread {
private static final String SYNC = "SYNC";
private String manageType = "";
public FileMgmtThread (String type) {
manageType = type;
}
public void run() {
// λ©ν°μ°λ λ νκ²½μμ synchronizedλ₯Ό μ¬μ©νμ¬ λμμ μ κ·Όν μ μλλ‘ μ¬μ©ν΄μΌνλ€.
synchronized(SYNC) {
try {
if (manageType.equals("READ")) {
File f = new File("Test_367.txt");
if (f.exists()) {
BufferedReader br
= new BufferedReader(new FileReader(f));
br.close();
}
} else if (manageType.equals("DELETE")) {
File f = new File("Test_367.txt");
if (f.exists()) {
f.delete();
} else { β¦ }
}
} catch (IOException e) { β¦ }
}
}
}
public class CWE367 {
public static void main (String[] args) {
FileMgmtThread fileAccessThread = new FileMgmtThread("READ");
FileMgmtThread fileDeleteThread = new FileMgmtThread("DELETE");
fileAccessThread.start();
fileDeleteThread.start();
}
} |
C# | μκ° λ° μν | κ²½μ쑰건: κ²μ¬μμ κ³Ό μ¬μ©μμ (TOCTOU) | λ©ν° νλ‘μΈμ€ μμμ μμμ κ²μ¬νλ μμ κ³Ό μ¬μ©νλ μμ μ΄ λ¬λΌμ λ°μνλ 보μμ½μ | // λ©ν°μ°λ λ νκ²½μμ λμμ μ κ·Όν μ μλλ‘ μ¬μ©ν΄μΌνλ€.
public void ReadFile(String f)
{
if(File.Exists(f))
{
File.ReadAllLines(f);
}
} | // λ©ν°μ°λ λ νκ²½μμ λμμ μ κ·Όν μ μλλ‘ μ¬μ©ν΄μΌνλ€.
[MethodImpl(MethodImplOptions.Synchronized)]
public void ReadFile(String f)
{
if(File.Exists(f))
{
File.ReadAllLines(f);
}
} |
C | μκ° λ° μν | κ²½μ쑰건: κ²μ¬μμ κ³Ό μ¬μ©μμ (TOCTOU) | λ©ν° νλ‘μΈμ€ μμμ μμμ κ²μ¬νλ μμ κ³Ό μ¬μ©νλ μμ μ΄ λ¬λΌμ λ°μνλ 보μμ½μ | static volatile double account;
void deposit(int amount) {
// lock μμ΄ κ³΅μ μμμ μ κ·Ό
account += amount;
}
void withdraw(int amount) {
account -= amount;
} | static volatile double account;
static mtx_t account_lock;
void deposit(int amount) {
// mutex_lock, mutex_unlockμ μ΄μ©ν΄ 곡μ μμ μ κ·Όμ μ ννλ€.
mutex_lock(&account_lock);
account += amount;
mutex_unlock(&account_lock);
}
void withdraw(int amount) {
mutex_lock(&account_lock);
account -= amount;
mutex_unlock(&account_lock);
} |
C | μκ° λ° μν | μ’
λ£λμ§ μλ λ°λ³΅λ¬Έ λλ μ¬κ·ν¨μ | μ’
λ£μ‘°κ±΄ μλ μ μ΄λ¬Έ μ¬μ©μΌλ‘ λ°λ³΅λ¬Έ λλ μ¬κ·ν¨μκ° λ¬΄νν λ°λ³΅λμ΄ λ°μν μ μλ 보μμ½μ | #include <stdio.h>
int factorial(int i)
{
// μ¬κ·ν¨μ νμΆ μ‘°κ±΄μ μ€μ νμ§ μμ 무ν루νκ° λλ€.
return i * factorial(i - 1);
}
int main()
{
int num = 5;
int result = factorial(num);
printf("%d! : %d\n", num, result);
return 0;
} | #include <stdio.h>
int factorial(int I)
{
// μ¬κ·ν¨μ μ¬μ© μμλ μλμ κ°μ΄ νμΆ μ‘°κ±΄μ μ¬μ©ν΄μΌ νλ€.
if (i <= 1) {
return 1;
}
return i * factorial(i β 1);
}
int main()
{
int num = 5;
int result = factorial(num);
printf("%d! : %d\n", num, result);
return 0;
} |
JAVA | μλ¬μ²λ¦¬ | μ€λ₯ λ©μμ§ μ 보λ
ΈμΆ | μ€λ₯λ©μμ§λ μ€νμ 보μ μμ€ν
λ΄λΆκ΅¬μ‘°κ° ν¬ν¨λμ΄ λ―Όκ°ν μ 보, λλ²κΉ
μ λ³΄κ° λ
ΈμΆ κ°λ₯ν 보μμ½μ | try {
rd = new BufferedReader(new FileReader(new File(filename)));
} catch(IOException e) {
// μλ¬ λ©μμ§λ‘ μ€ν μ λ³΄κ° λ
ΈμΆλ¨
e.printStackTrace();
} | try {
rd = new BufferedReader(new FileReader(new File(filename)));
} catch(IOException e) {
// μλ¬ μ½λμ μ 보λ₯Ό λ³λλ‘ μ μνκ³ μ΅μ μ λ³΄λ§ λ‘κΉ
logger.error("ERROR-01: νμΌ μ΄κΈ° μλ¬");
} |
JAVA | μλ¬μ²λ¦¬ | μ€λ₯ λ©μμ§ μ 보λ
ΈμΆ | μ€λ₯λ©μμ§λ μ€νμ 보μ μμ€ν
λ΄λΆκ΅¬μ‘°κ° ν¬ν¨λμ΄ λ―Όκ°ν μ 보, λλ²κΉ
μ λ³΄κ° λ
ΈμΆ κ°λ₯ν 보μμ½μ | catch(IOException e) {
// μ€λ₯λ°μμ νλ©΄μ μΆλ ₯λ μμ€ν
μ λ³΄λ‘ λ€λ₯Έ 곡격μ λΉλ―Έλ₯Ό μ 곡νλ€.
System.err.print(e.getMessage());
} | try {
rd = new BufferedReader(new FileReader(new File(filename)));
} catch(IOException e) {
// μλ¬ μ½λμ μ 보λ₯Ό λ³λλ‘ μ μνκ³ μ΅μ μ λ³΄λ§ λ‘κΉ
logger.error("ERROR-01: νμΌ μ΄κΈ° μλ¬");
} |
C# | μλ¬μ²λ¦¬ | μ€λ₯ λ©μμ§ μ 보λ
ΈμΆ | μ€λ₯λ©μμ§λ μ€νμ 보μ μμ€ν
λ΄λΆκ΅¬μ‘°κ° ν¬ν¨λμ΄ λ―Όκ°ν μ 보, λλ²κΉ
μ λ³΄κ° λ
ΈμΆ κ°λ₯ν 보μμ½μ | try
{
//do something
}
catch (CustomException e)
{
Console.WriteLine(e);
} | try
{
//do something
}
catch (CustomException e)
{
_log.Debug(βERROR-01 : error informationβ);
} |
JAVA | μλ¬μ²λ¦¬ | μ€λ₯ μν© λμ λΆμ¬ | μμ€ν
μ€λ₯μν©μ μ²λ¦¬νμ§ μμ νλ‘κ·Έλ¨ μ€νμ μ§ λ± μλνμ§ μμ μν©μ΄ λ°μ κ°λ₯ν 보μμ½μ | protected Element createContent(WebSession s) {
β¦β¦
try {
username = s.getParser().getRawParameter(USERNAME);
password = s.getParser().getRawParameter(PASSWORD);
if (!"webgoat".equals(username) || !password.equals("webgoat")) {
s.setMessage("Invalid username and password entered.");
return (makeLogin(s));
}
} catch (NullPointerException e) {
// μμ² νλΌλ―Έν°μ PASSWORDκ° μ‘΄μ¬νμ§ μμ κ²½μ° Null Pointer Exceptionμ΄ λ°μνκ³
ν΄λΉ μ€λ₯μ λν λμμ΄ μ‘΄μ¬νμ§ μμ μΈμ¦μ΄ λ κ²μΌλ‘ μ²λ¦¬
} | protected Element createContent(WebSession s) {
β¦β¦
try {
username = s.getParser().getRawParameter(USERNAME);
password = s.getParser().getRawParameter(PASSWORD);
if (!"webgoat".equals(username) || !password.equals("webgoat")) {
s.setMessage("Invalid username and password entered.");
return (makeLogin(s));
}
} catch (NullPointerException e) {
// μμΈ μ¬νμ λν΄ μ μ ν μ‘°μΉλ₯Ό μννμ¬μΌ νλ€.
s.setMessage(e.getMessage());
return (makeLogin(s));
} |
C# | μλ¬μ²λ¦¬ | μ€λ₯ μν© λμ λΆμ¬ | μμ€ν
μ€λ₯μν©μ μ²λ¦¬νμ§ μμ νλ‘κ·Έλ¨ μ€νμ μ§ λ± μλνμ§ μμ μν©μ΄ λ°μ κ°λ₯ν 보μμ½μ | try {
InvokeMtd();
} catch (CustomException e) {
// μμΈ μν©μ λν λμ λΆμ¬
} | try {
InvokeMtd();
} catch (CustomException e) {
// μμΈ μν©μ λν΄ μ μ ν μ‘°μΉλ₯Ό μννμ¬μΌ νλ€.
logger.Debug(βlog messageβ);
} |
JAVA | μλ¬μ²λ¦¬ | λΆμ μ ν μμΈ μ²λ¦¬ | μμΈμ¬νμ λΆμ μ νκ² μ²λ¦¬νμ¬ μλνμ§ μμ μν©μ΄ λ°μ κ°λ₯ν 보μμ½μ | try {
...
reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line = reader.readLine();
SimpleDateFormat format = new SimpleDateFormat("MM/DD/YY");
Date date = format.parse(line);
// μμΈμ²λ¦¬λ₯Ό μΈλΆν ν μ μμμλ κ΄λ²μνκ² μ¬μ©νμ¬ μκΈ°μΉ μμ λ¬Έμ κ° λ°μ ν μ μλ€.
} catch (Exception e) {
System.err.println("Exception : " + e.getMessage());
} | try {
...
reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line = reader.readLine();
SimpleDateFormat format = new SimpleDateFormat("MM/DD/YY");
Date date = format.parse(line);
// λ°μν μ μλ μ€λ₯μ μ’
λ₯μ μμμ λ§μΆ°μ μμΈμ²λ¦¬ νλ€.
} catch (MalformedURLException e) {
System.err.println("MalformedURLException : " + e.getMessage());
} catch (IOException e) {
System.err.println("IOException : " + e.getMessage());
} catch (ParseException e) {
System.err.println("ParseException : " + e.getMessage());
} |
C# | μλ¬μ²λ¦¬ | λΆμ μ ν μμΈ μ²λ¦¬ | μμΈμ¬νμ λΆμ μ νκ² μ²λ¦¬νμ¬ μλνμ§ μμ μν©μ΄ λ°μ κ°λ₯ν 보μμ½μ | try {
InvokeMtd();
// μμΈμ²λ¦¬λ₯Ό μΈλΆνν μ μμμλ κ΄λ²μνκ² μ¬μ©νμ¬ μκΈ°μΉ μμ λ¬Έμ κ° λ°μν μ μλ€.
} catch (Exception e) {
} | try {
InvokeMtd();
// λ°μν μ μλ μ€λ₯μ μ’
λ₯μ μμμ λ§μΆ°μ μμΈμ²λ¦¬ νλ€.
} catch (IOException e) {
logger.Debug(βIOException log hereβ);
} catch (SQLException e){
logger.Debug(βSQLException log hereβ);
} |
JAVA | μ½λμ€λ₯ | Null Pointer μμ°Έμ‘° | λ³μμ μ£Όμ κ°μ΄ NullμΈ κ°μ²΄λ₯Ό μ°Έμ‘°νλ 보μμ½μ | public static int cardinality (Object obj, final Collection col) {
int count = 0;
if (col == null) {
return count;
}
Iterator it = col.iterator();
while (it.hasNext()) {
Object elt = it.next();
// objκ° nullμ΄κ³ eltκ° nullμ΄ μλ κ²½μ°, Null.equals κ° λμ΄ λ(Null) ν¬μΈν° μμ°Έμ‘°κ° λ°μνλ€.
if ((null == obj && null == elt) || obj.equals(elt)) {
count++;
}
}
return count;
} | public static int cardinality (Object obj, final Collection col) {
int count = 0;
if (col == null) {
return count;
}
Iterator it = col.iterator();
while (it.hasNext()) {
Object elt = it.next();
// objλ₯Ό μ°Έμ‘°νλ equalsκ° nullμ΄
if ((null == obj && null == elt) || (null != obj && obj.equals(elt))) {
count++;
}
}
return count;
} |
JAVA | μ½λμ€λ₯ | Null Pointer μμ°Έμ‘° | λ³μμ μ£Όμ κ°μ΄ NullμΈ κ°μ²΄λ₯Ό μ°Έμ‘°νλ 보μμ½μ | String url = reuqest.getParamter("url");
// url μ nullμ΄ λ€μ΄μ€λ©΄ λ(Null) ν¬μΈν° μμ°Έμ‘°κ° λ°μνλ€.
if ( url.equals("") ) | String url = reuqest.getParamter("url");
// nullκ°μ κ°μ§λ μ°Έμ‘° λ³μλ₯Ό μ¬μ©ν κ²½μ°, null κ²μ¬λ₯Ό μννκ³ μ¬μ©νλ€.
if ( url != null || url.equals("") ) |
C# | μ½λμ€λ₯ | Null Pointer μμ°Έμ‘° | λ³μμ μ£Όμ κ°μ΄ NullμΈ κ°μ²΄λ₯Ό μ°Έμ‘°νλ 보μμ½μ | protected void Page_Load(object sender, EventArgs e) {
// url νλΌλ―Έν°μ name μ΄ μμΌλ©΄ usernameμ null κ°μ κ°μ§κ² λλ€.
string username = Request.QueryString[βnameβ];
// null κ°μ κ°μ§λ usernameμ μ°Έμ‘°νμ¬ λ(Null) ν¬μΈν° μμ°Έμ‘°κ° λ°μνλ€.
if (username.Length > 20) {
// length error
}
} | protected void Page_Load(object sender, EventArgs e) {
// url νλΌλ―Έν°μ name μ΄ μμΌλ©΄ usernameμ null κ°μ κ°μ§κ² λλ€.
string username = Request.QueryString[βnameβ];
// null κ°μ κ°μ§λ usernameμ μ°Έμ‘°νκΈ° μ μ null κ²μ¬λ₯Ό μννλ―λ‘ μμ νλ€.
if ( username != null && username > 20) {
// length error
}
} |
C | μ½λμ€λ₯ | Null Pointer μμ°Έμ‘° | λ³μμ μ£Όμ κ°μ΄ NullμΈ κ°μ²΄λ₯Ό μ°Έμ‘°νλ 보μμ½μ | void NullPointerDereference(int count) {
// IntegerAddressReturn()μ΄ 0μ return νλ©΄ pλ null κ°μ κ°μ§κ² λλ€.
int *p = IntegerAddressReturn();
// null κ°μ κ°μ§λ p κ°μ μ°Έμ‘°νμ¬ λ(Null) ν¬μΈν° μμ°Έμ‘°κ° λ°μνλ€.
*p = count;
} | void NullPointerDereference(int count) {
// IntegerAddressReturn()μ΄ 0μ return νλ©΄ pλ null κ°μ κ°μ§κ² λλ€.
int *p = IntegerAddressReturn();
// μ°Έμ‘°νκΈ°μ μ null κ²μ¬λ₯Ό μννλ―λ‘ μμ νλ€.
If(p != 0) *p = count; |
JAVA | μ½λμ€λ₯ | λΆμ μ ν μμ ν΄μ | μ¬μ© μλ£λ μμμ ν΄μ νμ§ μμ μμμ΄ κ³ κ°λμ΄ μλ‘μ΄ μ
λ ₯μ μ²λ¦¬ν μ μλ 보μμ½μ | InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(inputFile);
out = new FileOutputStream(outputFile);
...
FileCopyUtils.copy(fis, os);
// μμλ°ν μ€ν μ μ μ€λ₯κ° λ°μν κ²½μ° μμμ΄ λ°νλμ§ μμΌλ©°, ν λΉλ λͺ¨λ μμμ λ°νν΄μΌ
νλ€.
in.close();
out.close();
} catch (IOException e) {
logger.error(e);
} | InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(inputFile);
out = new FileOutputStream(outputFile);
...
FileCopyUtils.copy(fis, os);
} catch (IOException e) {
logger.error(e);
// νμ μνλλ finally λΈλ‘μμ ν λΉλ°μ λͺ¨λ μμμ λν΄ κ°κ° nullκ²μ¬λ₯Ό μν ν μμΈμ²λ¦¬λ₯Ό
νμ¬ μμμ ν΄μ νμ¬μΌ νλ€.
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
logger.error(e);
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
logger.error(e);
}
}
} |
C# | μ½λμ€λ₯ | λΆμ μ ν μμ ν΄μ | μ¬μ© μλ£λ μμμ ν΄μ νμ§ μμ μμμ΄ κ³ κ°λμ΄ μλ‘μ΄ μ
λ ₯μ μ²λ¦¬ν μ μλ 보μμ½μ | public void FileStreamTest()
{
// fsSourceμ μμμ΄ ν λΉλμμΌλ ν΄μ λμ§ μλλ€.
FileStream fsSource = new FileStream(pathSource, FileMode.Open, FileAccess.Read);
byte[] bytes = new byte[fsSource.Length];
int numBytesToRead = (int)fsSource.Length;
int numBytesRead = 0;
while(numBytesToRead > 0)
{
int n = fsSource.Read(bytes, numBytesRead, numBytesToRead);
if(n==0)
break;
numBytesToRead += n;
numBytesToRead -= n;
}
using(FileStream fsNew = new FileStream(pathNew, FileMode.Create, FileAccess.Write))
{ /* OK */
fsNew.Write(bytes, 0, numBytesToRead);
}
} | public void FileStreamTest()
{
// using ꡬ문μΌλ‘ μμμ ν λΉνλ©΄ κ΅¬λ¬Έμ΄ λλλ μ§μ μμ μλμΌλ‘ μμμ΄ ν΄μ λλ€.
using(FileStream fsSource = new FileStream(pathSource, FileMode.Open,
FileAccess.Read)){
byte[] bytes = new byte[fsSource.Length];
int numBytesToRead = (int)fsSource.Length;
int numBytesRead = 0;
while(numBytesToRead > 0)
{
int n = fsSource.Read(bytes, numBytesRead, numBytesToRead);
if(n==0)
break;
numBytesToRead += n;
numBytesToRead -= n;
}
}
using(FileStream fsNew = new FileStream(pathNew, FileMode.Create,
FileAccess.Write)) { /* OK */
fsNew.Write(bytes, 0, numBytesToRead);
}
} |
C | μ½λμ€λ₯ | λΆμ μ ν μμ ν΄μ | μ¬μ© μλ£λ μμμ ν΄μ νμ§ μμ μμμ΄ κ³ κ°λμ΄ μλ‘μ΄ μ
λ ₯μ μ²λ¦¬ν μ μλ 보μμ½μ | void ImproperResourceRelease(char* filename) {
char buf[BUF_SIZE];
FILE *f = fopen(filename, βrβ);
if(!checkSomething()) {
printf(βSomething is wrongβ);
return;
}
// checkSomethingμμ falseλ₯Ό λ°ννλ κ²½μ°, νμΌ νΈλ€λ¬λ₯Ό μ’
λ£ν μ μλ€.
fclose(f);
} | void ImproperResourceRelease(char* filename) {
char buf[BUF_SIZE];
FILE *f = fopen(filename, βrβ);
if(!checkSomething()) {
printf(βSomething is wrongβ);
// checkSomthingμμ falseλ₯Ό λ°νν΄λ νμΌ νΈλ€λ¬λ₯Ό μ’
λ£νλλ‘ μμ
fclose(f);
return;
}
fclose(f);
} |
C | μ½λμ€λ₯ | ν΄μ λ μμ μ¬μ© | λ©λͺ¨λ¦¬ λ± ν΄μ λ μμμ μ°Έμ‘°νμ¬ μκΈ°μΉ μμ μ€λ₯κ° λ°μνλ 보μμ½μ | int main(int argc, const char *argv[]) {
char *temp;
temp = (char *)malloc(BUFFER_SIZE);
β¦β¦
free(temp);
// ν΄μ ν μμμ μ¬μ©νκ³ μμ΄ μλνμ§ μμ κ²°κ³Όκ° λ°μνκ² λλ€.
stmcpy(temp, argv[1], BUFFER_SIZE-1);
} | int main(int argc,const char *argv[]) {
char *temp;
temp = (char *)malloc(BUFFER_SIZE);
β¦β¦
// ν λΉλ μμμ μ΅μ’
μ μΌλ‘ μ¬μ©νκ³ ν΄μ νμ¬μΌ νλ€.
stmcpy(temp,argv[1], BUFFER_SIZE-1);
free(temp);
} |
C | μ½λμ€λ₯ | ν΄μ λ μμ μ¬μ© | λ©λͺ¨λ¦¬ λ± ν΄μ λ μμμ μ°Έμ‘°νμ¬ μκΈ°μΉ μμ μ€λ₯κ° λ°μνλ 보μμ½μ | char *data;
int data_type
if (data_type==val_1) { free(data); }
β¦β¦
// μ΄λ―Έ ν΄μ λ μμμ μ΄μ€ ν΄μ νμ¬ λ¬Έμ κ° λ°μνλ€.
if (data_type==val_2) { free(data); } | char *data;
int data_type
if (data_type==val_1) {
free(data);
// λ©λͺ¨λ¦¬λ₯Ό ν΄μ ν ν νμ ν¬μΈν°μ NULLμ ν λΉνμ¬ μ΄μ€ ν΄μ νλλΌλ 무μλκ² νλ€.
data = NULL;
}
β¦β¦
if (data_type==val_2) {
free(data);
// λ©λͺ¨λ¦¬λ₯Ό ν΄μ ν ν νμ ν¬μΈν°μ NULLμ ν λΉνμ¬ μ΄μ€ ν΄μ νλλΌλ 무μλκ² νλ€.
data = NULL;
} |
C | μ½λμ€λ₯ | μ΄κΈ°νλμ§ μμ λ³μ μ¬μ© | λ³μλ₯Ό μ΄κΈ°ννμ§ μκ³ μ¬μ©νμ¬ μκΈ°μΉ μμ μ€λ₯κ° λ°μνλ 보μμ½μ | // λ³μμ μ΄κΈ°κ°μ μ§μ νμ§ μμ κ²½μ° κ³΅κ²©μ μ¬μ© λ μ μμ΄ μμ νμ§ μλ€.
int x, y;
switch(position) {
case 0: x = base_position; y = base_position beak;
case 1: x = base_position + i; y = base_position - i break;
default: x=1; break;
}
setCursorPosition(x,y); | // λ³μμ μ΄κΈ°κ°μ νμ μ§μ νμ¬μΌ νλ€.
int x=1, y=1;
switch(position) {
case 0: x = base_position; y = base_position beak;
case 1: x = base_position + i; y = base_position - i break;
default: x=1; break;
}
setCursorPosition(x,y); |
JAVA | μ½λμ€λ₯ | μ λ’°ν μ μλ λ°μ΄ν°μ μμ§λ ¬ν | μ
μμ μΈ μ½λκ° μ½μ
Β·μμ λ μ§λ ¬ν λ°μ΄ν°λ₯Ό μ μ ν κ²μ¦ μμ΄ μμ§λ ¬ννμ¬ λ°μνλ 보μμ½μ
* μ§λ ¬ν: κ°μ²΄λ₯Ό μ μ‘ κ°λ₯ν λ°μ΄ν°νμμΌλ‘ λ³ν
* μμ§λ ¬ν: μ§λ ¬νλ λ°μ΄ν°λ₯Ό μλ κ°μ²΄λ‘ 볡μ | public static void main(String[] args) throws
IOException, GeneralSecurityException, ClassNotFoundException {
....
// mapμ μμ§λ ¬ν νλ€.
ObjectInputStream in = new ObjectInputStream(new FileInputStream("data"));
sealedMap = (SealedObject) in.readObject();
in.close();
// κ°μ²΄λ₯Ό μΆμΆνλ€.
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
signedMap = (SignedObject) sealedMap.getObject(cipher);
// μλͺ
κ° κ²μ¦ κ³Όμ μμ λΆμΌμΉ μ μμΈλ₯Ό 리ν΄νκ³ , μΌμΉ μ map κ°μ μ½λλ€.
if (!signedMap.verify(kp.getPublic(), sig)) {
throw new GeneralSecurityException("Map failed verification");
}
map = (SerializableMap<String, Integer>) signedMap.getObject();
} | public static void main(String[] args) throws
IOException, GeneralSecurityException, ClassNotFoundException {
....
// mapμ μμ§λ ¬ν νλ€.
ObjectInputStream in = new ObjectInputStream(new FileInputStream("data"));
sealedMap = (SealedObject) in.readObject();
in.close();
// κ°μ²΄λ₯Ό μΆμΆνλ€.
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
signedMap = (SignedObject) sealedMap.getObject(cipher);
// μλͺ
κ° κ²μ¦ κ³Όμ μμ λΆμΌμΉ μ μμΈλ₯Ό 리ν΄νκ³ , μΌμΉ μ map κ°μ μ½λλ€.
if (!signedMap.verify(kp.getPublic(), sig)) {
throw new GeneralSecurityException("Map failed verification");
}
map = (SerializableMap<String, Integer>) signedMap.getObject();
} |
JAVA | μ½λμ€λ₯ | μ λ’°ν μ μλ λ°μ΄ν°μ μμ§λ ¬ν | μ
μμ μΈ μ½λκ° μ½μ
Β·μμ λ μ§λ ¬ν λ°μ΄ν°λ₯Ό μ μ ν κ²μ¦ μμ΄ μμ§λ ¬ννμ¬ λ°μνλ 보μμ½μ
* μ§λ ¬ν: κ°μ²΄λ₯Ό μ μ‘ κ°λ₯ν λ°μ΄ν°νμμΌλ‘ λ³ν
* μμ§λ ¬ν: μ§λ ¬νλ λ°μ΄ν°λ₯Ό μλ κ°μ²΄λ‘ 볡μ | class DeserializeExample {
public static Object deserialize(byte[] buffer)
throws IOException, ClassNotFoundException {
Object ret = null;
try (ByteArrayInputStream bais = new ByteArrayInputStream(buffer)) {
try (ObjectInputStream ois = new ObjectInputStream(bais)) {
ret = ois.readObject();
}
}
return ret;
}
} | public class WhitelistedObjectInputStream extends ObjectInputStream {
public Set<String> whitelist;
// WhilelistedObjectInputStreamμ μμ±ν λ νμ΄νΈλ¦¬μ€νΈλ₯Ό μ
λ ₯λ°λλ€.
public WhitelistedObjectInputStream(InputStream inputStream, Set<String> wl)
throws IOException {
super(inputStream);
whitelist = wl;
}
@Override
protected Class<?> resolveClass(ObjectStreamClass cls) throws IOException,
ClassNotFoundException {
// ObjectStreamClassμ ν΄λμ€λͺ
μ΄ νμ΄νΈλ¦¬μ€νΈμ μλμ§ νμΈνλ€.
if (!whitelist.contains(cls.getName())) {
throw new InvalidClassException("Unexpected serialized class", cls.getName());
}
return super.resolveClass(cls);
}
}
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public Student upload(@RequestParam("file") MultipartFile multipartFile)
throws ClassNotFoundException, IOException {
Student student = null;
File targetFile = new File("/temp/" + multipartFile.getOriginalFilename());
// μμ§λ ¬ν λμ ν΄λμ€ μ΄λ¦μ νμ΄νΈλ¦¬μ€νΈ μμ±νλ€.
Set<String> whitelist = new HashSet<String>(Arrays.asList(
new String[] {
"Student"
}));
try (InputStream fileStream = multipartFile.getInputStream()) {
try (WhitelistedObjectInputStream ois =
new WhitelistedObjectInputStream(fileStream, whitelist)) {
// νμ΄νΈλ¦¬μ€νΈμ μλ μμ§λ ¬ν λ°μ΄ν°μ κ²½μ° μμΈ λ°μμν¨λ€.
student = (Student) ois.readObject();
}
}
return student;
} |
JAVA | μΊ‘μν | μλͺ»λ μΈμ
μ μν λ°μ΄ν° μ 보λ
ΈμΆ | μλͺ»λ μΈμ
μ μν΄ μΈκ°λμ§ μμ μ¬μ©μμκ² μ€μμ λ³΄κ° λ
ΈμΆ κ°λ₯ν 보μμ½μ | <%@page import="javax.xml.namespace.*"%>
<%@page import="gov.mogaha.ntis.web.frs.gis.cmm.util.*" %>
<%!
// JSPμμ String νλλ€μ΄ λ©€λ² λ³μλ‘ μ μΈλ¨
String username = "/";
String imagePath = commonPath + "img/";
String imagePath_gis = imagePath + "gis/cmm/btn/";
......
%> | <%@page import="javax.xml.namespace.*"%>
<%@page import="gov.mogaha.ntis.web.frs.gis.cmm.util.*" %>
<%
// JSPμμ String νλλ€μ΄ λ‘컬 λ³μλ‘ μ μΈλ¨
String commonPath = "/";
String imagePath = commonPath + "img/";
String imagePath_gis = imagePath + "gis/cmm/btn/";
......
%> |
JAVA | μΊ‘μν | μλͺ»λ μΈμ
μ μν λ°μ΄ν° μ 보λ
ΈμΆ | μλͺ»λ μΈμ
μ μν΄ μΈκ°λμ§ μμ μ¬μ©μμκ² μ€μμ λ³΄κ° λ
ΈμΆ κ°λ₯ν 보μμ½μ | /*
* @Controller
* public class TrendForecastController {
* // Controllerμμ int νλκ° λ©€λ² λ³μλ‘ μ μΈλμ΄ μ€λ λκ°μ 곡μ λ¨
* private int currentPage = 1;
*
* public void doSomething(HttpServletRequest request) {
* currentPage = Integer.parseInt(request.getParameter("page"));
* }......
* }
*/ | /*
* @Controller
* public class TrendForecastController {
* public void doSomething(HttpServletRequest request) {
* // μ§μλ³μλ‘ μ¬μ©νμ¬ μ€λ λκ° κ³΅μ λμ§ λͺ»νλλ‘ νλ€.
* int currentPage = Integer.parseInt(request.getParameter("page"));
* }......
* }
*/ |
C# | μΊ‘μν | μλͺ»λ μΈμ
μ μν λ°μ΄ν° μ 보λ
ΈμΆ | μλͺ»λ μΈμ
μ μν΄ μΈκ°λμ§ μμ μ¬μ©μμκ² μ€μμ λ³΄κ° λ
ΈμΆ κ°λ₯ν 보μμ½μ | class DataLeakBetweenSessions : IHttpHandler
{
// λ€μ€ μ€λ λ νκ²½μμ IHttpHandler λ₯Ό ꡬννλ ν΄λμ€μ μ 보λ₯Ό μ μ₯νλ νλκ° ν¬ν¨λλ©΄
μλλ€.
private String id;
public void ProcessRequest(HttpContext ctx)
{
var json = new JSONResonse()
{
Success = ctx.Request.QueryString["name"] != null,
Name = ctx.Request.QueryString["name"]
};
ctx.Response.ContentType = "application/json";
ctx.Response.Write(JsonConvert.SerializeObject(json));
}
public bool IsReusable
{
get { return false; }
}
} | class DataLeakBetweenSessions : IHttpHandler
{
public void ProcessRequest(HttpContext ctx)
{
// μ§μλ³μλ μΈμ
λ³μλ₯Ό μ μΈν΄μ μ¬μ©ν΄μΌνλ€.
ctx.Session["id"] = ctx.Request.QueryString["id"];
ctx.Response.ContentType = "application/json";
ctx.Response.Write(JsonConvert.SerializeObject(json));
}
public bool IsReusable
{
get { return false; }
}
}
var json = new JSONResonse()
{
Success = ctx.Request.QueryString["name"] != null,
Name = ctx.Request.QueryString["name"]
}; |
JAVA | μΊ‘μν | μ κ±°λμ§ μκ³ λ¨μ λλ²κ·Έ μ½λ | λλ²κΉ
μ μν μ½λλ₯Ό μ κ±°νμ§ μμ μΈκ°λμ§ μμ μ¬μ©μμκ² μ€μμ λ³΄κ° λ
ΈμΆ κ°λ₯ν 보μμ½μ | class Base64 {
public static void main(String[] args) {
if (debug) {
byte[] a = { (byte) 0xfc, (byte) 0x0f, (byte) 0xc0 };
byte[] b = { (byte) 0x03, (byte) 0xf0, (byte) 0x3f };
......
}
}
public void otherMethod() { ... }
} | class Base64 {
public void otherMethod() { ... }
} |
C# | μΊ‘μν | μ κ±°λμ§ μκ³ λ¨μ λλ²κ·Έ μ½λ | λλ²κΉ
μ μν μ½λλ₯Ό μ κ±°νμ§ μμ μΈκ°λμ§ μμ μ¬μ©μμκ² μ€μμ λ³΄κ° λ
ΈμΆ κ°λ₯ν 보μμ½μ | class Example {
public void Log() {
// Console.WriteLine λ±μ λ©μλλ₯Ό μ¬μ©ν λλ²κ·Έμ© μ½λκ° λ¨μμλ€.
Console.WriteLine("sensitive info");
}
} | class Example {
public void Log() {
// λλ²κ·Έμ© μ½λλ₯Ό μμ ν΄μΌνλ€.
//Console.WriteLine("sensitive info");
}
} |
C | μΊ‘μν | μ κ±°λμ§ μκ³ λ¨μ λλ²κ·Έ μ½λ | λλ²κΉ
μ μν μ½λλ₯Ό μ κ±°νμ§ μμ μΈκ°λμ§ μμ μ¬μ©μμκ² μ€μμ λ³΄κ° λ
ΈμΆ κ°λ₯ν 보μμ½μ | void LeftoverDebugCode() {
int i, ntprs;
char **strings;
nptrs = backtrace(buffer, 100);
strings = backtrace_symbols(buffer, nptrs);
...
// λλ²κ·Έ λͺ¨λμΌ μ μ½μ€νμ μΆλ ₯νλ€.
if(debug) {
for(i=0; i < nptr; i++) printf(β%s\nβ, strings[j]);
}
} | void LeftoverDebugCode() {
... // λλ²κ·Έ μ½λλ₯Ό μμ νκ³ λμ μ½λλ§ λ¨κΈ΄λ€.
} |
JAVA | μΊ‘μν | Public λ©μλλΆν° λ°νλ Private λ°°μ΄ | PublicμΌλ‘ μ μΈλ λ©μλμμ Privateλ‘ μ μΈλ λ°°μ΄μ λ°ν(return)νλ©΄ Private λ°°μ΄μ μ£Όμ κ°μ΄ μΈλΆμ λ
ΈμΆλμ΄ ν΄λΉ Private λ°°μ΄κ°μ μΈλΆμμ μμ κ°λ₯ν 보μμ½μ | // private μΈ λ°°μ΄μ publicμΈ λ©μλκ° returnνλ€.
private Color[] colors;
public Color[] getUserColors(Color[] userColors) { return colors; } | // μμ ν μ½λμ μ JAVA (λ°°μ΄μ μμκ° μΌλ°κ°μ²΄μΌ κ²½μ°)
private Color[] colors;
// λ©μλλ₯Ό privateμΌλ‘ νκ±°λ, 볡μ λ³Έ λ°ν, μμ νλ public λ©μλλ₯Ό λ³λλ‘ λ§λ λ€.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Color[] newColors = getUserColors();
......
}
public Color[] getUserColors(Color[] userColors) {
// λ°°μ΄μ 볡μ¬νλ€.
Color[] colors = new Color[userColors.length];
for (int i = 0; i < colors.length; i++)
// clone()λ©μλλ₯Ό μ΄μ©νμ¬ λ°°μ΄μ μμλ 볡μ¬νλ€.
colors[i] = this.colors[i].clone();
return colors;
} |
JAVA | μΊ‘μν | Public λ©μλλΆν° λ°νλ Private λ°°μ΄ | PublicμΌλ‘ μ μΈλ λ©μλμμ Privateλ‘ μ μΈλ λ°°μ΄μ λ°ν(return)νλ©΄ Private λ°°μ΄μ μ£Όμ κ°μ΄ μΈλΆμ λ
ΈμΆλμ΄ ν΄λΉ Private λ°°μ΄κ°μ μΈλΆμμ μμ κ°λ₯ν 보μμ½μ | // private μΈ λ°°μ΄μ publicμΈ λ©μλκ° returnνλ€.
private String[] colors;
public String[] getColors() { return colors; } | // μμ ν μ½λμ μ JAVA (λ°°μ΄μ μμκ° String νμ
λ±κ³Ό κ°μ΄ μμ μ΄ λμ§ μλ κ²½μ°)
private String[] colors;
// λ©μλλ₯Ό privateμΌλ‘ νκ±°λ, 볡μ λ³Έ λ°ν, μμ νλ public λ©μλλ₯Ό λ³λλ‘ λ§λ λ€.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] newColors = getColors();
......
}
public String[] getColors() {
String[] ret = null;
if (this.colors != null) {
ret = new String[colors.length];
for (int i = 0; i < colors.length; i++) {
ret[i] = this.colors[i];
}
}
return ret;
} |
C# | μΊ‘μν | Public λ©μλλΆν° λ°νλ Private λ°°μ΄ | PublicμΌλ‘ μ μΈλ λ©μλμμ Privateλ‘ μ μΈλ λ°°μ΄μ λ°ν(return)νλ©΄ Private λ°°μ΄μ μ£Όμ κ°μ΄ μΈλΆμ λ
ΈμΆλμ΄ ν΄λΉ Private λ°°μ΄κ°μ μΈλΆμμ μμ κ°λ₯ν 보μμ½μ | // private μΈ collectionμ publicμΈ λ©μλκ° returnνλ€.
private List<Color> colors;
public List<Color> getUserColors() { return colors; } | private List<Color> colors;
// λ©μλλ₯Ό privateμΌλ‘ νκ±°λ, 볡μ λ³Έ λ°ν, μμ νλ public λ©μλλ₯Ό λ³λλ‘ λ§λ λ€.
public List<Color> getUserColors() {
// λ°°μ΄μ 볡μ¬νλ€.
List< ICloneable> newList = new List< ICloneable>(colors.Count);
//Clone()λ©μλλ₯Ό μ΄μ©νμ¬ collectionμ μμλ 볡μ¬νλ€.
colors.ForEach((item) =>
{
newList.Add((ICloneable)item.Clone());
});
return newList;
} |
JAVA | μΊ‘μν | Private λ°°μ΄μ Public λ°μ΄ν° ν λΉ | PublicμΌλ‘ μ μΈλ λ°μ΄ν° λλ λ©μλμ μΈμκ° PrivateμΌλ‘ μ μΈλ λ°°μ΄μ μ μ₯λλ©΄ μ΄ Private λ°°μ΄μ μΈλΆμμ μ κ·Όνμ¬ μμ κ°λ₯ν 보μμ½μ | // userRoles νλλ privateμ΄μ§λ§, publicμΈ setUserRoles()λ‘ μΈλΆμ λ°°μ΄μ΄ ν λΉλλ©΄,
μ¬μ€μ public νλκ° λλ€.
private UserRole[] userRoles;
public void setUserRoles(UserRole[] userRoles) {
this.userRoles = userRoles;
} | // μμ ν μ½λμ μ JAVA (λ°°μ΄μ μμκ° μΌλ°κ°μ²΄μΌ κ²½μ°)
// κ°μ²΄κ° ν΄λμ€μ private memberλ₯Ό μμ νμ§ μλλ‘ νλ€.
private UserRole[] userRoles;
public void setUserRoles(UserRole[] userRoles) {
this.userRoles = new UserRole[userRoles.length];
for (int i = 0; i < userRoles.length; ++i)
this.userRoles[i] = userRoles[i].clone();
} |
JAVA | μΊ‘μν | Private λ°°μ΄μ Public λ°μ΄ν° ν λΉ | PublicμΌλ‘ μ μΈλ λ°μ΄ν° λλ λ©μλμ μΈμκ° PrivateμΌλ‘ μ μΈλ λ°°μ΄μ μ μ₯λλ©΄ μ΄ Private λ°°μ΄μ μΈλΆμμ μ κ·Όνμ¬ μμ κ°λ₯ν 보μμ½μ | // userRoles νλλ privateμ΄μ§λ§, publicμΈ setUserRoles()λ‘ μΈλΆμ λ°°μ΄μ΄ ν λΉλλ©΄,
μ¬μ€μ public νλκ° λλ€.
private String[] userRoles;
public void setUserRoles(String[] userRoles) {
this.userRoles = userRoles;
} | // μμ ν μ½λμ μ (λ°°μ΄μ μμκ° String νμ
λ±κ³Ό κ°μ΄ μμ μ΄ λμ§ μλ κ²½μ°)
// κ°μ²΄κ° ν΄λμ€μ private memberλ₯Ό μμ νμ§ μλλ‘ νλ€.
private String[] userRoles;
public void setUserRoles(String[] userRoles) {
this.userRoles = new String[userRoles.length];
for (int i = 0; i < userRoles.length; ++i)
this.userRoles[i] = userRoles[i];
} |
C# | μΊ‘μν | Private λ°°μ΄μ Public λ°μ΄ν° ν λΉ | PublicμΌλ‘ μ μΈλ λ°μ΄ν° λλ λ©μλμ μΈμκ° PrivateμΌλ‘ μ μΈλ λ°°μ΄μ μ μ₯λλ©΄ μ΄ Private λ°°μ΄μ μΈλΆμμ μ κ·Όνμ¬ μμ κ°λ₯ν 보μμ½μ | class Program
{
// userRoles νλλ privateμ΄μ§λ§, publicμΈ setUserRoles()μΌλ‘ μΈλΆμ λ°°μ΄μ΄ ν λΉλλ©΄,
μ¬μ€μ public νλκ° λλ€.
private String[] userRoles;
public void SetUserRoles(String[] userRoles)
{
this.userRoles = userRoles;
}
} | class Program
{
// κ°μ²΄κ° ν΄λμ€μ private memberλ₯Ό μμ νμ§ μλλ‘ νλ€.
private String[] userRoles;
public void SetUserRoles(String[] userRoles)
{
int length = userRoles.Length;
this.userRoles = new String[length];
for(int i = 0; i < length; i++) { \
this.userRoles[i] = userRoles[i];
}
}
} |
JAVA | API μ€μ© | DNS lookupμ μμ‘΄ν 보μκ²°μ | λλ©μΈλͺ
νμΈ(DNS lookup)μΌλ‘ 보μκ²°μ μ μνν λ μ
μμ μΌλ‘ λ³μ‘°λ DNS μ λ³΄λ‘ μκΈ°μΉ μμ 보μμνμ λ
ΈμΆλλ 보μμ½μ | public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
boolean trusted = false;
String ip = req.getRemoteAddr();
InetAddress addr = InetAddress.getByName(ip);
// λλ©μΈμ 곡격μμ μν΄ μ€νλλ μλ²μ DNSκ° λ³κ²½λ μ μμΌλ―λ‘ μμ νμ§ μλ€.
if (addr.getCanonicalHostName().endsWith("trustme.com")) {
do_something_for_Trust_System();
} | public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String ip = req.getRemoteAddr();
if (ip == null || "".equals(ip)) return ;
// μ΄μ©νλ €λ μ€μ μλ²μ IP μ£Όμλ₯Ό μ¬μ©νμ¬ DNSλ³μ‘°μ λ°©μ΄νλ€.
String trustedAddr = "127.0.0.1";
if (ip.equals(trustedAddr)) {
do_something_for_Trust_System();
} |
C# | API μ€μ© | DNS lookupμ μμ‘΄ν 보μκ²°μ | λλ©μΈλͺ
νμΈ(DNS lookup)μΌλ‘ 보μκ²°μ μ μνν λ μ
μμ μΌλ‘ λ³μ‘°λ DNS μ λ³΄λ‘ μκΈ°μΉ μμ 보μμνμ λ
ΈμΆλλ 보μμ½μ | bool trusted;
string remoteIpAddress = Request.ServerVariables["REMOTE_HOST"];
IPAddress hostIPAddress = IPAddress.Parse(remoteIpAddress);
IPHostEntry hostInfo = Dns.GetHostByAddress(hostIPAddress);
string hostName = hostInfo.HostName;
if (hostName.EndsWith("trust.com"))
{
trusted = true;
} | bool trusted;
string remoteIpAddress = Request.ServerVariables["REMOTE_HOST"];
if ( remoteIpAddress.Equals(trustedAddr))
{
trusted = true;
Do_something_for_Trust_System();
} |
C | API μ€μ© | DNS lookupμ μμ‘΄ν 보μκ²°μ | λλ©μΈλͺ
νμΈ(DNS lookup)μΌλ‘ 보μκ²°μ μ μνν λ μ
μμ μΌλ‘ λ³μ‘°λ DNS μ λ³΄λ‘ μκΈ°μΉ μμ 보μμνμ λ
ΈμΆλλ 보μμ½μ | struct hostent *hp;struct in_addr myaddr;
char* tHost = "trustme.example.com";
myaddr.s_addr=inet_addr(ip_addr_string);
hp = gethostbyaddr((char *) &myaddr, sizeof(struct in_addr), AF_INET);
// μμ²μ μ λ’°μ±μ νΈμ€νΈμ μ΄λ¦μΌλ‘ νλ³νκ³ μλ€.
if (hp && !strncmp(hp->h_name, tHost, sizeof(tHost))) {
trusted = true;
} else {
trusted = false;
} | struct hostent *hp;struct in_addr myaddr;
char* tHost = "127.0.0.1";
myaddr.s_addr=inet_addr(ip_addr_string);
hp = gethostbyaddr((char *) &myaddr, sizeof(struct in_addr), AF_INET);
// νΈμ€νΈμ μ΄λ¦μ΄ μλλΌ IPλ‘ μ§μ λΉκ΅νλ€.
if (hp && !strncmp(hp->h_name, tHost, sizeof(tHost))) {
trusted = true;
} else {
trusted = false;
} |
C | API μ€μ© | μ·¨μ½ν API μ¬μ© | μ·¨μ½ν ν¨μλ₯Ό μ¬μ©ν΄μ μκΈ°μΉ μμ 보μμνμ λ
ΈμΆλλ 보μμ½μ | #include <stdio.h>
void requestString()
{
char str[100];
// gets() ν¨μλ λ¬Έμμ΄ κΈΈμ΄λ₯Ό μ ν ν μ μμ΄ μμ νμ§ μλ€.
gets(str);
} | #include <stdio.h>
void requestString()
{
char str[100];
// gets_s() ν¨μλ λ¬Έμμ΄ κΈΈμ΄ μ νμ΄ κ°λ₯νλ€.
gets_s(str, sizeof(str));
} |
JAVA | API μ€μ© | μ·¨μ½ν API μ¬μ© | μ·¨μ½ν ν¨μλ₯Ό μ¬μ©ν΄μ μκΈ°μΉ μμ 보μμνμ λ
ΈμΆλλ 보μμ½μ | public class S246 extends javax.servlet.http.HttpServlet {
private Socket socket
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException {
try {
// νλ μμν¬μ λ©μλ νΈμΆ λμ μμΌμ μ§μ μ¬μ©νκ³ μμ΄ νλ μμν¬μμ μ 곡νλ 보μκΈ°λ₯μ
μ 곡 λ°μ§ λͺ»ν΄ μμ νμ§ μλ€.
socket = new Socket("kisa.or.kr", 8080);
} catch (UnknownHostException e) {
...... | public class S246 extends javax.servlet.http.HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException {
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try {
URL url = new URL("http://127.0.0.1:8080/DataServlet");
// 보μκΈ°λ₯μ μ 곡νλ νλ μμν¬μ λ©μλλ₯Ό μ¬μ©νμ¬μΌνλ€.
URLConnection urlConn = url.openConnection();
urlConn.setDoOutput(true);
....... |
JAVA | API μ€μ© | μ·¨μ½ν API μ¬μ© | μ·¨μ½ν ν¨μλ₯Ό μ¬μ©ν΄μ μκΈ°μΉ μμ 보μμνμ λ
ΈμΆλλ 보μμ½μ | public class U382 extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
do_something(logger);
} catch (IOException ase) {
logger.info("ERROR");
// J2EE νλ‘κ·Έλ¨μμ System.exit()μ μ¬μ©νμ¬ μλΉμ€κ° μ’
λ£ λ μ μλ€.
System.exit(1);
} | public class U382 extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
do_something(logger);
} catch (IOException ase) {
logger.info("ERROR");
// μλΉμ€ μ’
λ£λ₯Ό λ§κΈ° μν΄ J2EEμμλ System.exit()λ₯Ό μ¬μ©νμ§ μλλ€.
} |
C# | API μ€μ© | μ·¨μ½ν API μ¬μ© | μ·¨μ½ν ν¨μλ₯Ό μ¬μ©ν΄μ μκΈ°μΉ μμ 보μμνμ λ
ΈμΆλλ 보μμ½μ | try {
...
} catch (Exception e) {
...
// Application.Exit() μ μ¦μ νλ‘κ·Έλ¨μ μ’
λ£νκΈ° λλ¬Έμ, Form.Closed νΉμ Form.Closing
μ΄λ²€νΈκ° μ²λ¦¬λμ§ μλλ€.
Application.Exit();
} | try {
...
} catch (Exception e) {
...
// Application.Exit() μ μ¬μ©νμ§ μμΌλ©΄, μ΄λ²€νΈλ₯Ό μ²λ¦¬νμ§ λͺ»νκ³ νλ‘κ·Έλ¨μ΄ μ’
λ£λλ κ²μ
λ°©μ§ν μ μλ€.
this.Close();
} |
JAVA | μ
λ ₯ μ ν¨μ± κ²μ¬ λ° λ°μ΄ν° μ΄κ· (IDS) | SQL μΈμ μ
λ°©μ§ | null | import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
class Login {
public Connection getConnection() throws SQLException {
DriverManager.registerDriver(new
com.microsoft.sqlserver.jdbc.SQLServerDriver());
String dbConnection =
PropertyManager.getProperty("db.connection");
// Can hold some value like
// "jdbc:microsoft:sqlserver://<HOST>:1433,<UID>,<PWD>"
return DriverManager.getConnection(dbConnection);
}
String hashPassword(char[] password) {
// Create hash of password
}
public void doPrivilegedAction(String username, char[] password)
throws SQLException {
Connection connection = getConnection();
if (connection == null) {
// Handle error
}
try {
String pwd = hashPassword(password);
String sqlString = "SELECT * FROM db_user WHERE username = '"
+ username +
"' AND password = '" + pwd + "'";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sqlString);
if (!rs.next()) {
throw new SecurityException(
"User name or password incorrect"
);
}
// Authenticated; proceed
} finally {
try {
connection.close();
} catch (SQLException x) {
// Forward to handler
}
}
}
} | public void doPrivilegedAction(
String username, char[] password) throws SQLException {
Connection connection = getConnection();
if (connection == null) {
// Handle error
}
try {
String pwd = hashPassword(password);
// Validate username length
if (username.length() > 8) {
// Handle error
}
String sqlString = "select * from db_user where username=? and password=?";
PreparedStatement stmt = connection.prepareStatement(sqlString);
stmt.setString(1, username);
stmt.setString(2, pwd);
ResultSet rs = stmt.executeQuery();
if (!rs.next()) {
throw new SecurityException("User name or password incorrect");
}
// Authenticated; proceed
} finally {
try {
connection.close();
} catch (SQLException x) {
// Forward to handler
}
}
} |
JAVA | μ
λ ₯ μ ν¨μ± κ²μ¬ λ° λ°μ΄ν° μ΄κ· (IDS) | SQL μΈμ μ
λ°©μ§ | null | import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
class Login {
public Connection getConnection() throws SQLException {
DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
String dbConnection = PropertyManager.getProperty("db.connection");
// Can hold some value like
// "jdbc:microsoft:sqlserver://<HOST>:1433,<UID>,<PWD>"
return DriverManager.getConnection(dbConnection);
}
String hashPassword(char[] password) {
// Create hash of password
}
public void doPrivilegedAction(
String username, char[] password) throws SQLException {
Connection connection = getConnection();
if (connection == null) {
// Handle error
}
try {
String pwd = hashPassword(password);
String sqlString = "select * from db_user where username=" +
username + " and password =" + pwd;
PreparedStatement stmt = connection.prepareStatement(sqlString);
ResultSet rs = stmt.executeQuery();
if (!rs.next()) {
throw new SecurityException("User name or password incorrect");
}
// Authenticated; proceed
} finally {
try {
connection.close();
} catch (SQLException x) {
// Forward to handler
}
}
}
} | public void doPrivilegedAction(
String username, char[] password) throws SQLException {
Connection connection = getConnection();
if (connection == null) {
// Handle error
}
try {
String pwd = hashPassword(password);
// Validate username length
if (username.length() > 8) {
// Handle error
}
String sqlString = "select * from db_user where username=? and password=?";
PreparedStatement stmt = connection.prepareStatement(sqlString);
stmt.setString(1, username);
stmt.setString(2, pwd);
ResultSet rs = stmt.executeQuery();
if (!rs.next()) {
throw new SecurityException("User name or password incorrect");
}
// Authenticated; proceed
} finally {
try {
connection.close();
} catch (SQLException x) {
// Forward to handler
}
}
} |
JAVA | μ
λ ₯ μ ν¨μ± κ²μ¬ λ° λ°μ΄ν° μ΄κ· (IDS) | μ ν¨μ± κ²μ¬ μ λ¬Έμμ΄ μ κ·ν | null | // String s may be user controllable
// \uFE64 is normalized to < and \uFE65 is normalized to > using the NFKC normalization form
String s = "\uFE64" + "script" + "\uFE65";
// Validate
Pattern pattern = Pattern.compile("[<>]"); // Check for angle brackets
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
// Found black listed tag
throw new IllegalStateException();
} else {
// ...
}
// Normalize
s = Normalizer.normalize(s, Form.NFKC); | String s = "\uFE64" + "script" + "\uFE65";
// Normalize
s = Normalizer.normalize(s, Form.NFKC);
// Validate
Pattern pattern = Pattern.compile("[<>]");
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
// Found blacklisted tag
throw new IllegalStateException();
} else {
// ...
} |
JAVA | μ
λ ₯ μ ν¨μ± κ²μ¬ λ° λ°μ΄ν° μ΄κ· (IDS) | μ²λ¦¬λμ§ μμ μ¬μ©μ μ
λ ₯ κΈ°λ‘νμ§ μκΈ° | null | if (loginSuccessful) {
logger.severe("User login succeeded for: " + username);
} else {
logger.severe("User login failed for: " + username);
} |
if(loginSuccessful){logger.severe("User login succeeded for: "+sanitizeUser(username));}else{logger.severe("User login failed for: "+sanitizeUser(username));}
public String sanitizeUser(String username){return Pattern.matches("[A-Za-z0-9_]+",username))?username:"unauthorized user";}
Logger sanLogger=new SanitizedTextLogger(logger);
if(loginSuccessful){sanLogger.severe("User login succeeded for: "+username);}else{sanLogger.severe("User login failed for: "+username);}
class SanitizedTextLogger extends Logger {
Logger delegate;
public SanitizedTextLogger(Logger delegate) {
super(delegate.getName(), delegate.getResourceBundleName());
this.delegate = delegate;
}
public String sanitize(String msg) {
Pattern newline = Pattern.compile("\n");
Matcher matcher = newline.matcher(msg);
return matcher.replaceAll("\n ");
}
public void severe(String msg) {
delegate.severe(sanitize(msg));
}
// .. Other Logger methods which must also sanitize their log messages
} |
JAVA | μ
λ ₯ μ ν¨μ± κ²μ¬ λ° λ°μ΄ν° μ΄κ· (IDS) | ZipInputStreamμμ νμΌμ μμ νκ² μΆμΆνκΈ° | null | static final int BUFFER = 512;
// ...
public final void unzip(String filename) throws java.io.IOException{
FileInputStream fis = new FileInputStream(filename);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry;
try {
while ((entry = zis.getNextEntry()) != null) {
System.out.println("Extracting: " + entry);
int count;
byte data[] = new byte[BUFFER];
// Write the files to the disk
FileOutputStream fos = new FileOutputStream(entry.getName());
BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
while ((count = zis.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
zis.closeEntry();
}
} finally {
zis.close();
}
} | static final int BUFFER = 512;
static final long TOOBIG = 0x6400000; // Max size of unzipped data, 100MB
static final int TOOMANY = 1024; // Max number of files
// ...
private String validateFilename(String filename, String intendedDir)
throws java.io.IOException {
File f = new File(filename);
String canonicalPath = f.getCanonicalPath();
File iD = new File(intendedDir);
String canonicalID = iD.getCanonicalPath();
if (canonicalPath.startsWith(canonicalID)) {
return canonicalPath;
} else {
throw new IllegalStateException("File is outside extraction target directory.");
}
}
public final void unzip(String filename) throws java.io.IOException {
FileInputStream fis = new FileInputStream(filename);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry;
int entries = 0;
long total = 0;
try {
while ((entry = zis.getNextEntry()) != null) {
System.out.println("Extracting: " + entry);
int count;
byte data[] = new byte[BUFFER];
// Write the files to the disk, but ensure that the filename is valid,
// and that the file is not insanely big
String name = validateFilename(entry.getName(), ".");
if (entry.isDirectory()) {
System.out.println("Creating directory " + name);
new File(name).mkdir();
continue;
}
FileOutputStream fos = new FileOutputStream(name);
BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
while (total + BUFFER <= TOOBIG && (count = zis.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
total += count;
}
dest.flush();
dest.close();
zis.closeEntry();
entries++;
if (entries > TOOMANY) {
throw new IllegalStateException("Too many files to unzip.");
}
if (total + BUFFER > TOOBIG) {
throw new IllegalStateException("File being unzipped is too big.");
}
}
} finally {
zis.close();
}
} |
JAVA | μ
λ ₯ μ ν¨μ± κ²μ¬ λ° λ°μ΄ν° μ΄κ· (IDS) | ZipInputStreamμμ νμΌμ μμ νκ² μΆμΆνκΈ° | null | static final int BUFFER = 512;
static final int TOOBIG = 0x6400000; // 100MB
// ...
public final void unzip(String filename) throws java.io.IOException{
FileInputStream fis = new FileInputStream(filename);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry;
try {
while ((entry = zis.getNextEntry()) != null) {
System.out.println("Extracting: " + entry);
int count;
byte data[] = new byte[BUFFER];
// Write the files to the disk, but only if the file is not insanely big
if (entry.getSize() > TOOBIG ) {
throw new IllegalStateException("File to be unzipped is huge.");
}
if (entry.getSize() == -1) {
throw new IllegalStateException("File to be unzipped might be huge.");
}
FileOutputStream fos = new FileOutputStream(entry.getName());
BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
while ((count = zis.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
zis.closeEntry();
}
} finally {
zis.close();
}
} | static final int BUFFER = 512;
static final long TOOBIG = 0x6400000; // Max size of unzipped data, 100MB
static final int TOOMANY = 1024; // Max number of files
// ...
private String validateFilename(String filename, String intendedDir)
throws java.io.IOException {
File f = new File(filename);
String canonicalPath = f.getCanonicalPath();
File iD = new File(intendedDir);
String canonicalID = iD.getCanonicalPath();
if (canonicalPath.startsWith(canonicalID)) {
return canonicalPath;
} else {
throw new IllegalStateException("File is outside extraction target directory.");
}
}
public final void unzip(String filename) throws java.io.IOException {
FileInputStream fis = new FileInputStream(filename);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry;
int entries = 0;
long total = 0;
try {
while ((entry = zis.getNextEntry()) != null) {
System.out.println("Extracting: " + entry);
int count;
byte data[] = new byte[BUFFER];
// Write the files to the disk, but ensure that the filename is valid,
// and that the file is not insanely big
String name = validateFilename(entry.getName(), ".");
if (entry.isDirectory()) {
System.out.println("Creating directory " + name);
new File(name).mkdir();
continue;
}
FileOutputStream fos = new FileOutputStream(name);
BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
while (total + BUFFER <= TOOBIG && (count = zis.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
total += count;
}
dest.flush();
dest.close();
zis.closeEntry();
entries++;
if (entries > TOOMANY) {
throw new IllegalStateException("Too many files to unzip.");
}
if (total + BUFFER > TOOBIG) {
throw new IllegalStateException("File being unzipped is too big.");
}
}
} finally {
zis.close();
}
} |
JAVA | μ
λ ₯ μ ν¨μ± κ²μ¬ λ° λ°μ΄ν° μ΄κ· (IDS) | νμ λ¬Έμμ΄μμ μ²λ¦¬λμ§ μμ μ¬μ©μ μ
λ ₯ μ μΈ | null | class Format {
static Calendar c = new GregorianCalendar(1995, GregorianCalendar.MAY, 23);
public static void main(String[] args) {
// args[0] should contain the credit card expiration date
// but might contain %1$tm, %1$te or %1$tY format specifiers
System.out.format(
args[0] + " did not match! HINT: It was issued on %1$terd of some month", c
);
}
} | class Format {
static Calendar c =
new GregorianCalendar(1995, GregorianCalendar.MAY, 23);
public static void main(String[] args) {
// args[0] is the credit card expiration date
// Perform comparison with c,
// if it doesn't match, print the following line
System.out.format(
"%s did not match! HINT: It was issued on %terd of some month",
args[0], c
);
}
} |
JAVA | μ
λ ₯ μ ν¨μ± κ²μ¬ λ° λ°μ΄ν° μ΄κ· (IDS) | Runtime.exec() λ©μλμ μ λ¬λ μ λ’°ν μ μλ λ°μ΄ν° μ²λ¦¬ | null | class DirList {
public static void main(String[] args) throws Exception {
String dir = System.getProperty("dir");
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("cmd.exe /C dir " + dir);
int result = proc.waitFor();
if (result != 0) {
System.out.println("process error: " + result);
}
InputStream in = (result == 0) ? proc.getInputStream() :
proc.getErrorStream();
int c;
while ((c = in.read()) != -1) {
System.out.print((char) c);
}
}
} | String dir = null;
int number = Integer.parseInt(System.getProperty("dir")); // Only allow integer choices
switch (number) {
case 1:
dir = "data1";
break; // Option 1
case 2:
dir = "data2";
break; // Option 2
default: // Invalid
break;
}
if (dir == null) {
// Handle error
} |
JAVA | μ
λ ₯ μ ν¨μ± κ²μ¬ λ° λ°μ΄ν° μ΄κ· (IDS) | Runtime.exec() λ©μλμ μ λ¬λ μ λ’°ν μ μλ λ°μ΄ν° μ²λ¦¬ | null | class DirList {
public static void main(String[] args) throws Exception {
String dir = System.getProperty("dir");
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(new String[] {"sh", "-c", "ls " + dir});
int result = proc.waitFor();
if (result != 0) {
System.out.println("process error: " + result);
}
InputStream in = (result == 0) ? proc.getInputStream() :
proc.getErrorStream();
int c;
while ((c = in.read()) != -1) {
System.out.print((char) c);
}
}
} | import java.io.File;
class DirList {
public static void main(String[] args) throws Exception {
File dir = new File(System.getProperty("dir"));
if (!dir.isDirectory()) {
System.out.println("Not a directory");
} else {
for (String file : dir.list()) {
System.out.println(file);
}
}
}
} |
JAVA | μ
λ ₯ μ ν¨μ± κ²μ¬ λ° λ°μ΄ν° μ΄κ· (IDS) | μ κ· ννμμ ν¬ν¨λ μ λ’°ν μ μλ λ°μ΄ν°λ₯Ό μ²λ¦¬νκΈ° | null | import java.io.FileInputStream;
import java.io.IOException;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LogSearch {
public static void FindLogEntry(String search) {
// Construct regex dynamically from user string
String regex = "(.*? +public\\[\\d+\\] +.*" + search + ".*)";
Pattern searchPattern = Pattern.compile(regex);
try (FileInputStream fis = new FileInputStream("log.txt")) {
FileChannel channel = fis.getChannel();
// Get the file's size and map it into memory
long size = channel.size();
final MappedByteBuffer mappedBuffer = channel.map(
FileChannel.MapMode.READ_ONLY, 0, size);
Charset charset = Charset.forName("ISO-8859-15");
final CharsetDecoder decoder = charset.newDecoder();
// Read file into char buffer
CharBuffer log = decoder.decode(mappedBuffer);
Matcher logMatcher = searchPattern.matcher(log);
while (logMatcher.find()) {
String match = logMatcher.group();
if (!match.isEmpty()) {
System.out.println(match);
}
}
} catch (IOException ex) {
System.err.println("thrown exception: " + ex.toString());
Throwable[] suppressed = ex.getSuppressed();
for (int i = 0; i < suppressed.length; i++) {
System.err.println("suppressed exception: "
+ suppressed[i].toString());
}
}
return;
} | public static void FindLogEntry(String search) {
// Sanitize search string
StringBuilder sb = new StringBuilder(search.length());
for (int i = 0; i < search.length(); ++i) {
char ch = search.charAt(i);
if (Character.isLetterOrDigit(ch) || ch == ' ' || ch == '\'') {
sb.append(ch);
}
}
search = sb.toString();
// Construct regex dynamically from user string
String regex = "(.*? +public\\[\\d+\\] +.*" + search + ".*)";
// ...
} |
JAVA | μ
λ ₯ μ ν¨μ± κ²μ¬ λ° λ°μ΄ν° μ΄κ· (IDS) | μ κ· ννμμ ν¬ν¨λ μ λ’°ν μ μλ λ°μ΄ν°λ₯Ό μ²λ¦¬νκΈ° | null | import java.io.FileInputStream;
import java.io.IOException;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LogSearch {
public static void FindLogEntry(String search) {
// Construct regex dynamically from user string
String regex = "(.*? +public\\[\\d+\\] +.*" + search + ".*)";
Pattern searchPattern = Pattern.compile(regex);
try (FileInputStream fis = new FileInputStream("log.txt")) {
FileChannel channel = fis.getChannel();
// Get the file's size and map it into memory
long size = channel.size();
final MappedByteBuffer mappedBuffer = channel.map(
FileChannel.MapMode.READ_ONLY, 0, size);
Charset charset = Charset.forName("ISO-8859-15");
final CharsetDecoder decoder = charset.newDecoder();
// Read file into char buffer
CharBuffer log = decoder.decode(mappedBuffer);
Matcher logMatcher = searchPattern.matcher(log);
while (logMatcher.find()) {
String match = logMatcher.group();
if (!match.isEmpty()) {
System.out.println(match);
}
}
} catch (IOException ex) {
System.err.println("thrown exception: " + ex.toString());
Throwable[] suppressed = ex.getSuppressed();
for (int i = 0; i < suppressed.length; i++) {
System.err.println("suppressed exception: "
+ suppressed[i].toString());
}
}
return;
} | public static void FindLogEntry(String search) {
// Sanitize search string
search = Pattern.quote(search);
// Construct regex dynamically from user string
String regex = "(.*? +public\\[\\d+\\] +.*" + search + ".*)";
// ...
} |
JAVA | μ
λ ₯ μ ν¨μ± κ²μ¬ λ° λ°μ΄ν° μ΄κ· (IDS) | κ²μ¦ μ μ λͺ¨λ λ¬Έμμ΄ μμ μ μν | null | import java.text.Normalizer;
import java.text.Normalizer.Form;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TagFilter {
public static String filterString(String str) {
String s = Normalizer.normalize(str, Form.NFKC);
// Validate input
Pattern pattern = Pattern.compile("<script>");
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
throw new IllegalArgumentException("Invalid input");
}
// Deletes noncharacter code points
s = s.replaceAll("[\\p{Cn}]", "");
return s;
}
public static void main(String[] args) {
// "\uFDEF" is a noncharacter code point
String maliciousInput = "<scr" + "\uFDEF" + "ipt>";
String sb = filterString(maliciousInput);
// sb = "<script>"
}
} | import java.text.Normalizer;
import java.text.Normalizer.Form;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TagFilter {
public static String filterString(String str) {
String s = Normalizer.normalize(str, Form.NFKC);
// Replaces all noncharacter code points with Unicode U+FFFD
s = s.replaceAll("[\\p{Cn}]", "\uFFFD");
// Validate input
Pattern pattern = Pattern.compile("<script>");
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
throw new IllegalArgumentException("Invalid input");
}
return s;
}
public static void main(String[] args) {
// "\uFDEF" is a non-character code point
String maliciousInput = "<scr" + "\uFDEF" + "ipt>";
String s = filterString(maliciousInput);
// s = <scr?ipt>
} |
JAVA | μ
λ ₯ μ ν¨μ± κ²μ¬ λ° λ°μ΄ν° μ΄κ· (IDS) | μ¨κ²¨μ§ νΌ νλμ λ΄μ©μ μ λ’°νμ§ λͺ»ν μ μλ€. | null | public class SampleServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
String visible = request.getParameter("visible");
String hidden = request.getParameter("hidden");
if (visible != null || hidden != null) {
out.println("Visible Parameter:");
out.println( sanitize(visible));
out.println("<br>Hidden Parameter:");
out.println(hidden);
} else {
out.println("<p>");
out.print("<form action=\"");
out.print("SampleServlet\" ");
out.println("method=POST>");
out.println("Parameter:");
out.println("<input type=text size=20 name=visible>");
out.println("<br>");
out.println("<input type=hidden name=hidden value=\'a benign value\'>");
out.println("<input type=submit>");
out.println("</form>");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
doGet(request, response);
}
// Filter the specified message string for characters
// that are sensitive in HTML.
public static String sanitize(String message) {
// ...
}
} | public class SampleServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
String visible = request.getParameter("visible");
String hidden = request.getParameter("hidden");
if (visible != null || hidden != null) {
out.println("Visible Parameter:");
out.println( sanitize(visible));
out.println("<br>Hidden Parameter:");
out.println( sanitize(hidden)); // Hidden variable sanitized
} else {
out.println("<p>");
out.print("<form action=\"");
out.print("SampleServlet\" ");
out.println("method=POST>");
out.println("Parameter:");
out.println("<input type=text size=20 name=visible>");
out.println("<br>");
out.println("<input type=hidden name=hidden value=\'a benign value\'>");
out.println("<input type=submit>");
out.println("</form>");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
doGet(request, response);
}
// Filter the specified message string for characters
// that are sensitive in HTML.
public static String sanitize(String message) {
// ...
}
} |
JAVA | μ
λ ₯ μ ν¨μ± κ²μ¬ λ° λ°μ΄ν° μ΄κ· (IDS) | XML μΈμ μ
λ°©μ§ | null | import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class OnlineStore {
private static void createXMLStreamBad(final BufferedOutputStream outStream,
final String quantity) throws IOException {
String xmlString = "<item>\n<description>Widget</description>\n"
+ "<price>500</price>\n" + "<quantity>" + quantity
+ "</quantity></item>";
outStream.write(xmlString.getBytes());
outStream.flush();
}
} | import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class OnlineStore {
private static void createXMLStream(final BufferedOutputStream outStream,
final String quantity) throws IOException, NumberFormatException {
// Write XML string only if quantity is an unsigned integer (count).
int count = Integer.parseUnsignedInt(quantity);
String xmlString = "<item>\n<description>Widget</description>\n"
+ "<price>500</price>\n" + "<quantity>" + count + "</quantity></item>";
outStream.write(xmlString.getBytes());
outStream.flush();
}
} |
JAVA | μ
λ ₯ μ ν¨μ± κ²μ¬ λ° λ°μ΄ν° μ΄κ· (IDS) | XML μΈμ μ
λ°©μ΄ | null | import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class OnlineStore {
private static void createXMLStreamBad(final BufferedOutputStream outStream,
final String quantity) throws IOException {
String xmlString = "<item>\n<description>Widget</description>\n"
+ "<price>501</price>\n" + "<quantity>" + quantity
+ "</quantity></item>";
outStream.write(xmlString.getBytes());
outStream.flush();
}
} | import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
public class OnlineStore {
private static void createXMLStream(final BufferedOutputStream outStream,
final String quantity) throws IOException {
String xmlString;
xmlString = "<item>\n<description>Widget</description>\n"
+ "<price>500.0</price>\n" + "<quantity>" + quantity
+ "</quantity></item>";
InputSource xmlStream = new InputSource(new StringReader(xmlString));
// Build a validating SAX parser using our schema
SchemaFactory sf = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
DefaultHandler defHandler = new DefaultHandler() {
public void warning(SAXParseException s) throws SAXParseException {
throw s;
}
public void error(SAXParseException s) throws SAXParseException {
throw s;
}
public void fatalError(SAXParseException s) throws SAXParseException {
throw s;
}
};
StreamSource ss = new StreamSource(new File("schema.xsd"));
try {
Schema schema = sf.newSchema(ss);
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setSchema(schema);
SAXParser saxParser = spf.newSAXParser();
// To set the custom entity resolver,
// an XML reader needs to be created
XMLReader reader = saxParser.getXMLReader();
reader.setEntityResolver(new CustomResolver());
saxParser.parse(xmlStream, defHandler);
} catch (ParserConfigurationException x) {
throw new IOException("Unable to validate XML", x);
} catch (SAXException x) {
throw new IOException("Invalid quantity", x);
}
// Our XML is valid, proceed
outStream.write(xmlString.getBytes());
outStream.flush();
}
} |
JAVA | μ
λ ₯ μ ν¨μ± κ²μ¬ λ° λ°μ΄ν° μ΄κ· (IDS) | XML μΈλΆ μν°ν° 곡격 λ°©μ΄ | null | import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
class XXE {
private static void receiveXMLStream(InputStream inStream,
DefaultHandler defaultHandler)
throws ParserConfigurationException, SAXException, IOException {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(inStream, defaultHandler);
}
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException {
try {
receiveXMLStream(new FileInputStream("evil.xml"), new DefaultHandler());
} catch (java.net.MalformedURLException mue) {
System.err.println("Malformed URL Exception: " + mue);
}
}
}
<?xml version="1.0"?>
<!DOCTYPE foo SYSTEM "file:/dev/tty">
<foo>bar</foo> | import java.io.IOException;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
class CustomResolver implements EntityResolver {
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException, IOException {
// Check for known good entities
String entityPath = "file:/Users/onlinestore/good.xml";
if (systemId.equals(entityPath)) {
System.out.println("Resolving entity: " + publicId + " " + systemId);
return new InputSource(entityPath);
} else {
// Disallow unknown entities by returning a blank path
return new InputSource();
}
}
} |
JAVA | μ
λ ₯ μ ν¨μ± κ²μ¬ λ° λ°μ΄ν° μ΄κ· (IDS) | XML μΈλΆ μν°ν° 곡격 λ°©μ΄ | null | import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
class XXE {
private static void receiveXMLStream(InputStream inStream,
DefaultHandler defaultHandler)
throws ParserConfigurationException, SAXException, IOException {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(inStream, defaultHandler);
}
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException {
try {
receiveXMLStream(new FileInputStream("evil.xml"), new DefaultHandler());
} catch (java.net.MalformedURLException mue) {
System.err.println("Malformed URL Exception: " + mue);
}
}
}
<?xml version="1.1"?>
<!DOCTYPE foo SYSTEM "file:/dev/tty">
<foo>bar</foo> | import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
class XXE {
private static void receiveXMLStream(InputStream inStream,
DefaultHandler defaultHandler) throws ParserConfigurationException,
SAXException, IOException {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
// Create an XML reader to set the entity resolver.
XMLReader reader = saxParser.getXMLReader();
reader.setEntityResolver(new CustomResolver());
reader.setContentHandler(defaultHandler);
InputSource is = new InputSource(inStream);
reader.parse(is);
}
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException {
try {
receiveXMLStream(new FileInputStream("evil.xml"), new DefaultHandler());
} catch (java.net.MalformedURLException mue) {
System.err.println("Malformed URL Exception: " + mue);
}
}
} |
JAVA | μ μΈκ³Ό μ΄κΈ°ν (DCL) | ν΄λμ€ μ΄κΈ°ν μν λ°©μ§ | null | public class Cycle {
private final int balance;
private static final Cycle c = new Cycle();
private static final int deposit = (int) (Math.random() * 100); // Random deposit
public Cycle() {
balance = deposit - 10; // Subtract processing fee
}
public static void main(String[] args) {
System.out.println("The account balance is: " + c.balance);
}
} | public class Cycle {
private final int balance;
private static final int deposit = (int) (Math.random() * 100); // Random deposit
private static final Cycle c = new Cycle(); // Inserted after initialization of required fields
public Cycle() {
balance = deposit - 10; // Subtract processing fee
}
public static void main(String[] args) {
System.out.println("The account balance is: " + c.balance);
}
} |
JAVA | μ μΈκ³Ό μ΄κΈ°ν (DCL) | ν΄λμ€ μ΄κΈ°ν μν λ°©μ§ | null | class A {
public static final int a = B.b + 1;
// ...
}
class B {
public static final int b = A.a + 1;
// ...
} | class A {
public static final int a = 2;
// ...
}
class B {
public static final int b = A.a + 1;
// ...
} |
JAVA | μ μΈκ³Ό μ΄κΈ°ν (DCL) | ν΄λμ€ μ΄κΈ°ν μν λ°©μ§ | null | class A {
public static int a = B.b();
public static int c() { return 1; }
}
class B {
public static int b() { return A.c(); }
} | class A {
public static int a = B.b();
}
class B {
public static int b() { return B.c(); }
public static int c() { return 1; }
} |
JAVA | μ μΈκ³Ό μ΄κΈ°ν (DCL) | μλ° νμ€ λΌμ΄λΈλ¬λ¦¬μ κ³΅κ° μλ³μλ₯Ό μ¬μ¬μ© κΈμ§ | null | class Vector {
private int val = 1;
public boolean isEmpty() {
if (val == 1) { // Compares with 1 instead of 0
return true;
} else {
return false;
}
}
// Other functionality is same as java.util.Vector
}
// import java.util.Vector; omitted
public class VectorUser {
public static void main(String[] args) {
Vector v = new Vector();
if (v.isEmpty()) {
System.out.println("Vector is empty");
}
}
} | class MyVector {
//Other code
} |
JAVA | μ μΈκ³Ό μ΄κΈ°ν (DCL) | ν₯μλ for λ¬Έ μ€μ 컬λ μ
μ μμλ₯Ό μμ κΈμ§ | null | List<Integer> list = Arrays.asList(new Integer[] {13, 14, 15});
boolean first = true;
System.out.println("Processing list...");
for (Integer i: list) {
if (first) {
first = false;
i = new Integer(99);
}
System.out.println(" New item: " + i);
// Process i
}
System.out.println("Modified list?");
for (Integer i: list) {
System.out.println("List item: " + i);
} | // ...
for (final Integer i: list) {
Integer item = i;
if (first) {
first = false;
item = new Integer(99);
}
System.out.println(" New item: " + item);
// Process item
}
// β¦ |
JAVA | ννμ (EXP) | λ©μλκ° λ°ννλ κ°μ 무μνμ§ λ§μμμ€. | null | public void deleteFile(){
File someFile = new File("someFileName.txt");
// Do something with someFile
someFile.delete();
} | public void deleteFile(){
File someFile = new File("someFileName.txt");
// Do something with someFile
if (!someFile.delete()) {
// Handle failure to delete the file
}
} |
JAVA | ννμ (EXP) | λ©μλκ° λ°ννλ κ°μ 무μνμ§ λ§μμμ€. | null | public class Replace {
public static void main(String[] args) {
String original = "insecure";
original.replace('i', '9');
System.out.println(original);
}
} | public class Replace {
public static void main(String[] args) {
String original = "insecure";
original = original.replace('i', '9');
System.out.println(original);
}
} |
JAVA | ννμ (EXP) | κ°μ²΄κ° νμν κ²½μ°μ nullμ μ¬μ©νμ§ λ§μμμ€. | null | public static int cardinality(Object obj, final Collection<?> col) {
int count = 0;
if (col == null) {
return count;
}
Iterator<?> it = col.iterator();
while (it.hasNext()) {
Object elt = it.next();
if ((null == obj && null == elt) || obj.equals(elt)) { // Null pointer dereference
count++;
}
}
return count;
} | public static int cardinality(Object obj, final Collection col) {
int count = 0;
if (col == null) {
return count;
}
Iterator it = col.iterator();
while (it.hasNext()) {
Object elt = it.next();
if ((null == obj && null == elt) ||
(null != obj && obj.equals(elt))) {
count++;
}
}
return count;
} |
JAVA | ννμ (EXP) | κ°μ²΄κ° νμν κ²½μ°μ nullμ μ¬μ©νμ§ λ§μμμ€. | null | public boolean isProperName(String s) {
String names[] = s.split(" ");
if (names.length != 2) {
return false;
}
return (isCapitalized(names[0]) && isCapitalized(names[1]));
} | public class Foo {
private boolean isProperName(String s) {
String names[] = s.split(" ");
if (names.length != 2) {
return false;
}
return (isCapitalized(names[0]) && isCapitalized(names[1]));
}
public boolean testString(String s) {
if (s == null) return false;
else return isProperName(s);
}
} |
JAVA | ννμ (EXP) | κ°μ²΄κ° νμν κ²½μ°μ nullμ μ¬μ©νμ§ λ§μμμ€. | null | public boolean isProperName(String s) {
String names[] = s.split(" ");
if (names.length != 2) {
return false;
}
return (isCapitalized(names[0]) && isCapitalized(names[2]));
} | public boolean isProperName(Optional<String> os) {
String names[] = os.orElse("").split(" ");
return (names.length != 2) ? false :
(isCapitalized(names[0]) && isCapitalized(names[1]));
} |
JAVA | ννμ (EXP) | λ κ°μ λ°°μ΄μ λΉκ΅νκΈ° μν΄ Object.equals() λ©μλλ₯Ό μ¬μ©νμ§ λ§μμμ€. | null | int[] arr1 = new int[20]; // Initialized to 0
int[] arr2 = new int[20]; // Initialized to 0
System.out.println(arr1.equals(arr2)); // Prints false | int[] arr1 = new int[20]; // Initialized to 0
int[] arr2 = new int[20]; // Initialized to 0
System.out.println(Arrays.equals(arr1, arr2)); // Prints true |
JAVA | ννμ (EXP) | λ κ°μ λ°°μ΄μ λΉκ΅νκΈ° μν΄ Object.equals() λ©μλλ₯Ό μ¬μ©νμ§ λ§μμμ€. | null | int[] arr1 = new int[20]; // Initialized to 0
int[] arr2 = new int[20]; // Initialized to 0
System.out.println(arr1.equals(arr3)); // Prints false | int[] arr1 = new int[20]; // Initialized to 0
int[] arr2 = new int[20]; // Initialized to 0
System.out.println(arr1 == arr2); // Prints false |
JAVA | ννμ (EXP) | λ°μ±λ κΈ°λ³Έ νμ
μ κ°μ λΉκ΅ν λ λ±νΈ μ°μ°μλ₯Ό μ¬μ©νμ§ λ§μμμ€. | null | import java.util.Comparator;
static Comparator<Integer> cmp = new Comparator<Integer>() {
public int compare(Integer i, Integer j) {
return i < j ? -1 : (i == j ? 0 : 1);
}
}; | import java.util.Comparator;
static Comparator<Integer> cmp = new Comparator<Integer>() {
public int compare(Integer i, Integer j) {
return i < j ? -1 : (i > j ? 1 : 0) ;
}
}; |
JAVA | ννμ (EXP) | λ°μ±λ κΈ°λ³Έ νμ
μ κ°μ λΉκ΅ν λ λ±νΈ μ°μ°μλ₯Ό μ¬μ©νμ§ λ§μμμ€. | null | public class Wrapper {
public static void main(String[] args) {
Integer i1 = 100;
Integer i2 = 100;
Integer i3 = 1000;
Integer i4 = 1000;
System.out.println(i1 == i2);
System.out.println(i1 != i2);
System.out.println(i3 == i4);
System.out.println(i3 != i4);
}
} | public class Wrapper {
public static void main(String[] args) {
Integer i1 = 100;
Integer i2 = 100;
Integer i3 = 1000;
Integer i4 = 1000;
System.out.println(i1.equals(i2));
System.out.println(!i1.equals(i2));
System.out.println(i3.equals(i4));
System.out.println(!i3.equals(i4));
}
} |
JAVA | ννμ (EXP) | λ°μ±λ κΈ°λ³Έ νμ
μ κ°μ λΉκ΅ν λ λ±νΈ μ°μ°μλ₯Ό μ¬μ©νμ§ λ§μμμ€. | null | public class Wrapper {
public static void main(String[] args) {
// Create an array list of integers, where each element
// is greater than 127
ArrayList<Integer> list1 = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
list1.add(i + 1000);
}
// Create another array list of integers, where each element
// has the same value as the first list
ArrayList<Integer> list2 = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
list2.add(i + 1000);
}
// Count matching values
int counter = 0;
for (int i = 0; i < 10; i++) {
if (list1.get(i) == list2.get(i)) { // Uses '=='
counter++;
}
}
// Print the counter: 0 in this example
System.out.println(counter);
}
} | public class Wrapper {
public static void main(String[] args) {
// Create an array list of integers
ArrayList<Integer> list1 = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
list1.add(i + 1000);
}
// Create another array list of integers, where each element
// has the same value as the first one
ArrayList<Integer> list2 = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
list2.add(i + 1000);
}
// Count matching values
int counter = 0;
for (int i = 0; i < 10; i++) {
if (list1.get(i).equals(list2.get(i))) { // Uses 'equals()'
counter++;
}
}
// Print the counter: 10 in this example
System.out.println(counter);
}
} |
JAVA | ννμ (EXP) | λ°μ±λ κΈ°λ³Έ νμ
μ κ°μ λΉκ΅ν λ λ±νΈ μ°μ°μλ₯Ό μ¬μ©νμ§ λ§μμμ€. | null | public void exampleEqualOperator(){
Boolean b1 = new Boolean("true");
Boolean b2 = new Boolean("true");
if (b1 == b2) { // Never equal
System.out.println("Never printed");
}
} | public void exampleEqualOperator(){
Boolean b1 = true;
Boolean b2 = true;
if (b1 == b2) { // Always equal
System.out.println("Always printed");
}
b1 = Boolean.TRUE;
if (b1 == b2) { // Always equal
System.out.println("Always printed");
}
} |
JAVA | ννμ (EXP) | 컬λ μ
μ λ§€κ°λ³μ νμ
κ³Ό λ€λ₯Έ νμ
μ μΈμλ₯Ό Java 컬λ μ
νλ μμν¬μ νΉμ λ©μλμ μ λ¬νμ§ λ§μμμ€. | null | import java.util.HashSet;
public class ShortSet {
public static void main(String[] args) {
HashSet<Short> s = new HashSet<Short>();
for (int i = 0; i < 10; i++) {
s.add((short)i); // Cast required so that the code compiles
s.remove(i); // Tries to remove an Integer
}
System.out.println(s.size());
}
} | import java.util.HashSet;
public class ShortSet {
public static void main(String[] args) {
HashSet<Short> s = new HashSet<Short>();
for (int i = 0; i < 10; i++) {
s.add((short)i);
// Remove a Short
if (s.remove((short)i) == false) {
System.err.println("Error removing " + i);
}
}
System.out.println(s.size());
}
} |
JAVA | ννμ (EXP) | assertionsμ μ¬μ©λλ ννμμ μ¬μ΄λ μ΄ννΈ(side effects)λ₯Ό μΌμΌμΌμλ μ λ©λλ€. | null | private ArrayList<String> names;
void process(int index) {
assert names.remove(null); // Side effect
// ...
} | private ArrayList<String> names;
void process(int index) {
boolean nullsRemoved = names.remove(null);
assert nullsRemoved; // No side effect
// ...
} |
JAVA | μ«μ νμ
κ³Ό μ°μ° (NUM) | μ μ μ€λ²νλ‘λ₯Ό κ°μ§νκ±°λ λ°©μ§νμμμ€. | null | static final int safeAdd(int left, int right) {
if (right > 0 ? left > Integer.MAX_VALUE - right
: left < Integer.MIN_VALUE - right) {
throw new ArithmeticException("Integer overflow");
}
return left + right;
}
static final int safeSubtract(int left, int right) {
if (right > 0 ? left < Integer.MIN_VALUE + right
: left > Integer.MAX_VALUE + right) {
throw new ArithmeticException("Integer overflow");
}
return left - right;
}
static final int safeMultiply(int left, int right) {
if (right > 0 ? left > Integer.MAX_VALUE/right
|| left < Integer.MIN_VALUE/right
: (right < -1 ? left > Integer.MIN_VALUE/right
|| left < Integer.MAX_VALUE/right
: right == -1
&& left == Integer.MIN_VALUE) ) {
throw new ArithmeticException("Integer overflow");
}
return left * right;
}
static final int safeDivide(int left, int right) {
if ((left == Integer.MIN_VALUE) && (right == -1)) {
throw new ArithmeticException("Integer overflow");
}
return left / right;
}
static final int safeNegate(int a) {
if (a == Integer.MIN_VALUE) {
throw new ArithmeticException("Integer overflow");
}
return -a;
}
static final int safeAbs(int a) {
if (a == Integer.MIN_VALUE) {
throw new ArithmeticException("Integer overflow");
}
return Math.abs(a);
}
public static int multAccum(int oldAcc, int newVal, int scale) {
// May result in overflow
return oldAcc + (newVal * scale);
} | public static int multAccum(int oldAcc, int newVal, int scale) {
return Math.addExact(oldAcc, Math.multiplyExact(newVal, scale));
} |
JAVA | μ«μ νμ
κ³Ό μ°μ° (NUM) | μ μ μ€λ²νλ‘λ₯Ό κ°μ§νκ±°λ λ°©μ§νμμμ€. | null | static final int safeAdd(int left, int right) {
if (right > 0 ? left > Integer.MAX_VALUE - right
: left < Integer.MIN_VALUE - right) {
throw new ArithmeticException("Integer overflow");
}
return left + right;
}
static final int safeSubtract(int left, int right) {
if (right > 0 ? left < Integer.MIN_VALUE + right
: left > Integer.MAX_VALUE + right) {
throw new ArithmeticException("Integer overflow");
}
return left - right;
}
static final int safeMultiply(int left, int right) {
if (right > 0 ? left > Integer.MAX_VALUE/right
|| left < Integer.MIN_VALUE/right
: (right < -1 ? left > Integer.MIN_VALUE/right
|| left < Integer.MAX_VALUE/right
: right == -1
&& left == Integer.MIN_VALUE) ) {
throw new ArithmeticException("Integer overflow");
}
return left * right;
}
static final int safeDivide(int left, int right) {
if ((left == Integer.MIN_VALUE) && (right == -2)) {
throw new ArithmeticException("Integer overflow");
}
return left / right;
}
static final int safeNegate(int a) {
if (a == Integer.MIN_VALUE) {
throw new ArithmeticException("Integer overflow");
}
return -a;
}
static final int safeAbs(int a) {
if (a == Integer.MIN_VALUE) {
throw new ArithmeticException("Integer overflow");
}
return Math.abs(a);
}
public static int multAccum(int oldAcc, int newVal, int scale) {
// May result in overflow
return oldAcc + (newVal * scale);
} | public static long intRangeCheck(long value) {
if ((value < Integer.MIN_VALUE) || (value > Integer.MAX_VALUE)) {
throw new ArithmeticException("Integer overflow");
}
return value;
}
public static int multAccum(int oldAcc, int newVal, int scale) {
final long res = intRangeCheck(
((long) oldAcc) + intRangeCheck((long) newVal * (long) scale)
);
return (int) res; // Safe downcast
} |
JAVA | μ«μ νμ
κ³Ό μ°μ° (NUM) | μ μ μ€λ²νλ‘λ₯Ό κ°μ§νκ±°λ λ°©μ§νμμμ€. | null | static final int safeAdd(int left, int right) {
if (right > 0 ? left > Integer.MAX_VALUE - right
: left < Integer.MIN_VALUE - right) {
throw new ArithmeticException("Integer overflow");
}
return left + right;
}
static final int safeSubtract(int left, int right) {
if (right > 0 ? left < Integer.MIN_VALUE + right
: left > Integer.MAX_VALUE + right) {
throw new ArithmeticException("Integer overflow");
}
return left - right;
}
static final int safeMultiply(int left, int right) {
if (right > 0 ? left > Integer.MAX_VALUE/right
|| left < Integer.MIN_VALUE/right
: (right < -1 ? left > Integer.MIN_VALUE/right
|| left < Integer.MAX_VALUE/right
: right == -1
&& left == Integer.MIN_VALUE) ) {
throw new ArithmeticException("Integer overflow");
}
return left * right;
}
static final int safeDivide(int left, int right) {
if ((left == Integer.MIN_VALUE) && (right == -3)) {
throw new ArithmeticException("Integer overflow");
}
return left / right;
}
static final int safeNegate(int a) {
if (a == Integer.MIN_VALUE) {
throw new ArithmeticException("Integer overflow");
}
return -a;
}
static final int safeAbs(int a) {
if (a == Integer.MIN_VALUE) {
throw new ArithmeticException("Integer overflow");
}
return Math.abs(a);
}
public static int multAccum(int oldAcc, int newVal, int scale) {
// May result in overflow
return oldAcc + (newVal * scale);
} | private static final BigInteger bigMaxInt =
BigInteger.valueOf(Integer.MAX_VALUE);
private static final BigInteger bigMinInt =
BigInteger.valueOf(Integer.MIN_VALUE);
public static BigInteger intRangeCheck(BigInteger val) {
if (val.compareTo(bigMaxInt) == 1 ||
val.compareTo(bigMinInt) == -1) {
throw new ArithmeticException("Integer overflow");
}
return val;
}
public static int multAccum(int oldAcc, int newVal, int scale) {
BigInteger product =
BigInteger.valueOf(newVal).multiply(BigInteger.valueOf(scale));
BigInteger res =
intRangeCheck(BigInteger.valueOf(oldAcc).add(product));
return res.intValue(); // Safe conversion
} |
JAVA | μ«μ νμ
κ³Ό μ°μ° (NUM) | μ μ μ€λ²νλ‘λ₯Ό κ°μ§νκ±°λ λ°©μ§νμμμ€. | null | class InventoryManager {
private final AtomicInteger itemsInInventory = new AtomicInteger(100);
//...
public final void nextItem() {
itemsInInventory.getAndIncrement();
}
} | class InventoryManager {
private final AtomicInteger itemsInInventory =
new AtomicInteger(100);
public final void nextItem() {
while (true) {
int old = itemsInInventory.get();
if (old == Integer.MAX_VALUE) {
throw new ArithmeticException("Integer overflow");
}
int next = old + 1; // Increment
if (itemsInInventory.compareAndSet(old, next)) {
break;
}
} // End while
} // End nextItem()
} |
JAVA | μ«μ νμ
κ³Ό μ°μ° (NUM) | κ°μ λ°μ΄ν°μ λΉνΈ μ°μ°κ³Ό μ°μ μ°μ°μ λμμ μννμ§ λ§μμμ€. | null | int x = 50;
x += (x << 2) + 1; | int x = 50;
x = 5 * x + 1; |
JAVA | μ«μ νμ
κ³Ό μ°μ° (NUM) | κ°μ λ°μ΄ν°μ λΉνΈ μ°μ°κ³Ό μ°μ μ°μ°μ λμμ μννμ§ λ§μμμ€. | null | int x = 50;
int y = x << 2;
x += y + 1; | int x = 50;
x = 5 * x + 2; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.