or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

datasource-configuration.mdindex.mdmonitoring-statistics.mdsecurity-filtering.mdsql-processing.md

security-filtering.mddocs/

0

# Security Filtering

1

2

Advanced SQL injection protection and security filtering system with configurable policies, database-specific rules, and comprehensive validation capabilities through the WallFilter framework.

3

4

## Core Security Components

5

6

### WallFilter - Main Security Filter

7

8

```java { .api }

9

// Main security filter class

10

class WallFilter extends FilterAdapter implements WallFilterMBean {

11

// Constructors

12

public WallFilter();

13

public WallFilter(Properties properties);

14

15

// Configuration

16

public void configFromProperties(Properties properties);

17

public synchronized void init(DataSourceProxy dataSource);

18

19

// Security behavior

20

public boolean isLogViolation();

21

public void setLogViolation(boolean logViolation);

22

public boolean isThrowException();

23

public void setThrowException(boolean throwException);

24

public String getDbType();

25

public void setDbType(String dbType);

26

public void setDbType(DbType dbType);

27

28

// Provider and configuration access

29

public WallProvider getProvider();

30

public WallConfig getConfig();

31

public void setConfig(WallConfig config);

32

33

// SQL validation

34

public String check(String sql) throws SQLException;

35

public boolean checkValid(String sql);

36

37

// Statistics and management

38

public long getViolationCount();

39

public void resetViolationCount();

40

public void clearProviderCache();

41

public Set<String> getProviderWhiteList();

42

public void clearWhiteList();

43

}

44

```

45

46

### WallConfig - Security Policy Configuration

47

48

```java { .api }

49

// Security configuration class

50

class WallConfig implements WallConfigMBean {

51

// Statement type controls

52

public boolean isSelectAllow();

53

public void setSelectAllow(boolean selectAllow);

54

public boolean isInsertAllow();

55

public void setInsertAllow(boolean insertAllow);

56

public boolean isUpdateAllow();

57

public void setUpdateAllow(boolean updateAllow);

58

public boolean isDeleteAllow();

59

public void setDeleteAllow(boolean deleteAllow);

60

61

// DDL controls

62

public boolean isCreateTableAllow();

63

public void setCreateTableAllow(boolean createTableAllow);

64

public boolean isDropTableAllow();

65

public void setDropTableAllow(boolean dropTableAllow);

66

public boolean isAlterTableAllow();

67

public void setAlterTableAllow(boolean alterTableAllow);

68

public boolean isTruncateAllow();

69

public void setTruncateAllow(boolean truncateAllow);

70

71

// Security checks

72

public boolean isSelectWhereAlwayTrueCheck();

73

public void setSelectWhereAlwayTrueCheck(boolean selectWhereAlwayTrueCheck);

74

public boolean isUpdateWhereAlwayTrueCheck();

75

public void setUpdateWhereAlwayTrueCheck(boolean updateWhereAlwayTrueCheck);

76

public boolean isDeleteWhereAlwayTrueCheck();

77

public void setDeleteWhereAlwayTrueCheck(boolean deleteWhereAlwayTrueCheck);

78

79

// Syntax and features

80

public boolean isCommentAllow();

81

public void setCommentAllow(boolean commentAllow);

82

public boolean isMultiStatementAllow();

83

public void setMultiStatementAllow(boolean multiStatementAllow);

84

public boolean isStrictSyntaxCheck();

85

public void setStrictSyntaxCheck(boolean strictSyntaxCheck);

86

87

// Access controls

88

public Set<String> getDenyFunctions();

89

public Set<String> getDenyTables();

90

public Set<String> getDenySchemas();

91

public Set<String> getPermitFunctions();

92

public Set<String> getPermitTables();

93

public Set<String> getReadOnlyTables();

94

95

// Advanced features

96

public boolean isMustParameterized();

97

public void setMustParameterized(boolean mustParameterized);

98

public int getSelectLimit();

99

public void setSelectLimit(int selectLimit);

100

public void configFromProperties(Properties properties);

101

}

102

```

