Skip to content

Commit c9971b0

Browse files
committed
Save data outside metadate to prevent invalid data when storing things
like json strings or serialized objects.
1 parent d2962f1 commit c9971b0

File tree

1 file changed

+18
-10
lines changed

1 file changed

+18
-10
lines changed

phpsec/phpsec.store.filesystem.php

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -24,30 +24,35 @@ public function __construct($loc) {
2424
}
2525

2626
public function read($type, $id) {
27-
$fileName = $this->fileName($type, $id);
27+
$fileName = $this->fileName($type, $id);
2828
if(!file_exists($fileName)) {
2929
return false;
3030
}
31-
$data = json_decode(file_get_contents($fileName));
32-
$mac = phpsecCrypt::pbkdf2($data->data, $id, 1000, 32);
31+
$data = file_get_contents($fileName);
32+
list($meta, $data) = explode("\n\n", $data);
33+
$jsonData = json_decode($meta);
34+
35+
$mac = phpsecCrypt::pbkdf2($data, $id, 1000, 32);
3336

34-
if($mac != base64_decode($data->mac)) {
37+
if($mac != base64_decode($jsonData->mac)) {
3538
phpsec::error('Message authentication code invalid while reading store');
3639
return false;
3740
}
38-
return unserialize(base64_decode($data->data));
41+
return unserialize($data);
3942
}
4043

4144
public function write($type, $id, $data) {
4245
$fileName = $this->fileName($type, $id);
46+
47+
$data = serialize($data);
4348
$saveData['id'] = base64_encode($id);
44-
$saveData['data'] = base64_encode(serialize($data));
45-
$saveData['mac'] = base64_encode(phpsecCrypt::pbkdf2($saveData['data'], $id, 1000, 32));
49+
$saveData['mac'] = base64_encode(phpsecCrypt::pbkdf2($data, $id, 1000, 32));
4650

47-
$data = json_encode($saveData);
51+
$jsonData = json_encode($saveData);
4852
$fp = fopen($fileName, 'w');
4953
if($fp !== false) {
5054
if(flock($fp, LOCK_EX)) {
55+
fwrite($fp, $jsonData."\n\n");
5156
fwrite($fp, $data);
5257
flock($fp, LOCK_UN);
5358
fclose($fp);
@@ -67,8 +72,11 @@ public function listIds($type) {
6772
$ids = array();
6873
$files = glob($this->_dataDir.'/store_'.$type.'_*');
6974
foreach($files as $file) {
70-
$data = json_decode(file_get_contents($file));
71-
$ids[] = base64_decode($data->id);
75+
$data = file_get_contents($file);
76+
77+
list($meta, $data) = explode("\n\n", $data);
78+
$jsonData = json_decode($meta);
79+
$ids[] = base64_decode($jsonData->id);
7280

7381
}
7482
return $ids;

0 commit comments

Comments
 (0)