Symfony + WSSE:为什么随机数缓存文件夹的大小为20GB?

问题描述

我正在基于Symfony 3.4的项目中使用WSSE authentication as described in the Symfony docs

每个随机数都作为单独的文件存储在高速缓存目录myProject/var/cache/prod/security/nonces中。探针是,此目录的大小变得非常非常大。该项目已启动并正在运行,随机数已使用近20GB的磁盘空间

$ cd myProject/var/cache/prod/security/
$ du -sch *
19G    nonces
19G    total

这对我来说似乎很...我试图找出存储了多少随机数,并使用以下命令对文件进行计数:

$ cd myProject/var/cache/prod/security/nonces
$ find -maxdepth 1 -type f | wc -l
4697417

即使有470万个文件,19GB看起来也差不多。每个文件的大小大约为4KB。但是,据我所知,每个文件只有10B ...

$ cd myProject/var/cache/prod/security/nonces
$ ls -lh
-rw-r----- 1 user nobody 10 Jul 25 16:46 'MWFiYWM5YjAiOTRyOWRmZA=='
-rw-r----- 1 user nobody 10 Jul  1 19:41 'MWFiYWNiYTflNTdhlGYwYQ=='
-rw-r----- 1 user nobody 10 Sep 29 11:05 'MWFiYWNkNzEjZfFlCjM0OQ=='
...

我知道文件大小和消耗的磁盘空间之间存在差异。但是,du显示了10B的磁盘空间:

$ du -sb --apparent-size MWFiYWNkNzEjZfFlCjM0OQ==
10

那么,文件如何使用19G的磁盘空间,而每个文件仅使用10B?我想念什么吗?还是我没有正确使用命令?

有没有更好的存储随机数?

我当然可以不时删除缓存。但是,这会使随机数变得毫无用处,不是吗?

解决方法

文件大小

du报告已消耗的磁盘空间大小。 磁盘空间按块分配。因此,文件可占用的最小空间为1个块。在您的情况下,文件系统的块大小似乎为4kb。因此,大约470万个文件(大小为10byte)消耗了4700000 * 4kb,即大约19gb。

存储随机数多长时间

名词通常会缓存几分钟。您提到的symfony食谱建议5分钟的现时值。这是该文档的摘录

class WsseProvider implements AuthenticationProviderInterface
{
  protected function validateDigest($digest,$nonce,$created,$secret)
    {
        // Check created time is not in the future
        if (strtotime($created) > time()) {
            return false;
        }

        // Expire timestamp after 5 minutes
        if (time() - strtotime($created) > 300) {
            return false;
        }

        // Try to fetch the cache item from pool
        $cacheItem = $this->cachePool->getItem(md5($nonce));

        // Validate that the nonce is *not* in cache
        // if it is,this could be a replay attack
        if ($cacheItem->isHit()) {
            // In a real world application you should throw a custom
            // exception extending the AuthenticationException
            throw new AuthenticationException('Previously used nonce detected');
        }

        // Store the item in cache for 5 minutes
        $cacheItem->set(null)->expiresAfter(300);
        $this->cachePool->save($cacheItem);

        // Validate Secret
        $expected = base64_encode(sha1(base64_decode($nonce).$created.$secret,true));

        return hash_equals($expected,$digest);
    }
}

随机数以5分钟的ttl添加到缓存池。 保持随机数的时间长于您认为已创建字段有效的时间(在本示例if (time() - strtotime($created) > 300)中为5分钟)不会增加任何额外的安全性,因为一旦创建日期过时,就可以基于以下原因拒绝重播的请求:创建的时间戳。