oauth2_proxy/pkg/sessions/redis/redis_store.go

301 lines
8.8 KiB
Go
Raw Normal View History

2019-05-09 23:09:22 +00:00
package redis
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/go-redis/redis"
"github.com/pusher/oauth2_proxy/cookie"
"github.com/pusher/oauth2_proxy/pkg/apis/options"
"github.com/pusher/oauth2_proxy/pkg/apis/sessions"
"github.com/pusher/oauth2_proxy/pkg/cookies"
)
// TicketData is a structure representing the ticket used in server session storage
2019-05-09 23:09:22 +00:00
type TicketData struct {
TicketID string
Secret []byte
}
// SessionStore is an implementation of the sessions.SessionStore
// interface that stores sessions in redis
type SessionStore struct {
2019-05-15 16:06:05 +00:00
CookieCipher *cookie.Cipher
CookieOptions *options.CookieOptions
Client *redis.Client
2019-05-09 23:09:22 +00:00
}
// NewRedisSessionStore initialises a new instance of the SessionStore from
// the configuration given
2019-05-15 16:06:05 +00:00
func NewRedisSessionStore(opts *options.SessionOptions, cookieOpts *options.CookieOptions) (sessions.SessionStore, error) {
2019-05-24 16:32:55 +00:00
client, err := newRedisClient(opts.RedisStoreOptions)
2019-05-09 23:09:22 +00:00
if err != nil {
2019-05-24 16:32:55 +00:00
return nil, fmt.Errorf("error constructing redis client: %v", err)
2019-05-09 23:09:22 +00:00
}
rs := &SessionStore{
2019-05-15 16:06:05 +00:00
Client: client,
CookieCipher: opts.Cipher,
CookieOptions: cookieOpts,
2019-05-09 23:09:22 +00:00
}
return rs, nil
}
2019-05-24 16:32:55 +00:00
func newRedisClient(opts options.RedisStoreOptions) (*redis.Client, error) {
if opts.UseSentinel {
client := redis.NewFailoverClient(&redis.FailoverOptions{
MasterName: opts.SentinelMasterName,
SentinelAddrs: opts.SentinelConnectionURLs,
})
return client, nil
}
opt, err := redis.ParseURL(opts.RedisConnectionURL)
if err != nil {
return nil, fmt.Errorf("unable to parse redis url: %s", err)
}
client := redis.NewClient(opt)
return client, nil
}
2019-05-09 23:09:22 +00:00
// Save takes a sessions.SessionState and stores the information from it
// to redies, and adds a new ticket cookie on the HTTP response writer
func (store *SessionStore) Save(rw http.ResponseWriter, req *http.Request, s *sessions.SessionState) error {
if s.CreatedAt.IsZero() {
s.CreatedAt = time.Now()
}
// Old sessions that we are refreshing would have a request cookie
// New sessions don't, so we ignore the error. storeValue will check requestCookie
2019-05-15 16:06:05 +00:00
requestCookie, _ := req.Cookie(store.CookieOptions.CookieName)
2019-05-09 23:09:22 +00:00
value, err := s.EncodeSessionState(store.CookieCipher)
if err != nil {
return err
}
ticketString, err := store.storeValue(value, store.CookieOptions.CookieExpire, requestCookie)
2019-05-09 23:09:22 +00:00
if err != nil {
return err
}
ticketCookie := store.makeCookie(
2019-05-09 23:09:22 +00:00
req,
ticketString,
2019-05-15 16:06:05 +00:00
store.CookieOptions.CookieExpire,
s.CreatedAt,
2019-05-09 23:09:22 +00:00
)
http.SetCookie(rw, ticketCookie)
return nil
}
// Load reads sessions.SessionState information from a ticket
// cookie within the HTTP request object
func (store *SessionStore) Load(req *http.Request) (*sessions.SessionState, error) {
2019-05-15 16:06:05 +00:00
requestCookie, err := req.Cookie(store.CookieOptions.CookieName)
if err != nil {
return nil, fmt.Errorf("error loading session: %s", err)
}
val, _, ok := cookie.Validate(requestCookie, store.CookieOptions.CookieSecret, store.CookieOptions.CookieExpire)
if !ok {
return nil, fmt.Errorf("Cookie Signature not valid")
}
2019-05-16 16:06:13 +00:00
session, err := store.loadSessionFromString(val)
2019-05-09 23:09:22 +00:00
if err != nil {
return nil, fmt.Errorf("error loading session: %s", err)
}
return session, nil
}
2019-05-16 16:06:13 +00:00
// loadSessionFromString loads the session based on the ticket value
func (store *SessionStore) loadSessionFromString(value string) (*sessions.SessionState, error) {
2019-05-15 16:06:05 +00:00
ticket, err := decodeTicket(store.CookieOptions.CookieName, value)
2019-05-09 23:09:22 +00:00
if err != nil {
return nil, err
}
2019-05-15 16:06:05 +00:00
result, err := store.Client.Get(ticket.asHandle(store.CookieOptions.CookieName)).Result()
2019-05-09 23:09:22 +00:00
if err != nil {
return nil, err
}
resultBytes := []byte(result)
block, err := aes.NewCipher(ticket.Secret)
if err != nil {
return nil, err
}
// Use secret as the IV too, because each entry has it's own key
stream := cipher.NewCFBDecrypter(block, ticket.Secret)
stream.XORKeyStream(resultBytes, resultBytes)
session, err := sessions.DecodeSessionState(string(resultBytes), store.CookieCipher)
if err != nil {
return nil, err
}
return session, nil
}
// Clear clears any saved session information for a given ticket cookie
// from redis, and then clears the session
func (store *SessionStore) Clear(rw http.ResponseWriter, req *http.Request) error {
// We go ahead and clear the cookie first, always.
clearCookie := store.makeCookie(
2019-05-09 23:09:22 +00:00
req,
"",
time.Hour*-1,
time.Now(),
)
http.SetCookie(rw, clearCookie)
// If there was an existing cookie we should clear the session in redis
requestCookie, err := req.Cookie(store.CookieOptions.CookieName)
if err != nil && err == http.ErrNoCookie {
// No existing cookie so can't clear redis
return nil
} else if err != nil {
return fmt.Errorf("error retrieving cookie: %v", err)
}
val, _, ok := cookie.Validate(requestCookie, store.CookieOptions.CookieSecret, store.CookieOptions.CookieExpire)
if !ok {
return fmt.Errorf("Cookie Signature not valid")
}
2019-05-09 23:09:22 +00:00
// We only return an error if we had an issue with redis
// If there's an issue decoding the ticket, ignore it
ticket, _ := decodeTicket(store.CookieOptions.CookieName, val)
2019-05-09 23:09:22 +00:00
if ticket != nil {
_, err := store.Client.Del(ticket.asHandle(store.CookieOptions.CookieName)).Result()
2019-05-09 23:09:22 +00:00
if err != nil {
return fmt.Errorf("error clearing cookie from redis: %s", err)
}
}
return nil
}
// makeCookie makes a cookie, signing the value if present
func (store *SessionStore) makeCookie(req *http.Request, value string, expires time.Duration, now time.Time) *http.Cookie {
if value != "" {
value = cookie.SignedValue(store.CookieOptions.CookieSecret, store.CookieOptions.CookieName, value, now)
}
return cookies.MakeCookieFromOptions(
req,
store.CookieOptions.CookieName,
value,
store.CookieOptions,
expires,
now,
)
}
func (store *SessionStore) storeValue(value string, expiration time.Duration, requestCookie *http.Cookie) (string, error) {
ticket, err := store.getTicket(requestCookie)
if err != nil {
return "", fmt.Errorf("error getting ticket: %v", err)
2019-05-09 23:09:22 +00:00
}
ciphertext := make([]byte, len(value))
block, err := aes.NewCipher(ticket.Secret)
if err != nil {
return "", fmt.Errorf("error initiating cipher block %s", err)
}
2019-05-16 16:07:43 +00:00
// Use secret as the Initialization Vector too, because each entry has it's own key
2019-05-09 23:09:22 +00:00
stream := cipher.NewCFBEncrypter(block, ticket.Secret)
stream.XORKeyStream(ciphertext, []byte(value))
2019-05-15 16:06:05 +00:00
handle := ticket.asHandle(store.CookieOptions.CookieName)
2019-05-16 16:08:10 +00:00
err = store.Client.Set(handle, ciphertext, expiration).Err()
2019-05-09 23:09:22 +00:00
if err != nil {
return "", err
}
2019-05-15 16:06:05 +00:00
return ticket.encodeTicket(store.CookieOptions.CookieName), nil
2019-05-09 23:09:22 +00:00
}
// getTicket retrieves an existing ticket from the cookie if present,
// or creates a new ticket
func (store *SessionStore) getTicket(requestCookie *http.Cookie) (*TicketData, error) {
if requestCookie == nil {
return newTicket()
}
// An existing cookie exists, try to retrieve the ticket
val, _, ok := cookie.Validate(requestCookie, store.CookieOptions.CookieSecret, store.CookieOptions.CookieExpire)
if !ok {
// Cookie is invalid, create a new ticket
return newTicket()
}
// Valid cookie, decode the ticket
return decodeTicket(store.CookieOptions.CookieName, val)
}
2019-05-09 23:09:22 +00:00
func newTicket() (*TicketData, error) {
rawID := make([]byte, 16)
if _, err := io.ReadFull(rand.Reader, rawID); err != nil {
return nil, fmt.Errorf("failed to create new ticket ID %s", err)
}
// ticketID is hex encoded
ticketID := fmt.Sprintf("%x", rawID)
secret := make([]byte, aes.BlockSize)
if _, err := io.ReadFull(rand.Reader, secret); err != nil {
return nil, fmt.Errorf("failed to create initialization vector %s", err)
}
ticket := &TicketData{
TicketID: ticketID,
Secret: secret,
}
return ticket, nil
}
func (ticket *TicketData) asHandle(prefix string) string {
return fmt.Sprintf("%s-%s", prefix, ticket.TicketID)
}
func decodeTicket(cookieName string, ticketString string) (*TicketData, error) {
prefix := cookieName + "-"
if !strings.HasPrefix(ticketString, prefix) {
return nil, fmt.Errorf("failed to decode ticket handle")
}
trimmedTicket := strings.TrimPrefix(ticketString, prefix)
ticketParts := strings.Split(trimmedTicket, ".")
if len(ticketParts) != 2 {
return nil, fmt.Errorf("failed to decode ticket")
}
ticketID, secretBase64 := ticketParts[0], ticketParts[1]
// ticketID must be a hexadecimal string
_, err := hex.DecodeString(ticketID)
if err != nil {
return nil, fmt.Errorf("server ticket failed sanity checks")
}
secret, err := base64.RawURLEncoding.DecodeString(secretBase64)
if err != nil {
return nil, fmt.Errorf("failed to decode initialization vector %s", err)
}
ticketData := &TicketData{
TicketID: ticketID,
Secret: secret,
}
return ticketData, nil
}
func (ticket *TicketData) encodeTicket(prefix string) string {
handle := ticket.asHandle(prefix)
ticketString := handle + "." + base64.RawURLEncoding.EncodeToString(ticket.Secret)
return ticketString
}