I have the following MySQL session schema:
CREATE TABLE `SessionData` (
`id` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`data` text COLLATE utf8_unicode_ci,
`date` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `date` (`date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
So I want to prevent users reading each other session data via e.g. SQL Injection. I want to secure it using MySQL view, procedure or something like this. Is there is some common, secure way to do it? I think it's common thing to do, as with this and remote shell it's difficult to overwrite anything on the server, except for it's own session data, but not the files and the SQL and SQL Session, so it's like read only, but with write only to it's own row.
I make a single column, single row data set:
CREATE TABLE `SessionId` (
`id` varchar(50) COLLATE utf8_unicode_ci DEFAULT '',
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
I insert an empty string into it:
INSERT INTO SessionId (id) VALUES ('');
So then I can create a view. In this case it's using "frontuser", as MySQL user.
DELIMITER $$
DROP VIEW IF EXISTS `SessionView`$$
CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`%` SQL SECURITY DEFINER VIEW `SessionView` AS (
SELECT
`SessionData`.`id` AS `id`,
`SessionData`.`data` AS `data`,
`SessionData`.`date` AS `date`
FROM (`SessionId`
JOIN `SessionData`
ON ((`SessionId`.`id` = `SessionData`.`id`))))$$
DELIMITER ;
How to INSERT session:
INSERT INTO SessionView (id, `data`, `date`)
VALUES (
HEX(AES_ENCRYPT("Cookie Value", "Random Key from Config")),
HEX(AES_ENCRYPT("128bit random block + Session Data", "Random Key from Config")),
NOW());
How to Check Session
BEGIN;
UPDATE SessionId SET id = HEX(AES_ENCRYPT("Cookie Value", "Random Key from Config"));
SELECT AES_DECRYPT(UNHEX(`data`), "Random Key from Config") FROM SessionView;
UPDATE SessionId SET id = '';
COMMIT;
So I grant only SELECT, UPDATE and INSERT to SessionView view. Since the keys are randomized and there is no way to extract all keys, I can create the session but I cannot browse them all.