Use sha256 to sanitize discovery HTTP cache keys

This helps avoid (potentially malicious) collisions when reading and
writing cache data.

Signed-off-by: Nic Cope <nicc@rk0n.org>

Kubernetes-commit: 288a17fd337c65cb5aea44e44ecb74e9cb8088f5
This commit is contained in:
Nic Cope 2022-07-14 14:11:33 -07:00 committed by Kubernetes Publisher
parent 1ea239faa5
commit 735524f850

View File

@ -17,10 +17,10 @@ limitations under the License.
package disk package disk
import ( import (
"crypto/sha256"
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"hash/crc32" "hash/crc32"
"hash/fnv"
"net/http" "net/http"
"os" "os"
"path/filepath" "path/filepath"
@ -95,7 +95,7 @@ func (c *crcDiskCache) Get(key string) ([]byte, bool) {
return response, true return response, true
} }
// Set writes the response to a file on disk. The filename will be the FNV-32a // Set writes the response to a file on disk. The filename will be the SHA256
// hash of the key. The file will contain the CRC-32 checksum of the response // hash of the key. The file will contain the CRC-32 checksum of the response
// bytes, followed by said response bytes. // bytes, followed by said response bytes.
func (c *crcDiskCache) Set(key string, response []byte) { func (c *crcDiskCache) Set(key string, response []byte) {
@ -113,7 +113,8 @@ func (c *crcDiskCache) Delete(key string) {
// the request method was GET) or "<method> <url>" for other methods, per the // the request method was GET) or "<method> <url>" for other methods, per the
// httpcache.cacheKey function. // httpcache.cacheKey function.
func sanitize(key string) string { func sanitize(key string) string {
h := fnv.New32a() // These keys are not sensitive. We use sha256 to avoid a (potentially
_, _ = h.Write([]byte(key)) // Writing to a hash never returns an error. // malicious) collision causing the wrong cache data to be written or
return fmt.Sprintf("%X", h.Sum32()) // accessed.
return fmt.Sprintf("%x", sha256.Sum256([]byte(key)))
} }