103

104

## Basic Security Setup

105

106

### Simple Security Configuration

107

108

```java

109

import com.alibaba.druid.wall.WallFilter;

110

import com.alibaba.druid.wall.WallConfig;

111

import com.alibaba.druid.pool.DruidDataSource;

112

113

// Create and configure WallFilter

114

WallFilter wallFilter = new WallFilter();

115

wallFilter.setDbType("mysql");

116

wallFilter.setLogViolation(true);

117

wallFilter.setThrowException(true);

118

119

// Configure security policies

120

WallConfig config = new WallConfig();

121

config.setMultiStatementAllow(false);

122

config.setSelectWhereAlwayTrueCheck(true);

123

config.setUpdateWhereAlwayTrueCheck(true);

124

config.setDeleteWhereAlwayTrueCheck(true);

125

config.setCommentAllow(false);

126

127

wallFilter.setConfig(config);

128

129

// Integrate with DataSource

130

DruidDataSource dataSource = new DruidDataSource();

131

dataSource.getProxyFilters().add(wallFilter);

132

// or via filters string

133

dataSource.setFilters("wall");

134

```

135

136

### Properties-Based Configuration

137

138

```java

139

// Configure via Properties

140

Properties config = new Properties();

141

config.setProperty("druid.wall.logViolation", "true");

142

config.setProperty("druid.wall.throwException", "true");

143

config.setProperty("druid.wall.selectAllow", "true");

144

config.setProperty("druid.wall.updateAllow", "true");

145

config.setProperty("druid.wall.deleteAllow", "true");

146

config.setProperty("druid.wall.insertAllow", "true");

147

config.setProperty("druid.wall.multiStatementAllow", "false");

148

config.setProperty("druid.wall.selectLimit", "1000");

149

150

WallFilter wallFilter = new WallFilter(config);

151

```

152

153

## Security Policy Configuration

154

155

### Statement Type Controls

156

157

```java

158

WallConfig config = new WallConfig();

159

160

// Basic DML controls

161

config.setSelectAllow(true); // Allow SELECT statements

162

config.setInsertAllow(true); // Allow INSERT statements

163

config.setUpdateAllow(true); // Allow UPDATE statements

164

config.setDeleteAllow(false); // Deny DELETE statements

165

166

// DDL controls

167

config.setCreateTableAllow(false); // Deny CREATE TABLE

168

config.setDropTableAllow(false); // Deny DROP TABLE

169

config.setAlterTableAllow(false); // Deny ALTER TABLE

170

config.setTruncateAllow(false); // Deny TRUNCATE

171

172

// Apply configuration

173

wallFilter.setConfig(config);

174

```

175

176

### SQL Injection Protection

177

178

```java

179

// Configure injection protection checks

180

config.setSelectWhereAlwayTrueCheck(true); // Detect "WHERE 1=1" patterns

181

config.setUpdateWhereAlwayTrueCheck(true); // Detect unsafe UPDATE conditions

182

config.setDeleteWhereAlwayTrueCheck(true); // Detect unsafe DELETE conditions

183

184

// Union and set operation controls

185

config.setSelectUnionCheck(true); // Check UNION operations

186

config.setMinusAllow(false); // Deny MINUS operations

187

config.setIntersectAllow(true); // Allow INTERSECT operations

188

189

// Syntax and structure controls

190

config.setStrictSyntaxCheck(true); // Enable strict syntax validation

191

config.setMultiStatementAllow(false); // Deny multiple statements

192

config.setCommentAllow(false); // Deny SQL comments

193

```

194

195

### Access Control Lists

196

197

```java

198

// Function blacklist/whitelist

199

Set<String> denyFunctions = config.getDenyFunctions();

200

denyFunctions.add("version");

201

denyFunctions.add("database");

202

denyFunctions.add("user");

203

denyFunctions.add("benchmark");

204

denyFunctions.add("sleep");

205

206

// Table access controls

207

Set<String> denyTables = config.getDenyTables();

208

denyTables.add("sys");

209

denyTables.add("information_schema");

210

211

Set<String> readOnlyTables = config.getReadOnlyTables();

212

readOnlyTables.add("users");

213

readOnlyTables.add("audit_log");

214

215

// Schema restrictions

216

Set<String> denySchemas = config.getDenySchemas();

217

denySchemas.add("mysql");

218

denySchemas.add("performance_schema");

219

```

220

221

## Database-Specific Security

222

223

### WallProvider - Database-Specific Rules

224

225

```java { .api }

226

// Base provider interface

227

abstract class WallProvider {

228

public WallCheckResult check(String sql);

229

public boolean checkValid(String sql);

230

public WallConfig getConfig();

231

232

// Statistics and management

233

public long getCheckCount();

234

public long getViolationCount();

235

public long getWhiteListHitCount();

236

public long getBlackListHitCount();

237

public void clearCache();

238

public void clearWhiteList();

239

public Set<String> getWhiteList();

240

public Set<String> getBlackList();

241

242

// Security checks

243

public boolean checkDenyFunction(String functionName);

244

public boolean checkDenySchema(String schemaName);

245

public boolean checkDenyTable(String tableName);

246

public boolean checkReadOnlyTable(String tableName);

247

}

248

```

249

250

### Database-Specific Configurations

251

252

```java

253

// MySQL-specific security

254

WallFilter mysqlWall = new WallFilter();

255

mysqlWall.setDbType(DbType.mysql);

256

// Uses MySqlWallProvider with MySQL-specific rules

257

258

// Oracle-specific security

259

WallFilter oracleWall = new WallFilter();

260

oracleWall.setDbType(DbType.oracle);

261

// Uses OracleWallProvider with Oracle-specific rules

262

263

// PostgreSQL-specific security

264

WallFilter pgWall = new WallFilter();

265

pgWall.setDbType(DbType.postgresql);

266

// Uses PGWallProvider with PostgreSQL-specific rules

267

```

268

269

## Security Validation

270

271

### WallUtils - Validation Utilities

272

273

```java { .api }

274

// Validation utility methods

275

class WallUtils {

276

// MySQL validation

277

static boolean isValidateMySql(String sql);

278

static boolean isValidateMySql(String sql, WallConfig config);

279

280

// Oracle validation

281

static boolean isValidateOracle(String sql);

282

static boolean isValidateOracle(String sql, WallConfig config);

283

284

// PostgreSQL validation

285

static boolean isValidatePostgres(String sql);

286

static boolean isValidatePostgres(String sql, WallConfig config);

287

288

// SQL Server validation

289

static boolean isValidateSqlServer(String sql);

290

static boolean isValidateSqlServer(String sql, WallConfig config);

291

292

// DB2 validation

293

static boolean isValidateDB2(String sql);

294

static boolean isValidateDB2(String sql, WallConfig config);

295

}

296

```

297

298

### Validation Examples

299

300

```java

301

import com.alibaba.druid.wall.WallUtils;

302

import com.alibaba.druid.wall.WallConfig;

303

304

// Basic validation

305

boolean valid = WallUtils.isValidateMySql("SELECT * FROM users WHERE id = ?");

306

// Returns: true (parameterized query is safe)

307

308

boolean invalid = WallUtils.isValidateMySql("SELECT * FROM users WHERE 1=1");

309

// Returns: false (always true condition detected)

310

311

// Custom configuration validation

312

WallConfig config = new WallConfig();

313

config.setSelectAllow(true);

314

config.setMultiStatementAllow(false);

315

config.setSelectWhereAlwayTrueCheck(true);

316

317

boolean result = WallUtils.isValidateMySql(

318

"SELECT * FROM users; DROP TABLE users;", config);

319

// Returns: false (multiple statements not allowed)

320

```

321

322

### Security Check Results

323

324

```java { .api }

325

// Security validation result

326

class WallCheckResult {

327

public String getSql();

328

public List<Violation> getViolations();

329

public List<SQLStatement> getStatementList();

330

public boolean isSyntaxError();

331

332

// Statistics

333

public Map<String, WallSqlTableStat> getTableStats();

334

public Map<String, WallSqlFunctionStat> getFunctionStats();

335

public WallSqlStat getSqlStat();

336

}

337

```

338

339

## Advanced Security Features

340

341

### Multi-Tenant Security Support

342

343

```java { .api }

344

// Multi-tenant configuration

345

void setTenantColumn(String tenantColumn);

346

String getTenantColumn();

347

void setTenantTablePattern(String tenantTablePattern);

348

String getTenantTablePattern();

349

void setTenantCallBack(TenantCallBack tenantCallBack);

350

TenantCallBack getTenantCallBack();

351

```

352

353

### Multi-Tenant Usage

354

355

```java

356

// Configure multi-tenant security

357

WallConfig config = new WallConfig();

358

config.setTenantColumn("tenant_id");

359

config.setTenantTablePattern(".*"); // Apply to all tables

360

361

// Custom tenant callback

362

config.setTenantCallBack(new TenantCallBack() {

363

@Override

364

public String getTenantValue() {

365

// Return current tenant ID from context

366

return getCurrentTenantId();

367

}

368

});

369

370

wallFilter.setConfig(config);

371

```

372

373

### Update Check Support

374

375

```java

376

// Configure update validation

377

WallConfig config = new WallConfig();

378

config.addUpdateCheckColumns("users.email,users.phone");

379

config.addUpdateCheckColumns("orders.status");

380

381

// Custom update check handler

382

config.setUpdateCheckHandler(new WallUpdateCheckHandler() {

383

@Override

384

public void checkUpdate(WallUpdateCheckItem item) throws SQLException {

385

// Custom validation logic

386

if (item.getColumn().equals("email")) {

387

validateEmailUpdate(item);

388

}

389

}

390

});

391

```

392

393

## Security Exception Handling

394

395

### Exception Types

396

397

```java { .api }

398

// Main security exception

399

class WallSQLException extends SQLException {

400

public WallSQLException(String reason);

401

public WallSQLException(String reason, Throwable cause);

402

}

403

404

// Violation types

405

interface Violation {

406

String getMessage();

407

int getErrorCode();

408

}

409

410

class IllegalSQLObjectViolation implements Violation {

411

public String getMessage();

412

public int getErrorCode();

413

}

414

```

415

416

### Error Codes and Handling

417

418

```java

419

// Common error codes

420

public interface ErrorCode {

421

int SYNTAX_ERROR = 1001; // SQL syntax errors

422

int SELECT_NOT_ALLOW = 1002; // SELECT not allowed

423

int INSERT_NOT_ALLOW = 1004; // INSERT not allowed

424

int DELETE_NOT_ALLOW = 1005; // DELETE not allowed

425

int UPDATE_NOT_ALLOW = 1006; // UPDATE not allowed

426

int FUNCTION_DENY = 2001; // Denied function

427

int SCHEMA_DENY = 2002; // Denied schema

428

int TABLE_DENY = 2004; // Denied table

429

int ALWAYS_TRUE = 2100; // Always true condition

430

int MULTI_STATEMENT = 2201; // Multiple statements

431

}

432

433

// Exception handling example

434

try {

435

Connection conn = dataSource.getConnection();

436

PreparedStatement stmt = conn.prepareStatement(sql);

437

// ... execute statement

438

} catch (WallSQLException e) {

439

int errorCode = e.getErrorCode();

440

switch (errorCode) {

441

case ErrorCode.ALWAYS_TRUE:

442

log.warn("SQL injection attempt detected: " + e.getMessage());

443

break;

444

case ErrorCode.FUNCTION_DENY:

445

log.warn("Unauthorized function usage: " + e.getMessage());

446

break;

447

default:

448

log.error("Security violation: " + e.getMessage());

449

}

450

}

451

```

