Files
agent/machinery/src/utils/main.go
T
Cédric VerstraetenandClaude Opus 5.5 88c2166133 encryption: derive recording keys with PBKDF2 and use AES-GCM
Recordings were encrypted in the OpenSSL/CryptoJS "Salted__" format, which
derives the AES key from the configured symmetric key with a single MD5
round. A captured recording therefore allowed fast offline guessing of
weak keys.

New recordings use a versioned format: magic "KRBREC1\0", the PBKDF2
iteration count, a 16-byte salt and a 12-byte nonce, followed by AES-256-GCM
ciphertext. The key is derived with PBKDF2-HMAC-SHA256 (600,000 iterations)
once per process and cached, so cameras do not pay the derivation cost per
recording; each recording still gets a fresh nonce. The header is
authenticated, and decryption caps the iteration count so a crafted file
cannot stall the agent.

DecryptRecording still reads the legacy format, so existing recordings keep
playing through /file and -action decrypt. The legacy decryption now
validates length and padding instead of panicking on truncated input or a
wrong key.

MQTT messages exchanged with Kerberos Hub keep the legacy format, which Hub
expects; their keys are random, so the weak key derivation does not make
them guessable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 05:38:43 +00:00

499 lines
14 KiB
Go

package utils
import (
"bytes"
"errors"
"fmt"
"image"
"image/jpeg"
"io/ioutil"
"math/rand"
"os"
"os/exec"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"github.com/kerberos-io/agent/machinery/src/encryption"
"github.com/kerberos-io/agent/machinery/src/models"
log "github.com/sirupsen/logrus"
"github.com/nfnt/resize"
)
// VERSION is the agent version. It defaults to "0.0.0" for local dev builds
// and is overridden at build time via:
//
// go build -ldflags "-X github.com/kerberos-io/agent/machinery/src/utils.VERSION=v1.2.3"
var VERSION = "0.0.0"
const letterBytes = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
// MaxUint8 - maximum value which can be held in an uint8
const MaxUint8 = ^uint8(0)
// MinUint8 - minimum value which can be held in an uint8
const MinUint8 = 0
// MaxUint16 - maximum value which can be held in an uint16
const MaxUint16 = ^uint16(0)
// MinUint16 - minimum value which can be held in an uint8
const MinUint16 = 0
const (
letterIdxBits = 6 // 6 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
)
func PrintASCIIArt() {
asciiArt := ` _ __ _ _
| |/ /___ _ __| |__ ___ _ __ ___ ___ (_) ___
| ' // _ \ '__| '_ \ / _ \ '__/ _ \/ __| | |/ _ \
| . \ __/ | | |_) | __/ | | (_) \__ \_| | (_) |
|_|\_\___|_| |_.__/ \___|_| \___/|___(_)_|\___/
`
fmt.Println(asciiArt)
}
func DirSize(path string) (int64, error) {
var size int64
err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
size += info.Size()
}
return err
})
return size, err
}
func FindOldestFile(dir string) (oldestFile os.FileInfo, err error) {
files, err := ioutil.ReadDir(dir)
if err != nil {
return
}
oldestTime := time.Now()
for _, file := range files {
if file.Mode().IsRegular() && file.ModTime().Before(oldestTime) {
oldestFile = file
oldestTime = file.ModTime()
}
}
if oldestFile == nil {
err = os.ErrNotExist
}
return
}
func RandStringBytesMaskImpr(n int) string {
b := make([]byte, n)
// A rand.Int63() generates 63 random bits, enough for letterIdxMax letters!
for i, cache, remain := n-1, rand.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = rand.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
i--
}
cache >>= letterIdxBits
remain--
}
return string(b)
}
func CountDigits(i int64) (count int) {
for i != 0 {
i /= 10
count = count + 1
}
return count
}
func CheckDataDirectoryPermissions(configDirectory string) error {
recordingsDirectory := configDirectory + "/data/recordings"
configurationDirectory := configDirectory + "/data/config"
snapshotsDirectory := configDirectory + "/data/snapshots"
cloudDirectory := configDirectory + "/data/cloud"
err := CheckDirectoryPermissions(recordingsDirectory)
if err == nil {
err = CheckDirectoryPermissions(configurationDirectory)
if err == nil {
err = CheckDirectoryPermissions(snapshotsDirectory)
if err == nil {
err = CheckDirectoryPermissions(cloudDirectory)
}
}
}
if err != nil {
log.Error("Checking data directory permissions: " + err.Error())
return err
}
log.Info("Checking data directory permissions: OK")
return nil
}
func CheckDirectoryPermissions(directory string) error {
// Check if the directory exists
if _, err := os.Stat(directory); os.IsNotExist(err) {
return errors.New("Directory does not exist, " + directory)
}
// Try to create a file
file := directory + "/.test"
f, err := os.Create(file)
if f != nil {
defer f.Close()
}
// We will remove the file if it was created
if err == nil {
err := os.Remove(file)
if err == nil {
return nil
} else {
return errors.New("Problem deleting a file: " + err.Error())
}
}
return errors.New("Problem creating a file: " + err.Error())
}
func ReadDirectory(directory string) ([]os.FileInfo, error) {
ff, err := ioutil.ReadDir(directory)
if err != nil {
return []os.FileInfo{}, nil
}
return ff, err
}
func GetSortedDirectory(files []os.FileInfo) []os.FileInfo {
sort.Slice(files, func(i, j int) bool {
return files[i].ModTime().After(files[j].ModTime())
})
return files
}
func GetMediaFormatted(files []os.FileInfo, recordingDirectory string, configuration *models.Configuration, eventFilter models.EventFilter) []models.Media {
filePaths := []models.Media{}
count := 0
for _, file := range files {
fileName := file.Name()
recordedAt, err := RecordingStartTime(fileName)
if err != nil {
continue
}
timestamp := recordedAt.Unix()
if eventFilter.TimestampOffsetStart > 0 && timestamp < eventFilter.TimestampOffsetStart {
continue
}
if eventFilter.TimestampOffsetEnd > 0 && timestamp >= eventFilter.TimestampOffsetEnd {
continue
}
loc, _ := time.LoadLocation(configuration.Config.Timezone)
localTime := recordedAt.In(loc)
filePaths = append(filePaths, models.Media{
Key: fileName,
Path: recordingDirectory + "/" + fileName,
CameraName: configuration.Config.Name,
CameraKey: configuration.Config.Key,
Day: localTime.Format("02-01-2006"),
ShortDay: localTime.Format("Jan _2"),
Time: localTime.Format("15:04:05"),
Timestamp: strconv.FormatInt(timestamp, 10),
})
count++
if eventFilter.NumberOfElements > 0 && count >= eventFilter.NumberOfElements {
break
}
}
return filePaths
}
func GetDays(files []os.FileInfo, recordingDirectory string, configuration *models.Configuration) []string {
days := []string{}
for _, file := range files {
recordedAt, err := RecordingStartTime(file.Name())
if err != nil {
continue
}
loc, _ := time.LoadLocation(configuration.Config.Timezone)
days = append(days, recordedAt.In(loc).Format("02-01-2006"))
}
uniqueDays := Unique(days)
return uniqueDays
}
func Unique(intSlice []string) []string {
keys := make(map[string]bool)
list := []string{}
for _, entry := range intSlice {
if _, value := keys[entry]; !value {
keys[entry] = true
list = append(list, entry)
}
}
return list
}
func NumberOfFilesInDirectory(path string) int {
files, _ := ioutil.ReadDir(path)
return len(files)
}
// NumberOfMP4sInDirectory counts MP4 files, including dated subdirectories.
func NumberOfMP4sInDirectory(path string) int {
files, err := ReadRecordingDirectory(path)
if err != nil {
log.WithError(err).Error("Could not count recordings")
return 0
}
return len(files)
}
func RandStringBytesRmndr(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = letterBytes[rand.Int63()%int64(len(letterBytes))]
}
return string(b)
}
func CreateFragmentedMP4(fullName string, fragmentedDuration int64) {
path, _ := os.Getwd()
duration := fragmentedDuration * 1000
// This timescale is crucial, as it should be the same as the one defined in JOY4.
cmd := exec.Command("mp4fragment", "--timescale", "10000000", "--fragment-duration", strconv.FormatInt(duration, 10), fullName, fullName+"f.mp4")
cmd.Dir = path
log.Info(cmd.String())
var out bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
log.Error(fmt.Sprint(err) + ": " + stderr.String())
} else {
log.Info("Created Fragmented: " + out.String())
}
// We will swap the files.
os.Remove(fullName)
os.Rename(fullName+"f.mp4", fullName)
}
func PrintEnvironmentVariables() {
names := agentEnvironmentVariableNames(os.Environ())
log.WithFields(log.Fields{
"component": "configuration",
"event": "environment_loaded",
"variable_count": len(names),
}).Info("Agent environment loaded")
log.WithFields(log.Fields{
"component": "configuration",
"event": "environment_details",
"variables": names,
}).Debug("Agent environment details")
}
func agentEnvironmentVariableNames(environment []string) []string {
names := make([]string, 0)
for _, entry := range environment {
name, _, found := strings.Cut(entry, "=")
if found && strings.HasPrefix(name, "AGENT_") {
names = append(names, name)
}
}
sort.Strings(names)
return names
}
func PrintConfiguration(configuration *models.Configuration) {
if configuration == nil {
log.WithFields(log.Fields{
"component": "configuration",
"event": "configuration_missing",
}).Warn("Agent configuration is nil")
return
}
log.WithFields(configurationLogFields(configuration.Config)).
Info("Agent configuration loaded")
log.WithFields(configurationDebugLogFields(configuration.Config)).
Debug("Agent configuration details")
}
func configurationLogFields(config models.Config) log.Fields {
return log.Fields{
"agent_name": config.Name,
"camera_type": config.Capture.Name,
"cloud_provider": config.Cloud,
"component": "configuration",
"event": "configuration_loaded",
"friendly_name": config.FriendlyName,
"liveview": config.Capture.Liveview,
"offline": config.Offline,
"recording": config.Capture.Recording,
"timezone": config.Timezone,
}
}
func configurationDebugLogFields(config models.Config) log.Fields {
return log.Fields{
"auto_clean": config.AutoClean,
"component": "configuration",
"continuous": config.Capture.Continuous,
"event": "configuration_details",
"gop_size": config.Capture.GopSize,
"main_fps": config.Capture.IPCamera.FPS,
"main_height": config.Capture.IPCamera.Height,
"main_stream_configured": config.Capture.IPCamera.RTSP != "",
"main_width": config.Capture.IPCamera.Width,
"max_recording_seconds": config.Capture.MaxLengthRecording,
"motion": config.Capture.Motion,
"onvif_configured": config.Capture.IPCamera.ONVIFXAddr != "",
"onvif_motion": config.Capture.ONVIFMotion,
"post_recording_seconds": config.Capture.PostRecording,
"pre_recording_seconds": config.Capture.PreRecording,
"remove_after_upload": config.RemoveAfterUpload,
"snapshots": config.Capture.Snapshots,
"sub_fps": config.Capture.IPCamera.SubFPS,
"sub_height": config.Capture.IPCamera.SubHeight,
"sub_stream_configured": config.Capture.IPCamera.SubRTSP != "",
"sub_width": config.Capture.IPCamera.SubWidth,
"transcoding_webrtc": config.Capture.TranscodingWebRTC,
}
}
func Decrypt(directoryOrFile string, symmetricKey []byte) {
// Check if file or directory
fileInfo, err := os.Stat(directoryOrFile)
if err != nil {
log.Fatal(err.Error())
return
}
var files []string
if fileInfo.IsDir() {
dir, err := ReadRecordingDirectory(directoryOrFile)
if err != nil {
log.Fatal(err.Error())
return
}
for _, file := range dir {
files = append(files, filepath.Join(directoryOrFile, file.Name()))
}
} else {
files = append(files, directoryOrFile)
}
// We'll loop over all files and decrypt them one by one.
for _, file := range files {
// Read file
content, err := os.ReadFile(file)
if err != nil {
log.Fatal(err.Error())
return
}
// Decrypt using AES key
decrypted, err := encryption.DecryptRecording(content, string(symmetricKey))
if err != nil {
log.Fatal("Something went wrong while decrypting: " + err.Error())
return
}
outputDirectory := filepath.Join(filepath.Dir(file), "decrypted")
if err := os.MkdirAll(outputDirectory, 0o755); err != nil {
log.Fatal(err.Error())
return
}
err = os.WriteFile(filepath.Join(outputDirectory, filepath.Base(file)), []byte(decrypted), 0644)
if err != nil {
log.Fatal(err.Error())
return
}
}
}
func ImageToBytes(img *image.Image) ([]byte, error) {
buffer := new(bytes.Buffer)
err := jpeg.Encode(buffer, *img, &jpeg.Options{Quality: 35})
log.WithFields(log.Fields{
"bytes": buffer.Len(),
"component": "image",
"event": "jpeg_encoded",
}).Debug("Image encoded as JPEG")
return buffer.Bytes(), err
}
func ResizeImage(img image.Image, newWidth uint, newHeight uint) (*image.Image, error) {
if img == nil {
return nil, errors.New("image is nil")
}
// Callers cast int->uint, so a negative or poisoned int (e.g. MinInt from
// `int(float * +Inf)` when the source width is 0) wraps to a near-MaxUint
// value here and crashes nfnt/resize's allocator with "makeslice: len out
// of range". Clamp anything past a sane camera ceiling to 0 ("auto" in
// nfnt — preserves aspect from the source).
const maxDim uint = 8192
if newWidth > maxDim {
newWidth = 0
}
if newHeight > maxDim {
newHeight = 0
}
// resize to width 640 using Lanczos resampling
// and preserve aspect ratio
m := resize.Resize(newWidth, newHeight, img, resize.Lanczos3)
return &m, nil
}
// ResolveBaseDimensions resolves the liveview/motion base dimensions for a
// stream given the (optionally configured) base width/height and the camera's
// probed source width/height. It returns the width and height that should be
// stored on the configuration.
//
// The aspect-ratio branch is gated on width>0 && height>0: a not-yet-probed
// stream has width=height=0, which previously made the ratio +Inf and
// int(float * +Inf) yield MinInt. That poisoned value, later cast to uint at
// the ResizeImage call sites, wrapped to ~MaxUint and crashed resize with
// "makeslice: len out of range". When the source isn't probed yet we fall back
// to the source dimensions (0,0 -> "auto") instead.
func ResolveBaseDimensions(baseWidth, baseHeight, width, height int) (int, int) {
if baseWidth > 0 && baseHeight == 0 && width > 0 && height > 0 {
// Derive the height from the configured width and the source aspect ratio.
widthAspectRatio := float64(baseWidth) / float64(width)
return baseWidth, int(float64(height) * widthAspectRatio)
} else if baseHeight > 0 && baseWidth > 0 {
// Both base dimensions are configured; honor them as-is.
return baseWidth, baseHeight
}
// Nothing usable configured (or source not probed yet): use source dimensions.
return width, height
}
func ResizeHeightWithAspectRatio(newWidth int, width int, height int) (int, int) {
if newWidth <= 0 || width <= 0 || height <= 0 {
return width, height
}
// Calculate the new height based on the aspect ratio
newHeight := (newWidth * height) / width
// Return the new dimensions
return newWidth, newHeight
}