store.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. // Copyright 2016 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package auth
  15. import (
  16. "bytes"
  17. "errors"
  18. "sort"
  19. "strings"
  20. "sync"
  21. "github.com/coreos/etcd/auth/authpb"
  22. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  23. "github.com/coreos/etcd/mvcc/backend"
  24. "github.com/coreos/pkg/capnslog"
  25. "golang.org/x/crypto/bcrypt"
  26. )
  27. var (
  28. enableFlagKey = []byte("authEnabled")
  29. authBucketName = []byte("auth")
  30. authUsersBucketName = []byte("authUsers")
  31. authRolesBucketName = []byte("authRoles")
  32. plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "auth")
  33. ErrUserAlreadyExist = errors.New("auth: user already exists")
  34. ErrUserNotFound = errors.New("auth: user not found")
  35. ErrRoleAlreadyExist = errors.New("auth: role already exists")
  36. ErrRoleNotFound = errors.New("auth: role not found")
  37. ErrAuthFailed = errors.New("auth: authentication failed, invalid user ID or password")
  38. )
  39. type AuthStore interface {
  40. // AuthEnable turns on the authentication feature
  41. AuthEnable()
  42. // AuthDisable turns off the authentication feature
  43. AuthDisable()
  44. // Authenticate does authentication based on given user name and password,
  45. // and returns a token for successful case.
  46. // Note that the generated token is valid only for the member the client
  47. // connected to within fixed time duration. Reauth is required after the duration.
  48. Authenticate(name string, password string) (*pb.AuthenticateResponse, error)
  49. // Recover recovers the state of auth store from the given backend
  50. Recover(b backend.Backend)
  51. // UserAdd adds a new user
  52. UserAdd(r *pb.AuthUserAddRequest) (*pb.AuthUserAddResponse, error)
  53. // UserDelete deletes a user
  54. UserDelete(r *pb.AuthUserDeleteRequest) (*pb.AuthUserDeleteResponse, error)
  55. // UserChangePassword changes a password of a user
  56. UserChangePassword(r *pb.AuthUserChangePasswordRequest) (*pb.AuthUserChangePasswordResponse, error)
  57. // UserGrant grants a role to the user
  58. UserGrant(r *pb.AuthUserGrantRequest) (*pb.AuthUserGrantResponse, error)
  59. // RoleAdd adds a new role
  60. RoleAdd(r *pb.AuthRoleAddRequest) (*pb.AuthRoleAddResponse, error)
  61. // RoleGrant grants a permission to a role
  62. RoleGrant(r *pb.AuthRoleGrantRequest) (*pb.AuthRoleGrantResponse, error)
  63. // UsernameFromToken gets a username from the given Token
  64. UsernameFromToken(token string) (string, bool)
  65. // IsPutPermitted checks put permission of the user
  66. IsPutPermitted(header *pb.RequestHeader, key string) bool
  67. // IsRangePermitted checks range permission of the user
  68. IsRangePermitted(header *pb.RequestHeader, key string) bool
  69. }
  70. type authStore struct {
  71. be backend.Backend
  72. enabled bool
  73. enabledMu sync.RWMutex
  74. }
  75. func (as *authStore) AuthEnable() {
  76. value := []byte{1}
  77. b := as.be
  78. tx := b.BatchTx()
  79. tx.Lock()
  80. tx.UnsafePut(authBucketName, enableFlagKey, value)
  81. tx.Unlock()
  82. b.ForceCommit()
  83. as.enabledMu.Lock()
  84. as.enabled = true
  85. as.enabledMu.Unlock()
  86. plog.Noticef("Authentication enabled")
  87. }
  88. func (as *authStore) AuthDisable() {
  89. value := []byte{0}
  90. b := as.be
  91. tx := b.BatchTx()
  92. tx.Lock()
  93. tx.UnsafePut(authBucketName, enableFlagKey, value)
  94. tx.Unlock()
  95. b.ForceCommit()
  96. as.enabledMu.Lock()
  97. as.enabled = false
  98. as.enabledMu.Unlock()
  99. plog.Noticef("Authentication disabled")
  100. }
  101. func (as *authStore) Authenticate(name string, password string) (*pb.AuthenticateResponse, error) {
  102. tx := as.be.BatchTx()
  103. tx.Lock()
  104. defer tx.Unlock()
  105. _, vs := tx.UnsafeRange(authUsersBucketName, []byte(name), nil, 0)
  106. if len(vs) != 1 {
  107. plog.Noticef("authentication failed, user %s doesn't exist", name)
  108. return &pb.AuthenticateResponse{}, ErrAuthFailed
  109. }
  110. user := &authpb.User{}
  111. err := user.Unmarshal(vs[0])
  112. if err != nil {
  113. return nil, err
  114. }
  115. if bcrypt.CompareHashAndPassword(user.Password, []byte(password)) != nil {
  116. plog.Noticef("authentication failed, invalid password for user %s", name)
  117. return &pb.AuthenticateResponse{}, ErrAuthFailed
  118. }
  119. token, err := genSimpleTokenForUser(name)
  120. if err != nil {
  121. plog.Errorf("failed to generate simple token: %s", err)
  122. return nil, err
  123. }
  124. plog.Infof("authorized %s, token is %s", name, token)
  125. return &pb.AuthenticateResponse{Token: token}, nil
  126. }
  127. func (as *authStore) Recover(be backend.Backend) {
  128. as.be = be
  129. // TODO(mitake): recovery process
  130. }
  131. func (as *authStore) UserAdd(r *pb.AuthUserAddRequest) (*pb.AuthUserAddResponse, error) {
  132. hashed, err := bcrypt.GenerateFromPassword([]byte(r.Password), bcrypt.DefaultCost)
  133. if err != nil {
  134. plog.Errorf("failed to hash password: %s", err)
  135. return nil, err
  136. }
  137. tx := as.be.BatchTx()
  138. tx.Lock()
  139. defer tx.Unlock()
  140. _, vs := tx.UnsafeRange(authUsersBucketName, []byte(r.Name), nil, 0)
  141. if len(vs) != 0 {
  142. return &pb.AuthUserAddResponse{}, ErrUserAlreadyExist
  143. }
  144. newUser := authpb.User{
  145. Name: []byte(r.Name),
  146. Password: hashed,
  147. }
  148. marshaledUser, merr := newUser.Marshal()
  149. if merr != nil {
  150. plog.Errorf("failed to marshal a new user data: %s", merr)
  151. return nil, merr
  152. }
  153. tx.UnsafePut(authUsersBucketName, []byte(r.Name), marshaledUser)
  154. plog.Noticef("added a new user: %s", r.Name)
  155. return &pb.AuthUserAddResponse{}, nil
  156. }
  157. func (as *authStore) UserDelete(r *pb.AuthUserDeleteRequest) (*pb.AuthUserDeleteResponse, error) {
  158. tx := as.be.BatchTx()
  159. tx.Lock()
  160. defer tx.Unlock()
  161. _, vs := tx.UnsafeRange(authUsersBucketName, []byte(r.Name), nil, 0)
  162. if len(vs) != 1 {
  163. return &pb.AuthUserDeleteResponse{}, ErrUserNotFound
  164. }
  165. tx.UnsafeDelete(authUsersBucketName, []byte(r.Name))
  166. plog.Noticef("deleted a user: %s", r.Name)
  167. return &pb.AuthUserDeleteResponse{}, nil
  168. }
  169. func (as *authStore) UserChangePassword(r *pb.AuthUserChangePasswordRequest) (*pb.AuthUserChangePasswordResponse, error) {
  170. // TODO(mitake): measure the cost of bcrypt.GenerateFromPassword()
  171. // If the cost is too high, we should move the encryption to outside of the raft
  172. hashed, err := bcrypt.GenerateFromPassword([]byte(r.Password), bcrypt.DefaultCost)
  173. if err != nil {
  174. plog.Errorf("failed to hash password: %s", err)
  175. return nil, err
  176. }
  177. tx := as.be.BatchTx()
  178. tx.Lock()
  179. defer tx.Unlock()
  180. _, vs := tx.UnsafeRange(authUsersBucketName, []byte(r.Name), nil, 0)
  181. if len(vs) != 1 {
  182. return &pb.AuthUserChangePasswordResponse{}, ErrUserNotFound
  183. }
  184. updatedUser := authpb.User{
  185. Name: []byte(r.Name),
  186. Password: hashed,
  187. }
  188. marshaledUser, merr := updatedUser.Marshal()
  189. if merr != nil {
  190. plog.Errorf("failed to marshal a new user data: %s", merr)
  191. return nil, merr
  192. }
  193. tx.UnsafePut(authUsersBucketName, []byte(r.Name), marshaledUser)
  194. plog.Noticef("changed a password of a user: %s", r.Name)
  195. return &pb.AuthUserChangePasswordResponse{}, nil
  196. }
  197. func (as *authStore) UserGrant(r *pb.AuthUserGrantRequest) (*pb.AuthUserGrantResponse, error) {
  198. tx := as.be.BatchTx()
  199. tx.Lock()
  200. defer tx.Unlock()
  201. _, vs := tx.UnsafeRange(authUsersBucketName, []byte(r.User), nil, 0)
  202. if len(vs) != 1 {
  203. return nil, ErrUserNotFound
  204. }
  205. user := &authpb.User{}
  206. err := user.Unmarshal(vs[0])
  207. if err != nil {
  208. return nil, err
  209. }
  210. _, vs = tx.UnsafeRange(authRolesBucketName, []byte(r.Role), nil, 0)
  211. if len(vs) != 1 {
  212. return nil, ErrRoleNotFound
  213. }
  214. idx := sort.SearchStrings(user.Roles, r.Role)
  215. if idx < len(user.Roles) && strings.Compare(user.Roles[idx], r.Role) == 0 {
  216. plog.Warningf("user %s is already granted role %s", r.User, r.Role)
  217. return &pb.AuthUserGrantResponse{}, nil
  218. }
  219. user.Roles = append(user.Roles, r.Role)
  220. sort.Sort(sort.StringSlice(user.Roles))
  221. marshaledUser, merr := user.Marshal()
  222. if merr != nil {
  223. return nil, merr
  224. }
  225. tx.UnsafePut(authUsersBucketName, user.Name, marshaledUser)
  226. plog.Noticef("granted role %s to user %s", r.Role, r.User)
  227. return &pb.AuthUserGrantResponse{}, nil
  228. }
  229. func (as *authStore) RoleAdd(r *pb.AuthRoleAddRequest) (*pb.AuthRoleAddResponse, error) {
  230. tx := as.be.BatchTx()
  231. tx.Lock()
  232. defer tx.Unlock()
  233. _, vs := tx.UnsafeRange(authRolesBucketName, []byte(r.Name), nil, 0)
  234. if len(vs) != 0 {
  235. return nil, ErrRoleAlreadyExist
  236. }
  237. newRole := &authpb.Role{
  238. Name: []byte(r.Name),
  239. }
  240. marshaledRole, err := newRole.Marshal()
  241. if err != nil {
  242. return nil, err
  243. }
  244. tx.UnsafePut(authRolesBucketName, []byte(r.Name), marshaledRole)
  245. plog.Noticef("Role %s is created", r.Name)
  246. return &pb.AuthRoleAddResponse{}, nil
  247. }
  248. func (as *authStore) UsernameFromToken(token string) (string, bool) {
  249. simpleTokensMu.RLock()
  250. defer simpleTokensMu.RUnlock()
  251. t, ok := simpleTokens[token]
  252. return t, ok
  253. }
  254. type permSlice []*authpb.Permission
  255. func (perms permSlice) Len() int {
  256. return len(perms)
  257. }
  258. func (perms permSlice) Less(i, j int) bool {
  259. return bytes.Compare(perms[i].Key, perms[j].Key) < 0
  260. }
  261. func (perms permSlice) Swap(i, j int) {
  262. perms[i], perms[j] = perms[j], perms[i]
  263. }
  264. func (as *authStore) RoleGrant(r *pb.AuthRoleGrantRequest) (*pb.AuthRoleGrantResponse, error) {
  265. tx := as.be.BatchTx()
  266. tx.Lock()
  267. defer tx.Unlock()
  268. _, vs := tx.UnsafeRange(authRolesBucketName, []byte(r.Name), nil, 0)
  269. if len(vs) != 1 {
  270. return nil, ErrRoleNotFound
  271. }
  272. role := &authpb.Role{}
  273. err := role.Unmarshal(vs[0])
  274. if err != nil {
  275. plog.Errorf("failed to unmarshal a role %s: %s", r.Name, err)
  276. return nil, err
  277. }
  278. idx := sort.Search(len(role.KeyPermission), func(i int) bool {
  279. return bytes.Compare(role.KeyPermission[i].Key, []byte(r.Perm.Key)) >= 0
  280. })
  281. if idx < len(role.KeyPermission) && bytes.Equal(role.KeyPermission[idx].Key, r.Perm.Key) {
  282. // update existing permission
  283. role.KeyPermission[idx].PermType = r.Perm.PermType
  284. } else {
  285. // append new permission to the role
  286. newPerm := &authpb.Permission{
  287. Key: []byte(r.Perm.Key),
  288. PermType: r.Perm.PermType,
  289. }
  290. role.KeyPermission = append(role.KeyPermission, newPerm)
  291. sort.Sort(permSlice(role.KeyPermission))
  292. }
  293. marshaledRole, merr := role.Marshal()
  294. if merr != nil {
  295. plog.Errorf("failed to marshal updated role %s: %s", r.Name, merr)
  296. return nil, merr
  297. }
  298. tx.UnsafePut(authRolesBucketName, []byte(r.Name), marshaledRole)
  299. plog.Noticef("role %s's permission of key %s is updated as %s", r.Name, r.Perm.Key, authpb.Permission_Type_name[int32(r.Perm.PermType)])
  300. return &pb.AuthRoleGrantResponse{}, nil
  301. }
  302. func (as *authStore) isOpPermitted(userName string, key string, write bool, read bool) bool {
  303. // TODO(mitake): this function would be costly so we need a caching mechanism
  304. if !as.isAuthEnabled() {
  305. return true
  306. }
  307. tx := as.be.BatchTx()
  308. tx.Lock()
  309. defer tx.Unlock()
  310. _, vs := tx.UnsafeRange(authUsersBucketName, []byte(userName), nil, 0)
  311. if len(vs) != 1 {
  312. plog.Errorf("invalid user name %s for permission checking", userName)
  313. return false
  314. }
  315. user := &authpb.User{}
  316. err := user.Unmarshal(vs[0])
  317. if err != nil {
  318. plog.Errorf("failed to unmarshal user struct (name: %s): %s", userName, err)
  319. return false
  320. }
  321. for _, roleName := range user.Roles {
  322. _, vs := tx.UnsafeRange(authRolesBucketName, []byte(roleName), nil, 0)
  323. if len(vs) != 1 {
  324. plog.Errorf("invalid role name %s for permission checking", roleName)
  325. return false
  326. }
  327. role := &authpb.Role{}
  328. err := role.Unmarshal(vs[0])
  329. if err != nil {
  330. plog.Errorf("failed to unmarshal a role %s: %s", roleName, err)
  331. return false
  332. }
  333. for _, perm := range role.KeyPermission {
  334. if bytes.Equal(perm.Key, []byte(key)) {
  335. if perm.PermType == authpb.READWRITE {
  336. return true
  337. }
  338. if write && !read && perm.PermType == authpb.WRITE {
  339. return true
  340. }
  341. if read && !write && perm.PermType == authpb.READ {
  342. return true
  343. }
  344. }
  345. }
  346. }
  347. return false
  348. }
  349. func (as *authStore) IsPutPermitted(header *pb.RequestHeader, key string) bool {
  350. return as.isOpPermitted(header.Username, key, true, false)
  351. }
  352. func (as *authStore) IsRangePermitted(header *pb.RequestHeader, key string) bool {
  353. return as.isOpPermitted(header.Username, key, false, true)
  354. }
  355. func (as *authStore) isAuthEnabled() bool {
  356. as.enabledMu.RLock()
  357. defer as.enabledMu.RUnlock()
  358. return as.enabled
  359. }
  360. func NewAuthStore(be backend.Backend) *authStore {
  361. tx := be.BatchTx()
  362. tx.Lock()
  363. tx.UnsafeCreateBucket(authBucketName)
  364. tx.UnsafeCreateBucket(authUsersBucketName)
  365. tx.UnsafeCreateBucket(authRolesBucketName)
  366. tx.Unlock()
  367. be.ForceCommit()
  368. return &authStore{
  369. be: be,
  370. }
  371. }