创建一个测试数据库表,插入测试数据:
CREATE TABLE `blank_space` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`uid` varchar(10) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`desc` varchar(10) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
UNIQUE KEY `uniq_key` (`uid`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO `blank_space`(`id`, `uid`, `desc`) VALUES (1, 'abc ', '末尾1个');
INSERT INTO `blank_space`(`id`, `uid`, `desc`) VALUES (2, ' abc', '开头1个');
INSERT INTO `blank_space`(`id`, `uid`, `desc`) VALUES (3, ' abc', '开头2个');
id | uid | desc |
---|---|---|
1 | abc_ | 末尾 1 个 |
2 | _abc | 开头 1 个 |
3 | __abc | 开头 2 个 |
uid 实际上没有
_
,这样写是为了看到空格。
执行操作:
SELECT * FROM blank_space WHERE uid = 'abc';
SELECT * FROM blank_space WHERE uid = 'abc ';
SELECT * FROM blank_space WHERE uid = 'abc ';
都可以查询出:
id | uid | desc |
---|---|---|
1 | abc_ | 末尾 1 个 |
执行操作:
INSERT INTO `blank_space`(`uid`, `desc`) VALUES ('abc', '无空格');
-- 1062 - Duplicate entry 'abc' for key 'uniq_key', Time: 0.322000s
INSERT INTO `blank_space`(`uid`, `desc`) VALUES ('abc ', '末位两个');
-- 1062 - Duplicate entry 'abc' for key 'uniq_key', Time: 0.322000s
MySQL 校对规则属于 PADSPACE,会忽略尾部空格。针对的是 varchar char text 等文本类的数据类型。此为 SQL 标准化行为。无需要设置也无法改变。
SELECT * FROM blank_space WHERE uid = BINARY 'abc';
-- 0 records
SELECT * FROM blank_space WHERE uid = BINARY 'abc ';
-- 1 records
SELECT * FROM blank_space WHERE uid = BINARY 'abc ';
-- 0 records
SELECT * FROM blank_space WHERE uid like 'abc';
-- 0 records
SELECT * FROM blank_space WHERE uid like 'abc ';
-- 1 records
SELECT * FROM blank_space WHERE uid like 'abc ';
-- 0 records
BINARY 不是函数,是类型转换运算符,它用来强制它后面的字符串为一个二进制字符串,可以理解成精确匹配。
需要在非严格模式下。
SET sql_mode = '';
CREATE TABLE `blank_space_attack` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`uid` varchar(10) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`pwd` varchar(10) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO `blank_space_attack`(`id`, `uid`, `pwd`) VALUES (1, 'admin', '123');
INSERT INTO `blank_space_attack`(`id`, `uid`, `pwd`) VALUES (2, 'tim', '234');
攻击:
INSERT INTO `blank_space_attack`(`uid`, `pwd`) VALUES ('admin 1', 'easy');
结果:
select * from blank_space_attack where uid = "admin" and pwd = "easy";
id | uid | desc |
---|---|---|
3 | admin_____ | easy |
admin_____
,如果此后的业务逻辑以该用户名为准,那么就不能达到越权的目的了。– EOF –