JAVA-13856 Create new security-modules (#12622)
This commit is contained in:
+34
@@ -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;
|
||||
|
||||
}
|
||||
+298
@@ -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();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+16
@@ -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;
|
||||
}
|
||||
+14
@@ -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 @@
|
||||
spring.data.jpa.repositories.bootstrap-mode=default
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
+92
@@ -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,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration scan="true" scanPeriod="15 seconds" debug="false">
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -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)
|
||||
);
|
||||
Reference in New Issue
Block a user