Help us shape the future of Go! Take the 2026 Go Developer Survey

security

package
v0.23.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 21, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Overview

Package security provides cryptographic utilities for session token binding and hijacking prevention. It handles HMAC-SHA256 token hashing, salt generation, and constant-time comparison to prevent timing attacks.

Index

Constants

View Source
const (
	// SHA256HexLen is the length of a hex-encoded SHA256 hash (32 bytes = 64 hex characters)
	SHA256HexLen = 64
)

Variables

This section is empty.

Functions

func PreventSessionHijacking

func PreventSessionHijacking(
	session sessiontypes.MultiSession,
	hmacSecret []byte,
	identity *auth.Identity,
) (sessiontypes.MultiSession, error)

PreventSessionHijacking wraps a session with hijack prevention security measures. It computes token binding hashes, stores them in session metadata, and returns a decorated session that validates caller identity on every operation.

Whether the session is anonymous is derived from the identity: nil identity or empty token means anonymous, a non-empty token means bound/authenticated.

For authenticated sessions (identity.Token != ""):

  • Generates a unique random salt
  • Computes HMAC-SHA256 hash of the bearer token
  • Stores hash and salt in session metadata
  • Returns decorator that validates every request against the creator's token

For anonymous sessions (identity == nil or identity.Token == ""):

  • Stores an empty string sentinel for the token hash metadata key
  • Omits the salt metadata key entirely (no salt is generated for anonymous sessions)
  • Returns decorator that allows nil callers and rejects token presentation

Security:

  • Makes defensive copies of secret and salt to prevent external mutation
  • Uses constant-time comparison to prevent timing attacks
  • Prevents session upgrade attacks (anonymous → authenticated)
  • Raw tokens are never stored, only HMAC-SHA256 hashes

Returns an error if:

  • session is nil
  • salt generation fails

func RestoreHijackPrevention added in v0.15.0

func RestoreHijackPrevention(
	session sessiontypes.MultiSession,
	tokenHash string,
	tokenSaltHex string,
	hmacSecret []byte,
) (sessiontypes.MultiSession, error)

RestoreHijackPrevention recreates the hijack-prevention decorator from persisted metadata, rather than recomputing token binding from an identity. Use this when reconstructing a MultiSession after a pod restart or cross-pod failover where the original bearer token is no longer available but the stored hash and salt are.

If tokenHash is empty the session is treated as anonymous (allowAnonymous=true). The hmacSecret must be the same server-managed secret used at creation time.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL