MycatPrivileges.java
10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
/*
* Copyright (c) 2013, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software;Designed and Developed mainly by many Chinese
* opensource volunteers. you can redistribute it and/or modify it under the
* terms of the GNU General Public License version 2 only, as published by the
* Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Any questions about this component can be directed to it's project Web address
* https://code.google.com/p/opencloudb/.
*
*/
package io.mycat.config;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import io.mycat.config.loader.xml.XMLServerLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.ast.statement.SQLDeleteStatement;
import com.alibaba.druid.sql.ast.statement.SQLInsertStatement;
import com.alibaba.druid.sql.ast.statement.SQLSelectStatement;
import com.alibaba.druid.sql.ast.statement.SQLShowTablesStatement;
import com.alibaba.druid.sql.ast.statement.SQLUpdateStatement;
import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlReplaceStatement;
import com.alibaba.druid.sql.parser.SQLStatementParser;
import com.alibaba.druid.sql.visitor.SchemaStatVisitor;
import com.alibaba.druid.wall.WallCheckResult;
import com.alibaba.druid.wall.WallProvider;
import io.mycat.MycatServer;
import io.mycat.config.model.FirewallConfig;
import io.mycat.config.model.UserConfig;
import io.mycat.config.model.UserPrivilegesConfig;
import io.mycat.net.handler.FrontendPrivileges;
import io.mycat.route.parser.druid.MycatSchemaStatVisitor;
import io.mycat.route.parser.druid.MycatStatementParser;
/**
* @author mycat
*/
public class MycatPrivileges implements FrontendPrivileges {
/**
* 无需每次建立连接都new实例。
*/
private static MycatPrivileges instance = new MycatPrivileges();
private static final Logger ALARM = LoggerFactory.getLogger("alarm");
private static boolean check = false;
private final static ThreadLocal<WallProvider> contextLocal = new ThreadLocal<WallProvider>();
public static MycatPrivileges instance() {
return instance;
}
private MycatPrivileges() {
super();
}
@Override
public boolean schemaExists(String schema) {
MycatConfig conf = MycatServer.getInstance().getConfig();
return conf.getSchemas().containsKey(schema);
}
@Override
public boolean userExists(String user, String host) {
//检查用户及白名单
return checkFirewallWhiteHostPolicy(user, host);
}
@Override
public String getPassword(String user) {
MycatConfig conf = MycatServer.getInstance().getConfig();
if (user != null && user.equals(conf.getSystem().getClusterHeartbeatUser())) {
return conf.getSystem().getClusterHeartbeatPass();
} else {
UserConfig uc = conf.getUsers().get(user);
if (uc != null) {
return uc.getPassword();
} else {
return null;
}
}
}
@Override
public Set<String> getUserSchemas(String user) {
MycatConfig conf = MycatServer.getInstance().getConfig();
UserConfig uc = conf.getUsers().get(user);
if (uc != null) {
return uc.getSchemas();
} else {
return null;
}
}
@Override
public Boolean isReadOnly(String user) {
MycatConfig conf = MycatServer.getInstance().getConfig();
UserConfig uc = conf.getUsers().get(user);
if (uc != null) {
return uc.isReadOnly();
} else {
return null;
}
}
@Override
public int getBenchmark(String user) {
MycatConfig conf = MycatServer.getInstance().getConfig();
UserConfig uc = conf.getUsers().get(user);
if (uc != null) {
return uc.getBenchmark();
} else {
return 0;
}
}
/**
* 防火墙白名单处理,根据防火墙配置,判断目前主机是否可以通过某用户登陆
* 白名单配置请参考:
* @see XMLServerLoader
* @see FirewallConfig
*
* @modification 修改增加网段白名单识别配置
* @date 2016/12/8
* @modifiedBy Hash Zhang
*/
@Override
public boolean checkFirewallWhiteHostPolicy(String user, String host) {
MycatConfig mycatConfig = MycatServer.getInstance().getConfig();
FirewallConfig firewallConfig = mycatConfig.getFirewall();
//防火墙 白名单处理
boolean isPassed = false;
Map<String, List<UserConfig>> whitehost = firewallConfig.getWhitehost();
Map<Pattern, List<UserConfig>> whitehostMask = firewallConfig.getWhitehostMask();
if ((whitehost == null || whitehost.size() == 0)&&(whitehostMask == null || whitehostMask.size() == 0)) {
Map<String, UserConfig> users = mycatConfig.getUsers();
isPassed = users.containsKey(user);
} else {
List<UserConfig> list = whitehost.get(host);
Set<Pattern> patterns = whitehostMask.keySet();
if(patterns != null && patterns.size() > 0){
for(Pattern pattern : patterns) {
if(pattern.matcher(host).find()){
isPassed = true;
break;
}
}
}
if (list != null) {
for (UserConfig userConfig : list) {
if (userConfig.getName().equals(user)) {
isPassed = true;
break;
}
}
}
}
if ( !isPassed ) {
ALARM.error(new StringBuilder().append(Alarms.FIREWALL_ATTACK).append("[host=").append(host)
.append(",user=").append(user).append(']').toString());
return false;
}
return true;
}
/**
* @see https://github.com/alibaba/druid/wiki/%E9%85%8D%E7%BD%AE-wallfilter
*/
@Override
public boolean checkFirewallSQLPolicy(String user, String sql) {
boolean isPassed = true;
if( contextLocal.get() == null ){
FirewallConfig firewallConfig = MycatServer.getInstance().getConfig().getFirewall();
if ( firewallConfig != null) {
if ( firewallConfig.isCheck() ) {
contextLocal.set(firewallConfig.getProvider());
check = true;
}
}
}
if( check ){
WallCheckResult result = contextLocal.get().check(sql);
// 修复 druid 防火墙在处理SHOW FULL TABLES WHERE Table_type != 'VIEW' 的时候存在的 BUG
List<SQLStatement> stmts = result.getStatementList();
if ( !stmts.isEmpty() && !( stmts.get(0) instanceof SQLShowTablesStatement) ) {
if ( !result.getViolations().isEmpty()) {
isPassed = false;
ALARM.warn("Firewall to intercept the '" + user + "' unsafe SQL , errMsg:"
+ result.getViolations().get(0).getMessage() +
" \r\n " + sql);
}
}
}
return isPassed;
}
// 审计SQL权限
@Override
public boolean checkDmlPrivilege(String user, String schema, String sql) {
if ( schema == null ) {
return true;
}
boolean isPassed = false;
MycatConfig conf = MycatServer.getInstance().getConfig();
UserConfig userConfig = conf.getUsers().get(user);
if (userConfig != null) {
UserPrivilegesConfig userPrivilege = userConfig.getPrivilegesConfig();
if ( userPrivilege != null && userPrivilege.isCheck() ) {
UserPrivilegesConfig.SchemaPrivilege schemaPrivilege = userPrivilege.getSchemaPrivilege( schema );
if ( schemaPrivilege != null ) {
String tableName = null;
int index = -1;
//TODO 此处待优化,寻找更优SQL 解析器
//修复bug
// https://github.com/alibaba/druid/issues/1309
//com.alibaba.druid.sql.parser.ParserException: syntax error, error in :'begin',expect END, actual EOF begin
if ( sql != null && sql.length() == 5 && sql.equalsIgnoreCase("begin") ) {
return true;
}
SQLStatementParser parser = new MycatStatementParser(sql);
SQLStatement stmt = parser.parseStatement();
if (stmt instanceof MySqlReplaceStatement || stmt instanceof SQLInsertStatement ) {
index = 0;
} else if (stmt instanceof SQLUpdateStatement ) {
index = 1;
} else if (stmt instanceof SQLSelectStatement ) {
index = 2;
} else if (stmt instanceof SQLDeleteStatement ) {
index = 3;
}
if ( index > -1) {
SchemaStatVisitor schemaStatVisitor = new MycatSchemaStatVisitor();
stmt.accept(schemaStatVisitor);
String key = schemaStatVisitor.getCurrentTable();
if ( key != null ) {
if (key.contains("`")) {
key = key.replaceAll("`", "");
}
int dotIndex = key.indexOf(".");
if (dotIndex > 0) {
tableName = key.substring(dotIndex + 1);
} else {
tableName = key;
}
//获取table 权限, 此处不需要检测空值, 无设置则自动继承父级权限
UserPrivilegesConfig.TablePrivilege tablePrivilege = schemaPrivilege.getTablePrivilege( tableName );
if ( tablePrivilege.getDml()[index] > 0 ) {
isPassed = true;
}
} else {
//skip
isPassed = true;
}
} else {
//skip
isPassed = true;
}
} else {
//skip
isPassed = true;
}
} else {
//skip
isPassed = true;
}
} else {
//skip
isPassed = true;
}
if( !isPassed ) {
ALARM.error(new StringBuilder().append(Alarms.DML_ATTACK ).append("[sql=").append( sql )
.append(",user=").append(user).append(']').toString());
}
return isPassed;
}
}