protocol.go 6.59 KB
Newer Older
ale's avatar
ale committed
1 2 3 4 5 6 7 8 9 10 11 12
package auth

import (
	"fmt"

	"github.com/tstranex/u2f"
)

// DeviceInfo holds information about the client device. We use a
// simple persistent cookie to track the same client device across
// multiple session.
type DeviceInfo struct {
ale's avatar
ale committed
13 14 15 16 17 18 19
	ID         string `json:"id"`
	RemoteAddr string `json:"remote_addr"`
	RemoteZone string `json:"remote_zone"`
	UserAgent  string `json:"user_agent"`
	Browser    string `json:"browser"`
	OS         string `json:"os"`
	Mobile     bool   `json:"mobile"`
ale's avatar
ale committed
20 21 22 23 24 25 26 27
}

func (d *DeviceInfo) encodeToMap(m map[string]string, prefix string) {
	m[prefix+"id"] = d.ID
	m[prefix+"remote_addr"] = d.RemoteAddr
	m[prefix+"remote_zone"] = d.RemoteZone
	m[prefix+"browser"] = d.Browser
	m[prefix+"os"] = d.OS
ale's avatar
ale committed
28 29 30 31 32 33
	m[prefix+"user_agent"] = d.UserAgent
	if d.Mobile {
		m[prefix+"mobile"] = "true"
	} else {
		m[prefix+"mobile"] = "false"
	}
ale's avatar
ale committed
34 35 36 37 38 39 40 41 42 43 44 45
}

func decodeDeviceInfoFromMap(m map[string]string, prefix string) *DeviceInfo {
	if _, ok := m[prefix+"id"]; !ok {
		return nil
	}
	return &DeviceInfo{
		ID:         m[prefix+"id"],
		RemoteAddr: m[prefix+"remote_addr"],
		RemoteZone: m[prefix+"remote_zone"],
		Browser:    m[prefix+"browser"],
		OS:         m[prefix+"os"],
ale's avatar
ale committed
46 47
		UserAgent:  m[prefix+"user_agent"],
		Mobile:     m[prefix+"mobile"] == "true",
ale's avatar
ale committed
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
	}
}

// Request to authenticate a user. It supports multiple methods for
// authentication including challenge-response 2FA.
type Request struct {
	Service     string
	Username    string
	Password    []byte
	OTP         string
	U2FAppID    string
	U2FResponse *u2f.SignResponse
	DeviceInfo  *DeviceInfo
	//Extra       map[string]string
}

func (r *Request) EncodeToMap(m map[string]string, prefix string) {
	m[prefix+"service"] = r.Service
	m[prefix+"username"] = r.Username
	m[prefix+"password"] = string(r.Password)

	if r.OTP != "" {
		m[prefix+"otp"] = r.OTP
	}
	if r.U2FAppID != "" {
		m[prefix+"u2f_app_id"] = r.U2FAppID
	}
	if r.U2FResponse != nil {
		encodeU2FResponseToMap(r.U2FResponse, m, prefix+"u2f_response.")
	}
	if r.DeviceInfo != nil {
		r.DeviceInfo.encodeToMap(m, prefix+"device.")
	}
}

func (r *Request) DecodeFromMap(m map[string]string, prefix string) {
	r.Service = m[prefix+"service"]
	r.Username = m[prefix+"username"]
	r.Password = []byte(m[prefix+"password"])
	r.OTP = m[prefix+"otp"]
	r.U2FAppID = m[prefix+"u2f_app_id"]
	r.U2FResponse = decodeU2FResponseFromMap(m, prefix+"u2f_response.")
	r.DeviceInfo = decodeDeviceInfoFromMap(m, prefix+"device.")
}

ale's avatar
ale committed
93 94
// UserInfo contains optional user information that may be useful to
// authentication endpoints.
ale's avatar
ale committed
95 96
type UserInfo struct {
	Email  string
ale's avatar
ale committed
97
	Shard  string
ale's avatar
ale committed
98 99 100 101 102 103 104
	Groups []string
}

func (u *UserInfo) EncodeToMap(m map[string]string, prefix string) {
	if u.Email != "" {
		m[prefix+"email"] = u.Email
	}
ale's avatar
ale committed
105 106 107
	if u.Shard != "" {
		m[prefix+"shard"] = u.Shard
	}
ale's avatar
ale committed
108 109 110 111 112 113
	for i, g := range u.Groups {
		m[fmt.Sprintf("%sgroup.%d.", prefix, i)] = g
	}
}

