store.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. // Copyright 2016 Nippon Telegraph and Telephone Corporation.
  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. "github.com/coreos/etcd/auth/authpb"
  21. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  22. "github.com/coreos/etcd/mvcc/backend"
  23. "github.com/coreos/pkg/capnslog"
  24. "golang.org/x/crypto/bcrypt"
  25. )
  26. var (
  27. enableFlagKey = []byte("authEnabled")
  28. authBucketName = []byte("auth")
  29. authUsersBucketName = []byte("authUsers")
  30. authRolesBucketName = []byte("authRoles")
  31. plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "auth")
  32. ErrUserAlreadyExist = errors.New("auth: user already exists")
  33. ErrUserNotFound = errors.New("auth: user not found")
  34. ErrRoleAlreadyExist = errors.New("auth: role already exists")
  35. ErrRoleNotFound = errors.New("auth: role not found")
  36. ErrAuthFailed = errors.New("auth: authentication failed, invalid user ID or password")
  37. )
  38. type AuthStore interface {
  39. // AuthEnable turns on the authentication feature
  40. AuthEnable()
  41. // Authenticate does authentication based on given user name and password,
  42. // and returns a token for successful case.
  43. // Note that the generated token is valid only for the member the client
  44. // connected to within fixed time duration. Reauth is required after the duration.
  45. Authenticate(name string, password string) (*pb.AuthenticateResponse, error)
  46. // Recover recovers the state of auth store from the given backend
  47. Recover(b backend.Backend)
  48. // UserAdd adds a new user
  49. UserAdd(r *pb.AuthUserAddRequest) (*pb.AuthUserAddResponse, error)
  50. // UserDelete deletes a user
  51. UserDelete(r *pb.AuthUserDeleteRequest) (*pb.AuthUserDeleteResponse, error)
  52. // UserChangePassword changes a password of a user
  53. UserChangePassword(r *pb.AuthUserChangePasswordRequest) (*pb.AuthUserChangePasswordResponse, error)
  54. // UserGrant grants a role to the user
  55. UserGrant(r *pb.AuthUserGrantRequest) (*pb.AuthUserGrantResponse, error)
  56. // RoleAdd adds a new role
  57. RoleAdd(r *pb.AuthRoleAddRequest) (*pb.AuthRoleAddResponse, error)
  58. // RoleGrant grants a permission to a role
  59. RoleGrant(r *pb.AuthRoleGrantRequest) (*pb.AuthRoleGrantResponse, error)
  60. }
  61. type authStore struct {
  62. be backend.Backend
  63. }
  64. func (as *authStore) AuthEnable() {
  65. value := []byte{1}
  66. b := as.be
  67. tx := b.BatchTx()
  68. tx.Lock()
  69. tx.UnsafePut(authBucketName, enableFlagKey, value)
  70. tx.Unlock()
  71. b.ForceCommit()
  72. plog.Noticef("Authentication enabled")
  73. }
  74. func (as *authStore) Authenticate(name string, password string) (*pb.AuthenticateResponse, error) {
  75. tx := as.be.BatchTx()
  76. tx.Lock()
  77. defer tx.Unlock()
  78. _, vs := tx.UnsafeRange(authUsersBucketName, []byte(name), nil, 0)
  79. if len(vs) != 1 {
  80. plog.Noticef("authentication failed, user %s doesn't exist", name)
  81. return &pb.AuthenticateResponse{}, ErrAuthFailed
  82. }
  83. user := &authpb.User{}
  84. err := user.Unmarshal(vs[0])
  85. if err != nil {
  86. return nil, err
  87. }
  88. if bcrypt.CompareHashAndPassword(user.Password, []byte(password)) != nil {
  89. plog.Noticef("authentication failed, invalid password for user %s", name)
  90. return &pb.AuthenticateResponse{}, ErrAuthFailed
  91. }
  92. token, err := genSimpleTokenForUser(name)
  93. if err != nil {
  94. plog.Errorf("failed to generate simple token: %s", err)
  95. return nil, err
  96. }
  97. plog.Infof("authorized %s, token is %s", name, token)
  98. return &pb.AuthenticateResponse{Token: token}, nil
  99. }
  100. func (as *authStore) Recover(be backend.Backend) {
  101. as.be = be
  102. // TODO(mitake): recovery process
  103. }
  104. func (as *authStore) UserAdd(r *pb.AuthUserAddRequest) (*pb.AuthUserAddResponse, error) {
  105. hashed, err := bcrypt.GenerateFromPassword([]byte(r.Password), bcrypt.DefaultCost)
  106. if err != nil {
  107. plog.Errorf("failed to hash password: %s", err)
  108. return nil, err
  109. }
  110. tx := as.be.BatchTx()
  111. tx.Lock()
  112. defer tx.Unlock()
  113. _, vs := tx.UnsafeRange(authUsersBucketName, []byte(r.Name), nil, 0)
  114. if len(vs) != 0 {
  115. return &pb.AuthUserAddResponse{}, ErrUserAlreadyExist
  116. }
  117. newUser := authpb.User{
  118. Name: []byte(r.Name),
  119. Password: hashed,
  120. }
  121. marshaledUser, merr := newUser.Marshal()
  122. if merr != nil {
  123. plog.Errorf("failed to marshal a new user data: %s", merr)
  124. return nil, merr
  125. }
  126. tx.UnsafePut(authUsersBucketName, []byte(r.Name), marshaledUser)
  127. plog.Noticef("added a new user: %s", r.Name)
  128. return &pb.AuthUserAddResponse{}, nil
  129. }
  130. func (as *authStore) UserDelete(r *pb.AuthUserDeleteRequest) (*pb.AuthUserDeleteResponse, error) {
  131. tx := as.be.BatchTx()
  132. tx.Lock()
  133. defer tx.Unlock()
  134. _, vs := tx.UnsafeRange(authUsersBucketName, []byte(r.Name), nil, 0)
  135. if len(vs) != 1 {
  136. return &pb.AuthUserDeleteResponse{}, ErrUserNotFound
  137. }
  138. tx.UnsafeDelete(authUsersBucketName, []byte(r.Name))
  139. plog.Noticef("deleted a user: %s", r.Name)
  140. return &pb.AuthUserDeleteResponse{}, nil
  141. }
  142. func (as *authStore) UserChangePassword(r *pb.AuthUserChangePasswordRequest) (*pb.AuthUserChangePasswordResponse, error) {
  143. // TODO(mitake): measure the cost of bcrypt.GenerateFromPassword()
  144. // If the cost is too high, we should move the encryption to outside of the raft
  145. hashed, err := bcrypt.GenerateFromPassword([]byte(r.Password), bcrypt.DefaultCost)
  146. if err != nil {
  147. plog.Errorf("failed to hash password: %s", err)
  148. return nil, err
  149. }
  150. tx := as.be.BatchTx()
  151. tx.Lock()
  152. defer tx.Unlock()
  153. _, vs := tx.UnsafeRange(authUsersBucketName, []byte(r.Name), nil, 0)
  154. if len(vs) != 1 {
  155. return &pb.AuthUserChangePasswordResponse{}, ErrUserNotFound
  156. }
  157. updatedUser := authpb.User{
  158. Name: []byte(r.Name),
  159. Password: hashed,
  160. }
  161. marshaledUser, merr := updatedUser.Marshal()
  162. if merr != nil {
  163. plog.Errorf("failed to marshal a new user data: %s", merr)
  164. return nil, merr
  165. }
  166. tx.UnsafePut(authUsersBucketName, []byte(r.Name), marshaledUser)
  167. plog.Noticef("changed a password of a user: %s", r.Name)
  168. return &pb.AuthUserChangePasswordResponse{}, nil
  169. }
  170. func (as *authStore) UserGrant(r *pb.AuthUserGrantRequest) (*pb.AuthUserGrantResponse, error) {
  171. tx := as.be.BatchTx()
  172. tx.Lock()
  173. defer tx.Unlock()
  174. _, vs := tx.UnsafeRange(authUsersBucketName, []byte(r.User), nil, 0)
  175. if len(vs) != 1 {
  176. return nil, ErrUserNotFound
  177. }
  178. user := &authpb.User{}
  179. err := user.Unmarshal(vs[0])
  180. if err != nil {
  181. return nil, err
  182. }
  183. _, vs = tx.UnsafeRange(authRolesBucketName, []byte(r.Role), nil, 0)
  184. if len(vs) != 1 {
  185. return nil, ErrRoleNotFound
  186. }
  187. idx := sort.SearchStrings(user.Roles, r.Role)
  188. if idx < len(user.Roles) && strings.Compare(user.Roles[idx], r.Role) == 0 {
  189. plog.Warningf("user %s is already granted role %s", r.User, r.Role)
  190. return &pb.AuthUserGrantResponse{}, nil
  191. }
  192. user.Roles = append(user.Roles, r.Role)
  193. sort.Sort(sort.StringSlice(user.Roles))
  194. marshaledUser, merr := user.Marshal()
  195. if merr != nil {
  196. return nil, merr
  197. }
  198. tx.UnsafePut(authUsersBucketName, user.Name, marshaledUser)
  199. plog.Noticef("granted role %s to user %s", r.Role, r.User)
  200. return &pb.AuthUserGrantResponse{}, nil
  201. }
  202. func (as *authStore) RoleAdd(r *pb.AuthRoleAddRequest) (*pb.AuthRoleAddResponse, error) {
  203. tx := as.be.BatchTx()
  204. tx.Lock()
  205. defer tx.Unlock()
  206. _, vs := tx.UnsafeRange(authRolesBucketName, []byte(r.Name), nil, 0)
  207. if len(vs) != 0 {
  208. return nil, ErrRoleAlreadyExist
  209. }
  210. newRole := &authpb.Role{
  211. Name: []byte(r.Name),
  212. }
  213. marshaledRole, err := newRole.Marshal()
  214. if err != nil {
  215. return nil, err
  216. }
  217. tx.UnsafePut(authRolesBucketName, []byte(r.Name), marshaledRole)
  218. plog.Noticef("Role %s is created", r.Name)
  219. return &pb.AuthRoleAddResponse{}, nil
  220. }
  221. type permSlice []*authpb.Permission
  222. func (perms permSlice) Len() int {
  223. return len(perms)
  224. }
  225. func (perms permSlice) Less(i, j int) bool {
  226. return bytes.Compare(perms[i].Key, perms[j].Key) < 0
  227. }
  228. func (perms permSlice) Swap(i, j int) {
  229. perms[i], perms[j] = perms[j], perms[i]
  230. }
  231. func (as *authStore) RoleGrant(r *pb.AuthRoleGrantRequest) (*pb.AuthRoleGrantResponse, error) {
  232. tx := as.be.BatchTx()
  233. tx.Lock()
  234. defer tx.Unlock()
  235. _, vs := tx.UnsafeRange(authRolesBucketName, []byte(r.Name), nil, 0)
  236. if len(vs) != 1 {
  237. return nil, ErrRoleNotFound
  238. }
  239. role := &authpb.Role{}
  240. err := role.Unmarshal(vs[0])
  241. if err != nil {
  242. plog.Errorf("failed to unmarshal a role %s: %s", r.Name, err)
  243. return nil, err
  244. }
  245. idx := sort.Search(len(role.KeyPermission), func(i int) bool {
  246. return bytes.Compare(role.KeyPermission[i].Key, []byte(r.Perm.Key)) >= 0
  247. })
  248. if idx < len(role.KeyPermission) && bytes.Equal(role.KeyPermission[idx].Key, r.Perm.Key) {
  249. // update existing permission
  250. role.KeyPermission[idx].PermType = r.Perm.PermType
  251. } else {
  252. // append new permission to the role
  253. newPerm := &authpb.Permission{
  254. Key: []byte(r.Perm.Key),
  255. PermType: r.Perm.PermType,
  256. }
  257. role.KeyPermission = append(role.KeyPermission, newPerm)
  258. sort.Sort(permSlice(role.KeyPermission))
  259. }
  260. marshaledRole, merr := role.Marshal()
  261. if merr != nil {
  262. plog.Errorf("failed to marshal updated role %s: %s", r.Name, merr)
  263. return nil, merr
  264. }
  265. tx.UnsafePut(authRolesBucketName, []byte(r.Name), marshaledRole)
  266. 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)])
  267. return &pb.AuthRoleGrantResponse{}, nil
  268. }
  269. func NewAuthStore(be backend.Backend) *authStore {
  270. tx := be.BatchTx()
  271. tx.Lock()
  272. tx.UnsafeCreateBucket(authBucketName)
  273. tx.UnsafeCreateBucket(authUsersBucketName)
  274. tx.UnsafeCreateBucket(authRolesBucketName)
  275. tx.Unlock()
  276. be.ForceCommit()
  277. return &authStore{
  278. be: be,
  279. }
  280. }