452

453

## Security Statistics and Monitoring

454

455

### Statistics Collection

456

457

```java

458

// Access security statistics

459

WallFilter wallFilter = getWallFilter();

460

long violationCount = wallFilter.getViolationCount();

461

long checkCount = wallFilter.getProvider().getCheckCount();

462

long whiteListHits = wallFilter.getProvider().getWhiteListHitCount();

463

long blackListHits = wallFilter.getProvider().getBlackListHitCount();

464

465

// Table and function statistics

466

Map<String, WallTableStat> tableStats = wallFilter.getProvider().getTableStats();

467

Map<String, WallFunctionStat> functionStats = wallFilter.getProvider().getFunctionStats();

468

469

// Reset statistics

470

wallFilter.resetViolationCount();

471

wallFilter.getProvider().reset();

472

```

473

474

### Cache Management

475

476

```java

477

// Cache operations

478

Set<String> whiteList = wallFilter.getProvider().getWhiteList();

479

Set<String> blackList = wallFilter.getProvider().getBlackList();

480

481

// Clear caches

482

wallFilter.clearProviderCache();

483

wallFilter.getProvider().clearWhiteList();

484

wallFilter.getProvider().clearBlackList();

485

wallFilter.getProvider().clearCache();

486

```

487

488

## Complete Security Configuration Example

489

490

```java

491

import com.alibaba.druid.wall.WallFilter;

492

import com.alibaba.druid.wall.WallConfig;

493

import com.alibaba.druid.pool.DruidDataSource;

494

import com.alibaba.druid.DbType;

495

496

public class DruidSecurityConfiguration {

497

498

public static DruidDataSource createSecureDataSource() {

499

// Create DataSource

500

DruidDataSource dataSource = new DruidDataSource();

501

dataSource.setUrl("jdbc:mysql://localhost:3306/mydb");

502

dataSource.setUsername("dbuser");

503

dataSource.setPassword("dbpass");

504

505

// Create WallFilter

506

WallFilter wallFilter = new WallFilter();

507

wallFilter.setDbType(DbType.mysql);

508

wallFilter.setLogViolation(true);

509

wallFilter.setThrowException(true);

510

511

// Configure security policies

512

WallConfig config = new WallConfig();

513

514

// Statement controls

515

config.setSelectAllow(true);

516

config.setInsertAllow(true);

517

config.setUpdateAllow(true);

518

config.setDeleteAllow(true);

519

config.setCreateTableAllow(false); // Deny DDL

520

config.setDropTableAllow(false);

521

config.setAlterTableAllow(false);

522

523

// Injection protection

524

config.setSelectWhereAlwayTrueCheck(true);

525

config.setUpdateWhereAlwayTrueCheck(true);

526

config.setDeleteWhereAlwayTrueCheck(true);

527

config.setMultiStatementAllow(false);

528

config.setCommentAllow(false);

529

config.setStrictSyntaxCheck(true);

530

531

// Function restrictions

532

config.getDenyFunctions().addAll(Arrays.asList(

533

"version", "database", "user", "benchmark", "sleep", "load_file"

534

));

535

536

// Table restrictions

537

config.getDenyTables().addAll(Arrays.asList(

538

"information_schema", "mysql", "performance_schema", "sys"

539

));

540

541

// Read-only tables

542

config.getReadOnlyTables().addAll(Arrays.asList(

543

"audit_log", "system_config"

544

));

545

546

// Advanced features

547

config.setSelectLimit(10000); // Limit result set size

548

config.setMustParameterized(true); // Require parameterized queries

549

550

wallFilter.setConfig(config);

551

552

// Add filter to DataSource

553

dataSource.getProxyFilters().add(wallFilter);

554

555

return dataSource;

556

}

557

}

558

```

559

560

This comprehensive security framework provides enterprise-grade SQL injection protection through configurable policies, database-specific rules, access controls, and detailed monitoring capabilities.