This commit is contained in:
Jonathan Cook
2019-10-23 15:01:44 +02:00
parent db85c8f275
commit 684ec0d2e3
20486 changed files with 1642483 additions and 0 deletions
@@ -0,0 +1,25 @@
/target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/build/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
@@ -0,0 +1,3 @@
## Relevant articles:
- [SQL Injection and How to Prevent It?](https://www.baeldung.com/sql-injection)
@@ -0,0 +1,66 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>sql-injection-samples</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>sql-injection-samples</name>
<description>Sample SQL Injection tests</description>
<parent>
<artifactId>parent-boot-2</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,34 @@
/**
*
*/
package com.baeldung.examples.security.sql;
import java.math.BigDecimal;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;
/**
* @author Philippe
*
*/
@Entity
@Table(name="Accounts")
@Data
public class Account {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String customerId;
private String accNumber;
private String branchId;
private BigDecimal balance;
}
@@ -0,0 +1,298 @@
/**
*
*/
package com.baeldung.examples.security.sql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Root;
import javax.persistence.metamodel.SingularAttribute;
import javax.sql.DataSource;
import org.springframework.stereotype.Component;
/**
* @author Philippe
*
*/
@Component
public class AccountDAO {
private final DataSource dataSource;
private final EntityManager em;
public AccountDAO(DataSource dataSource, EntityManager em) {
this.dataSource = dataSource;
this.em = em;
}
/**
* Return all accounts owned by a given customer,given his/her external id
*
* @param customerId
* @return
*/
public List<AccountDTO> unsafeFindAccountsByCustomerId(String customerId) {
String sql = "select " + "customer_id,acc_number,branch_id,balance from Accounts where customer_id = '" + customerId + "'";
try (Connection c = dataSource.getConnection();
ResultSet rs = c.createStatement()
.executeQuery(sql)) {
List<AccountDTO> accounts = new ArrayList<>();
while (rs.next()) {
AccountDTO acc = AccountDTO.builder()
.customerId(rs.getString("customer_id"))
.branchId(rs.getString("branch_id"))
.accNumber(rs.getString("acc_number"))
.balance(rs.getBigDecimal("balance"))
.build();
accounts.add(acc);
}
return accounts;
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
/**
* Return all accounts owned by a given customer,given his/her external id - JPA version
*
* @param customerId
* @return
*/
public List<AccountDTO> unsafeJpaFindAccountsByCustomerId(String customerId) {
String jql = "from Account where customerId = '" + customerId + "'";
TypedQuery<Account> q = em.createQuery(jql, Account.class);
return q.getResultList()
.stream()
.map(a -> AccountDTO.builder()
.accNumber(a.getAccNumber())
.balance(a.getBalance())
.branchId(a.getAccNumber())
.customerId(a.getCustomerId())
.build())
.collect(Collectors.toList());
}
/**
* Return all accounts owned by a given customer,given his/her external id
*
* @param customerId
* @return
*/
public List<AccountDTO> safeFindAccountsByCustomerId(String customerId) {
String sql = "select customer_id, branch_id,acc_number,balance from Accounts where customer_id = ?";
try (Connection c = dataSource.getConnection(); PreparedStatement p = c.prepareStatement(sql)) {
p.setString(1, customerId);
ResultSet rs = p.executeQuery();
List<AccountDTO> accounts = new ArrayList<>();
while (rs.next()) {
AccountDTO acc = AccountDTO.builder()
.customerId(rs.getString("customerId"))
.branchId(rs.getString("branch_id"))
.accNumber(rs.getString("acc_number"))
.balance(rs.getBigDecimal("balance"))
.build();
accounts.add(acc);
}
return accounts;
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
/**
* Return all accounts owned by a given customer,given his/her external id - JPA version
*
* @param customerId
* @return
*/
public List<AccountDTO> safeJpaFindAccountsByCustomerId(String customerId) {
String jql = "from Account where customerId = :customerId";
TypedQuery<Account> q = em.createQuery(jql, Account.class)
.setParameter("customerId", customerId);
return q.getResultList()
.stream()
.map(a -> AccountDTO.builder()
.accNumber(a.getAccNumber())
.balance(a.getBalance())
.branchId(a.getAccNumber())
.customerId(a.getCustomerId())
.build())
.collect(Collectors.toList());
}
/**
* Return all accounts owned by a given customer,given his/her external id - JPA version
*
* @param customerId
* @return
*/
public List<AccountDTO> safeJpaCriteriaFindAccountsByCustomerId(String customerId) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Account> cq = cb.createQuery(Account.class);
Root<Account> root = cq.from(Account.class);
cq.select(root)
.where(cb.equal(root.get(Account_.customerId), customerId));
TypedQuery<Account> q = em.createQuery(cq);
return q.getResultList()
.stream()
.map(a -> AccountDTO.builder()
.accNumber(a.getAccNumber())
.balance(a.getBalance())
.branchId(a.getAccNumber())
.customerId(a.getCustomerId())
.build())
.collect(Collectors.toList());
}
private static final Set<String> VALID_COLUMNS_FOR_ORDER_BY = Stream.of("acc_number", "branch_id", "balance")
.collect(Collectors.toCollection(HashSet::new));
/**
* Return all accounts owned by a given customer,given his/her external id
*
* @param customerId
* @return
*/
public List<AccountDTO> safeFindAccountsByCustomerId(String customerId, String orderBy) {
String sql = "select " + "customer_id,acc_number,branch_id,balance from Accounts where customer_id = ? ";
if (VALID_COLUMNS_FOR_ORDER_BY.contains(orderBy)) {
sql = sql + " order by " + orderBy;
} else {
throw new IllegalArgumentException("Nice try!");
}
try (Connection c = dataSource.getConnection(); PreparedStatement p = c.prepareStatement(sql)) {
p.setString(1, customerId);
ResultSet rs = p.executeQuery();
List<AccountDTO> accounts = new ArrayList<>();
while (rs.next()) {
AccountDTO acc = AccountDTO.builder()
.customerId(rs.getString("customerId"))
.branchId(rs.getString("branch_id"))
.accNumber(rs.getString("acc_number"))
.balance(rs.getBigDecimal("balance"))
.build();
accounts.add(acc);
}
return accounts;
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
private static final Map<String,SingularAttribute<Account,?>> VALID_JPA_COLUMNS_FOR_ORDER_BY = Stream.of(
new AbstractMap.SimpleEntry<>(Account_.ACC_NUMBER, Account_.accNumber),
new AbstractMap.SimpleEntry<>(Account_.BRANCH_ID, Account_.branchId),
new AbstractMap.SimpleEntry<>(Account_.BALANCE, Account_.balance)
)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
/**
* Return all accounts owned by a given customer,given his/her external id
*
* @param customerId
* @return
*/
public List<AccountDTO> safeJpaFindAccountsByCustomerId(String customerId, String orderBy) {
SingularAttribute<Account,?> orderByAttribute = VALID_JPA_COLUMNS_FOR_ORDER_BY.get(orderBy);
if ( orderByAttribute == null) {
throw new IllegalArgumentException("Nice try!");
}
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Account> cq = cb.createQuery(Account.class);
Root<Account> root = cq.from(Account.class);
cq.select(root)
.where(cb.equal(root.get(Account_.customerId), customerId))
.orderBy(cb.asc(root.get(orderByAttribute)));
TypedQuery<Account> q = em.createQuery(cq);
return q.getResultList()
.stream()
.map(a -> AccountDTO.builder()
.accNumber(a.getAccNumber())
.balance(a.getBalance())
.branchId(a.getAccNumber())
.customerId(a.getCustomerId())
.build())
.collect(Collectors.toList());
}
/**
* Invalid placeholder usage example
*
* @param tableName
* @return
*/
public Long wrongCountRecordsByTableName(String tableName) {
try (Connection c = dataSource.getConnection(); PreparedStatement p = c.prepareStatement("select count(*) from ?")) {
p.setString(1, tableName);
ResultSet rs = p.executeQuery();
rs.next();
return rs.getLong(1);
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
/**
* Invalid placeholder usage example - JPA
*
* @param tableName
* @return
*/
public Long wrongJpaCountRecordsByTableName(String tableName) {
String jql = "select count(*) from :tableName";
TypedQuery<Long> q = em.createQuery(jql, Long.class)
.setParameter("tableName", tableName);
return q.getSingleResult();
}
}
@@ -0,0 +1,16 @@
package com.baeldung.examples.security.sql;
import java.math.BigDecimal;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class AccountDTO {
private String customerId;
private String accNumber;
private String branchId;
private BigDecimal balance;
}
@@ -0,0 +1,14 @@
package com.baeldung.examples.security.sql;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SqlInjectionSamplesApplication {
public static void main(String[] args) {
SpringApplication.run(SqlInjectionSamplesApplication.class, args);
}
}
@@ -0,0 +1,92 @@
package com.baeldung.examples.security.sql;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.examples.security.sql.AccountDAO;
import com.baeldung.examples.security.sql.AccountDTO;
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles({ "test" })
public class SqlInjectionSamplesApplicationUnitTest {
@Autowired
private AccountDAO target;
@Test
public void givenAVulnerableMethod_whenValidCustomerId_thenReturnSingleAccount() {
List<AccountDTO> accounts = target.unsafeFindAccountsByCustomerId("C1");
assertThat(accounts).isNotNull();
assertThat(accounts).isNotEmpty();
assertThat(accounts).hasSize(1);
}
@Test
public void givenAVulnerableMethod_whenHackedCustomerId_thenReturnAllAccounts() {
List<AccountDTO> accounts = target.unsafeFindAccountsByCustomerId("C1' or '1'='1");
assertThat(accounts).isNotNull();
assertThat(accounts).isNotEmpty();
assertThat(accounts).hasSize(3);
}
@Test
public void givenAVulnerableJpaMethod_whenHackedCustomerId_thenReturnAllAccounts() {
List<AccountDTO> accounts = target.unsafeJpaFindAccountsByCustomerId("C1' or '1'='1");
assertThat(accounts).isNotNull();
assertThat(accounts).isNotEmpty();
assertThat(accounts).hasSize(3);
}
@Test
public void givenASafeMethod_whenHackedCustomerId_thenReturnNoAccounts() {
List<AccountDTO> accounts = target.safeFindAccountsByCustomerId("C1' or '1'='1");
assertThat(accounts).isNotNull();
assertThat(accounts).isEmpty();
}
@Test
public void givenASafeJpaMethod_whenHackedCustomerId_thenReturnNoAccounts() {
List<AccountDTO> accounts = target.safeJpaFindAccountsByCustomerId("C1' or '1'='1");
assertThat(accounts).isNotNull();
assertThat(accounts).isEmpty();
}
@Test
public void givenASafeJpaCriteriaMethod_whenHackedCustomerId_thenReturnNoAccounts() {
List<AccountDTO> accounts = target.safeJpaCriteriaFindAccountsByCustomerId("C1' or '1'='1");
assertThat(accounts).isNotNull();
assertThat(accounts).isEmpty();
}
@Test(expected = IllegalArgumentException.class)
public void givenASafeMethod_whenInvalidOrderBy_thenThroweException() {
target.safeFindAccountsByCustomerId("C1", "INVALID");
}
@Test(expected = Exception.class)
public void givenWrongPlaceholderUsageMethod_whenNormalCall_thenThrowsException() {
target.wrongCountRecordsByTableName("Accounts");
}
@Test(expected = Exception.class)
public void givenWrongJpaPlaceholderUsageMethod_whenNormalCall_thenThrowsException() {
target.wrongJpaCountRecordsByTableName("Accounts");
}
}
@@ -0,0 +1,18 @@
#
# Test profile configuration
#
spring:
liquibase:
change-log: db/changelog/db.changelog-master.xml
jpa:
hibernate:
ddl-auto: none
datasource:
initialization-mode: embedded
logging:
level:
sql: DEBUG
@@ -0,0 +1,4 @@
insert into Accounts(customer_id,acc_number,branch_id,balance) values ('C1','0001',1,1000.00);
insert into Accounts(customer_id,acc_number,branch_id,balance) values ('C2','0002',1,500.00);
insert into Accounts(customer_id,acc_number,branch_id,balance) values ('C3','0003',1,501.00);
@@ -0,0 +1,7 @@
create table Accounts (
id BIGINT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
customer_id varchar(16) not null,
acc_number varchar(16) not null,
branch_id decimal(8,0),
balance decimal(16,4)
);