func decodeUserInfoFromMap(m map[string]string, prefix string) *UserInfo {
ale's avatar
ale committed
114 115 116 117
	u := UserInfo{
		Email: m[prefix+"email"],
		Shard: m[prefix+"shard"],
	}
ale's avatar
ale committed
118 119 120 121 122 123 124 125 126
	i := 0
	for {
		s, ok := m[fmt.Sprintf("%sgroup.%d.", prefix, i)]
		if !ok {
			break
		}
		u.Groups = append(u.Groups, s)
		i++
	}
ale's avatar
ale committed
127
	if u.Email == "" && u.Shard == "" && len(u.Groups) == 0 {
ale's avatar
ale committed
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
		return nil
	}
	return &u
}

// Response to an authentication request.
type Response struct {
	Status         Status
	TFAMethod      TFAMethod
	U2FSignRequest *u2f.WebSignRequest
	UserInfo       *UserInfo
}

func (r *Response) EncodeToMap(m map[string]string, prefix string) {
	m[prefix+"status"] = r.Status.String()
	m[prefix+"2fa_method"] = string(r.TFAMethod)
	if r.U2FSignRequest != nil {
		// External type.
		encodeU2FSignRequestToMap(r.U2FSignRequest, m, prefix+"u2f_req.")
	}
	if r.UserInfo != nil {
		r.UserInfo.EncodeToMap(m, prefix+"user.")
	}
}

func (r *Response) DecodeFromMap(m map[string]string, prefix string) {
	r.Status = parseAuthStatus(m[prefix+"status"])
	r.TFAMethod = TFAMethod(m[prefix+"2fa_method"])
	r.U2FSignRequest = decodeU2FSignRequestFromMap(m, prefix+"u2f_req.")
	r.UserInfo = decodeUserInfoFromMap(m, prefix+"user.")
}

// TFAMethod is a hint provided to the caller with the type of 2FA
// method that is available for authentication.
type TFAMethod string

const (
	TFAMethodNone = ""
	TFAMethodOTP  = "otp"
	TFAMethodU2F  = "u2f"
)

// Status of an authentication request.
type Status int

const (
	StatusOK = iota
	StatusInsufficientCredentials
	StatusError
)

func (s Status) String() string {
	switch s {
	case StatusOK:
		return "ok"
	case StatusInsufficientCredentials:
		return "insufficient_credentials"
	case StatusError:
		return "error"
	default:
		return fmt.Sprintf("unknown(%d)", int(s))
	}
}

func parseAuthStatus(s string) Status {
	switch s {
	case "ok":
		return StatusOK
	case "insufficient_credentials":
		return StatusInsufficientCredentials
	default:
		return StatusError
	}
}

func (s Status) Error() string {
	return s.String()
}

// Miscellaneous serializers for external objects.

func encodeU2FResponseToMap(resp *u2f.SignResponse, m map[string]string, prefix string) {
	m[prefix+"key_handle"] = resp.KeyHandle
	m[prefix+"signature_data"] = resp.SignatureData
	m[prefix+"client_data"] = resp.ClientData
}

func decodeU2FResponseFromMap(m map[string]string, prefix string) *u2f.SignResponse {
	if _, ok := m[prefix+"key_handle"]; !ok {
		return nil
	}
	return &u2f.SignResponse{
		KeyHandle:     m[prefix+"key_handle"],
		SignatureData: m[prefix+"signature_data"],
		ClientData:    m[prefix+"client_data"],
	}
}

func encodeU2FSignRequestToMap(req *u2f.WebSignRequest, m map[string]string, prefix string) {
	m[prefix+"app_id"] = req.AppID
	m[prefix+"challenge"] = req.Challenge
	for i, key := range req.RegisteredKeys {
		encodeU2FRegisteredKeyToMap(key, m, fmt.Sprintf("%sregistered_keys.%d.", prefix, i))
	}
}

func encodeU2FRegisteredKeyToMap(key u2f.RegisteredKey, m map[string]string, prefix string) {
	m[prefix+"version"] = key.Version
	m[prefix+"key_handle"] = key.KeyHandle
	m[prefix+"app_id"] = key.AppID
}

func decodeU2FSignRequestFromMap(m map[string]string, prefix string) *u2f.WebSignRequest {
	if _, ok := m[prefix+"app_id"]; !ok {
		return nil
	}
	req := u2f.WebSignRequest{
		AppID:     m[prefix+"app_id"],
		Challenge: m[prefix+"challenge"],
	}
	i := 0
	for {
		key := decodeU2FRegisteredKeyFromMap(m, fmt.Sprintf("%sregistered_keys.%d.", prefix, i))
		if key == nil {
			break
		}
		req.RegisteredKeys = append(req.RegisteredKeys, *key)
		i++
	}
	return &req
}

func decodeU2FRegisteredKeyFromMap(m map[string]string, prefix string) *u2f.RegisteredKey {
	if _, ok := m[prefix+"version"]; !ok {
		return nil
	}
	return &u2f.RegisteredKey{
		Version:   m[prefix+"version"],
		KeyHandle: m[prefix+"key_handle"],
		AppID:     m[prefix+"app_id"],
	}
}