store.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122
  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. "context"
  18. "encoding/binary"
  19. "errors"
  20. "sort"
  21. "strings"
  22. "sync"
  23. "sync/atomic"
  24. "github.com/coreos/etcd/auth/authpb"
  25. "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
  26. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  27. "github.com/coreos/etcd/mvcc/backend"
  28. "github.com/coreos/pkg/capnslog"
  29. "golang.org/x/crypto/bcrypt"
  30. "google.golang.org/grpc/credentials"
  31. "google.golang.org/grpc/metadata"
  32. "google.golang.org/grpc/peer"
  33. )
  34. var (
  35. enableFlagKey = []byte("authEnabled")
  36. authEnabled = []byte{1}
  37. authDisabled = []byte{0}
  38. revisionKey = []byte("authRevision")
  39. authBucketName = []byte("auth")
  40. authUsersBucketName = []byte("authUsers")
  41. authRolesBucketName = []byte("authRoles")
  42. plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "auth")
  43. ErrRootUserNotExist = errors.New("auth: root user does not exist")
  44. ErrRootRoleNotExist = errors.New("auth: root user does not have root role")
  45. ErrUserAlreadyExist = errors.New("auth: user already exists")
  46. ErrUserEmpty = errors.New("auth: user name is empty")
  47. ErrUserNotFound = errors.New("auth: user not found")
  48. ErrRoleAlreadyExist = errors.New("auth: role already exists")
  49. ErrRoleNotFound = errors.New("auth: role not found")
  50. ErrAuthFailed = errors.New("auth: authentication failed, invalid user ID or password")
  51. ErrPermissionDenied = errors.New("auth: permission denied")
  52. ErrRoleNotGranted = errors.New("auth: role is not granted to the user")
  53. ErrPermissionNotGranted = errors.New("auth: permission is not granted to the role")
  54. ErrAuthNotEnabled = errors.New("auth: authentication is not enabled")
  55. ErrAuthOldRevision = errors.New("auth: revision in header is old")
  56. ErrInvalidAuthToken = errors.New("auth: invalid auth token")
  57. ErrInvalidAuthOpts = errors.New("auth: invalid auth options")
  58. ErrInvalidAuthMgmt = errors.New("auth: invalid auth management")
  59. // BcryptCost is the algorithm cost / strength for hashing auth passwords
  60. BcryptCost = bcrypt.DefaultCost
  61. )
  62. const (
  63. rootUser = "root"
  64. rootRole = "root"
  65. revBytesLen = 8
  66. )
  67. type AuthInfo struct {
  68. Username string
  69. Revision uint64
  70. }
  71. // AuthenticateParamIndex is used for a key of context in the parameters of Authenticate()
  72. type AuthenticateParamIndex struct{}
  73. // AuthenticateParamSimpleTokenPrefix is used for a key of context in the parameters of Authenticate()
  74. type AuthenticateParamSimpleTokenPrefix struct{}
  75. type AuthStore interface {
  76. // AuthEnable turns on the authentication feature
  77. AuthEnable() error
  78. // AuthDisable turns off the authentication feature
  79. AuthDisable()
  80. // IsAuthEnabled returns true if the authentication feature is enabled.
  81. IsAuthEnabled() bool
  82. // Authenticate does authentication based on given user name and password
  83. Authenticate(ctx context.Context, username, password string) (*pb.AuthenticateResponse, error)
  84. // Recover recovers the state of auth store from the given backend
  85. Recover(b backend.Backend)
  86. // UserAdd adds a new user
  87. UserAdd(r *pb.AuthUserAddRequest) (*pb.AuthUserAddResponse, error)
  88. // UserDelete deletes a user
  89. UserDelete(r *pb.AuthUserDeleteRequest) (*pb.AuthUserDeleteResponse, error)
  90. // UserChangePassword changes a password of a user
  91. UserChangePassword(r *pb.AuthUserChangePasswordRequest) (*pb.AuthUserChangePasswordResponse, error)
  92. // UserGrantRole grants a role to the user
  93. UserGrantRole(r *pb.AuthUserGrantRoleRequest) (*pb.AuthUserGrantRoleResponse, error)
  94. // UserGet gets the detailed information of a users
  95. UserGet(r *pb.AuthUserGetRequest) (*pb.AuthUserGetResponse, error)
  96. // UserRevokeRole revokes a role of a user
  97. UserRevokeRole(r *pb.AuthUserRevokeRoleRequest) (*pb.AuthUserRevokeRoleResponse, error)
  98. // RoleAdd adds a new role
  99. RoleAdd(r *pb.AuthRoleAddRequest) (*pb.AuthRoleAddResponse, error)
  100. // RoleGrantPermission grants a permission to a role
  101. RoleGrantPermission(r *pb.AuthRoleGrantPermissionRequest) (*pb.AuthRoleGrantPermissionResponse, error)
  102. // RoleGet gets the detailed information of a role
  103. RoleGet(r *pb.AuthRoleGetRequest) (*pb.AuthRoleGetResponse, error)
  104. // RoleRevokePermission gets the detailed information of a role
  105. RoleRevokePermission(r *pb.AuthRoleRevokePermissionRequest) (*pb.AuthRoleRevokePermissionResponse, error)
  106. // RoleDelete gets the detailed information of a role
  107. RoleDelete(r *pb.AuthRoleDeleteRequest) (*pb.AuthRoleDeleteResponse, error)
  108. // UserList gets a list of all users
  109. UserList(r *pb.AuthUserListRequest) (*pb.AuthUserListResponse, error)
  110. // RoleList gets a list of all roles
  111. RoleList(r *pb.AuthRoleListRequest) (*pb.AuthRoleListResponse, error)
  112. // IsPutPermitted checks put permission of the user
  113. IsPutPermitted(authInfo *AuthInfo, key []byte) error
  114. // IsRangePermitted checks range permission of the user
  115. IsRangePermitted(authInfo *AuthInfo, key, rangeEnd []byte) error
  116. // IsDeleteRangePermitted checks delete-range permission of the user
  117. IsDeleteRangePermitted(authInfo *AuthInfo, key, rangeEnd []byte) error
  118. // IsAdminPermitted checks admin permission of the user
  119. IsAdminPermitted(authInfo *AuthInfo) error
  120. // GenTokenPrefix produces a random string in a case of simple token
  121. // in a case of JWT, it produces an empty string
  122. GenTokenPrefix() (string, error)
  123. // Revision gets current revision of authStore
  124. Revision() uint64
  125. // CheckPassword checks a given pair of username and password is correct
  126. CheckPassword(username, password string) (uint64, error)
  127. // Close does cleanup of AuthStore
  128. Close() error
  129. // AuthInfoFromCtx gets AuthInfo from gRPC's context
  130. AuthInfoFromCtx(ctx context.Context) (*AuthInfo, error)
  131. // AuthInfoFromTLS gets AuthInfo from TLS info of gRPC's context
  132. AuthInfoFromTLS(ctx context.Context) *AuthInfo
  133. // WithRoot generates and installs a token that can be used as a root credential
  134. WithRoot(ctx context.Context) context.Context
  135. // HasRole checks that user has role
  136. HasRole(user, role string) bool
  137. }
  138. type TokenProvider interface {
  139. info(ctx context.Context, token string, revision uint64) (*AuthInfo, bool)
  140. assign(ctx context.Context, username string, revision uint64) (string, error)
  141. enable()
  142. disable()
  143. invalidateUser(string)
  144. genTokenPrefix() (string, error)
  145. }
  146. type authStore struct {
  147. // atomic operations; need 64-bit align, or 32-bit tests will crash
  148. revision uint64
  149. be backend.Backend
  150. enabled bool
  151. enabledMu sync.RWMutex
  152. rangePermCache map[string]*unifiedRangePermissions // username -> unifiedRangePermissions
  153. tokenProvider TokenProvider
  154. }
  155. func (as *authStore) AuthEnable() error {
  156. as.enabledMu.Lock()
  157. defer as.enabledMu.Unlock()
  158. if as.enabled {
  159. plog.Noticef("Authentication already enabled")
  160. return nil
  161. }
  162. b := as.be
  163. tx := b.BatchTx()
  164. tx.Lock()
  165. defer func() {
  166. tx.Unlock()
  167. b.ForceCommit()
  168. }()
  169. u := getUser(tx, rootUser)
  170. if u == nil {
  171. return ErrRootUserNotExist
  172. }
  173. if !hasRootRole(u) {
  174. return ErrRootRoleNotExist
  175. }
  176. tx.UnsafePut(authBucketName, enableFlagKey, authEnabled)
  177. as.enabled = true
  178. as.tokenProvider.enable()
  179. as.rangePermCache = make(map[string]*unifiedRangePermissions)
  180. as.setRevision(getRevision(tx))
  181. plog.Noticef("Authentication enabled")
  182. return nil
  183. }
  184. func (as *authStore) AuthDisable() {
  185. as.enabledMu.Lock()
  186. defer as.enabledMu.Unlock()
  187. if !as.enabled {
  188. return
  189. }
  190. b := as.be
  191. tx := b.BatchTx()
  192. tx.Lock()
  193. tx.UnsafePut(authBucketName, enableFlagKey, authDisabled)
  194. as.commitRevision(tx)
  195. tx.Unlock()
  196. b.ForceCommit()
  197. as.enabled = false
  198. as.tokenProvider.disable()
  199. plog.Noticef("Authentication disabled")
  200. }
  201. func (as *authStore) Close() error {
  202. as.enabledMu.Lock()
  203. defer as.enabledMu.Unlock()
  204. if !as.enabled {
  205. return nil
  206. }
  207. as.tokenProvider.disable()
  208. return nil
  209. }
  210. func (as *authStore) Authenticate(ctx context.Context, username, password string) (*pb.AuthenticateResponse, error) {
  211. if !as.IsAuthEnabled() {
  212. return nil, ErrAuthNotEnabled
  213. }
  214. tx := as.be.BatchTx()
  215. tx.Lock()
  216. defer tx.Unlock()
  217. user := getUser(tx, username)
  218. if user == nil {
  219. return nil, ErrAuthFailed
  220. }
  221. // Password checking is already performed in the API layer, so we don't need to check for now.
  222. // Staleness of password can be detected with OCC in the API layer, too.
  223. token, err := as.tokenProvider.assign(ctx, username, as.Revision())
  224. if err != nil {
  225. return nil, err
  226. }
  227. plog.Debugf("authorized %s, token is %s", username, token)
  228. return &pb.AuthenticateResponse{Token: token}, nil
  229. }
  230. func (as *authStore) CheckPassword(username, password string) (uint64, error) {
  231. if !as.IsAuthEnabled() {
  232. return 0, ErrAuthNotEnabled
  233. }
  234. tx := as.be.BatchTx()
  235. tx.Lock()
  236. defer tx.Unlock()
  237. user := getUser(tx, username)
  238. if user == nil {
  239. return 0, ErrAuthFailed
  240. }
  241. if bcrypt.CompareHashAndPassword(user.Password, []byte(password)) != nil {
  242. plog.Noticef("authentication failed, invalid password for user %s", username)
  243. return 0, ErrAuthFailed
  244. }
  245. return getRevision(tx), nil
  246. }
  247. func (as *authStore) Recover(be backend.Backend) {
  248. enabled := false
  249. as.be = be
  250. tx := be.BatchTx()
  251. tx.Lock()
  252. _, vs := tx.UnsafeRange(authBucketName, enableFlagKey, nil, 0)
  253. if len(vs) == 1 {
  254. if bytes.Equal(vs[0], authEnabled) {
  255. enabled = true
  256. }
  257. }
  258. as.setRevision(getRevision(tx))
  259. tx.Unlock()
  260. as.enabledMu.Lock()
  261. as.enabled = enabled
  262. as.enabledMu.Unlock()
  263. }
  264. func (as *authStore) UserAdd(r *pb.AuthUserAddRequest) (*pb.AuthUserAddResponse, error) {
  265. if len(r.Name) == 0 {
  266. return nil, ErrUserEmpty
  267. }
  268. hashed, err := bcrypt.GenerateFromPassword([]byte(r.Password), BcryptCost)
  269. if err != nil {
  270. plog.Errorf("failed to hash password: %s", err)
  271. return nil, err
  272. }
  273. tx := as.be.BatchTx()
  274. tx.Lock()
  275. defer tx.Unlock()
  276. user := getUser(tx, r.Name)
  277. if user != nil {
  278. return nil, ErrUserAlreadyExist
  279. }
  280. newUser := &authpb.User{
  281. Name: []byte(r.Name),
  282. Password: hashed,
  283. }
  284. putUser(tx, newUser)
  285. as.commitRevision(tx)
  286. plog.Noticef("added a new user: %s", r.Name)
  287. return &pb.AuthUserAddResponse{}, nil
  288. }
  289. func (as *authStore) UserDelete(r *pb.AuthUserDeleteRequest) (*pb.AuthUserDeleteResponse, error) {
  290. if as.enabled && strings.Compare(r.Name, rootUser) == 0 {
  291. plog.Errorf("the user root must not be deleted")
  292. return nil, ErrInvalidAuthMgmt
  293. }
  294. tx := as.be.BatchTx()
  295. tx.Lock()
  296. defer tx.Unlock()
  297. user := getUser(tx, r.Name)
  298. if user == nil {
  299. return nil, ErrUserNotFound
  300. }
  301. delUser(tx, r.Name)
  302. as.commitRevision(tx)
  303. as.invalidateCachedPerm(r.Name)
  304. as.tokenProvider.invalidateUser(r.Name)
  305. plog.Noticef("deleted a user: %s", r.Name)
  306. return &pb.AuthUserDeleteResponse{}, nil
  307. }
  308. func (as *authStore) UserChangePassword(r *pb.AuthUserChangePasswordRequest) (*pb.AuthUserChangePasswordResponse, error) {
  309. // TODO(mitake): measure the cost of bcrypt.GenerateFromPassword()
  310. // If the cost is too high, we should move the encryption to outside of the raft
  311. hashed, err := bcrypt.GenerateFromPassword([]byte(r.Password), BcryptCost)
  312. if err != nil {
  313. plog.Errorf("failed to hash password: %s", err)
  314. return nil, err
  315. }
  316. tx := as.be.BatchTx()
  317. tx.Lock()
  318. defer tx.Unlock()
  319. user := getUser(tx, r.Name)
  320. if user == nil {
  321. return nil, ErrUserNotFound
  322. }
  323. updatedUser := &authpb.User{
  324. Name: []byte(r.Name),
  325. Roles: user.Roles,
  326. Password: hashed,
  327. }
  328. putUser(tx, updatedUser)
  329. as.commitRevision(tx)
  330. as.invalidateCachedPerm(r.Name)
  331. as.tokenProvider.invalidateUser(r.Name)
  332. plog.Noticef("changed a password of a user: %s", r.Name)
  333. return &pb.AuthUserChangePasswordResponse{}, nil
  334. }
  335. func (as *authStore) UserGrantRole(r *pb.AuthUserGrantRoleRequest) (*pb.AuthUserGrantRoleResponse, error) {
  336. tx := as.be.BatchTx()
  337. tx.Lock()
  338. defer tx.Unlock()
  339. user := getUser(tx, r.User)
  340. if user == nil {
  341. return nil, ErrUserNotFound
  342. }
  343. if r.Role != rootRole {
  344. role := getRole(tx, r.Role)
  345. if role == nil {
  346. return nil, ErrRoleNotFound
  347. }
  348. }
  349. idx := sort.SearchStrings(user.Roles, r.Role)
  350. if idx < len(user.Roles) && strings.Compare(user.Roles[idx], r.Role) == 0 {
  351. plog.Warningf("user %s is already granted role %s", r.User, r.Role)
  352. return &pb.AuthUserGrantRoleResponse{}, nil
  353. }
  354. user.Roles = append(user.Roles, r.Role)
  355. sort.Strings(user.Roles)
  356. putUser(tx, user)
  357. as.invalidateCachedPerm(r.User)
  358. as.commitRevision(tx)
  359. plog.Noticef("granted role %s to user %s", r.Role, r.User)
  360. return &pb.AuthUserGrantRoleResponse{}, nil
  361. }
  362. func (as *authStore) UserGet(r *pb.AuthUserGetRequest) (*pb.AuthUserGetResponse, error) {
  363. tx := as.be.BatchTx()
  364. tx.Lock()
  365. user := getUser(tx, r.Name)
  366. tx.Unlock()
  367. if user == nil {
  368. return nil, ErrUserNotFound
  369. }
  370. var resp pb.AuthUserGetResponse
  371. resp.Roles = append(resp.Roles, user.Roles...)
  372. return &resp, nil
  373. }
  374. func (as *authStore) UserList(r *pb.AuthUserListRequest) (*pb.AuthUserListResponse, error) {
  375. tx := as.be.BatchTx()
  376. tx.Lock()
  377. users := getAllUsers(tx)
  378. tx.Unlock()
  379. resp := &pb.AuthUserListResponse{Users: make([]string, len(users))}
  380. for i := range users {
  381. resp.Users[i] = string(users[i].Name)
  382. }
  383. return resp, nil
  384. }
  385. func (as *authStore) UserRevokeRole(r *pb.AuthUserRevokeRoleRequest) (*pb.AuthUserRevokeRoleResponse, error) {
  386. if as.enabled && strings.Compare(r.Name, rootUser) == 0 && strings.Compare(r.Role, rootRole) == 0 {
  387. plog.Errorf("the role root must not be revoked from the user root")
  388. return nil, ErrInvalidAuthMgmt
  389. }
  390. tx := as.be.BatchTx()
  391. tx.Lock()
  392. defer tx.Unlock()
  393. user := getUser(tx, r.Name)
  394. if user == nil {
  395. return nil, ErrUserNotFound
  396. }
  397. updatedUser := &authpb.User{
  398. Name: user.Name,
  399. Password: user.Password,
  400. }
  401. for _, role := range user.Roles {
  402. if strings.Compare(role, r.Role) != 0 {
  403. updatedUser.Roles = append(updatedUser.Roles, role)
  404. }
  405. }
  406. if len(updatedUser.Roles) == len(user.Roles) {
  407. return nil, ErrRoleNotGranted
  408. }
  409. putUser(tx, updatedUser)
  410. as.invalidateCachedPerm(r.Name)
  411. as.commitRevision(tx)
  412. plog.Noticef("revoked role %s from user %s", r.Role, r.Name)
  413. return &pb.AuthUserRevokeRoleResponse{}, nil
  414. }
  415. func (as *authStore) RoleGet(r *pb.AuthRoleGetRequest) (*pb.AuthRoleGetResponse, error) {
  416. tx := as.be.BatchTx()
  417. tx.Lock()
  418. defer tx.Unlock()
  419. var resp pb.AuthRoleGetResponse
  420. role := getRole(tx, r.Role)
  421. if role == nil {
  422. return nil, ErrRoleNotFound
  423. }
  424. resp.Perm = append(resp.Perm, role.KeyPermission...)
  425. return &resp, nil
  426. }
  427. func (as *authStore) RoleList(r *pb.AuthRoleListRequest) (*pb.AuthRoleListResponse, error) {
  428. tx := as.be.BatchTx()
  429. tx.Lock()
  430. roles := getAllRoles(tx)
  431. tx.Unlock()
  432. resp := &pb.AuthRoleListResponse{Roles: make([]string, len(roles))}
  433. for i := range roles {
  434. resp.Roles[i] = string(roles[i].Name)
  435. }
  436. return resp, nil
  437. }
  438. func (as *authStore) RoleRevokePermission(r *pb.AuthRoleRevokePermissionRequest) (*pb.AuthRoleRevokePermissionResponse, error) {
  439. tx := as.be.BatchTx()
  440. tx.Lock()
  441. defer tx.Unlock()
  442. role := getRole(tx, r.Role)
  443. if role == nil {
  444. return nil, ErrRoleNotFound
  445. }
  446. updatedRole := &authpb.Role{
  447. Name: role.Name,
  448. }
  449. for _, perm := range role.KeyPermission {
  450. if !bytes.Equal(perm.Key, []byte(r.Key)) || !bytes.Equal(perm.RangeEnd, []byte(r.RangeEnd)) {
  451. updatedRole.KeyPermission = append(updatedRole.KeyPermission, perm)
  452. }
  453. }
  454. if len(role.KeyPermission) == len(updatedRole.KeyPermission) {
  455. return nil, ErrPermissionNotGranted
  456. }
  457. putRole(tx, updatedRole)
  458. // TODO(mitake): currently single role update invalidates every cache
  459. // It should be optimized.
  460. as.clearCachedPerm()
  461. as.commitRevision(tx)
  462. plog.Noticef("revoked key %s from role %s", r.Key, r.Role)
  463. return &pb.AuthRoleRevokePermissionResponse{}, nil
  464. }
  465. func (as *authStore) RoleDelete(r *pb.AuthRoleDeleteRequest) (*pb.AuthRoleDeleteResponse, error) {
  466. if as.enabled && strings.Compare(r.Role, rootRole) == 0 {
  467. plog.Errorf("the role root must not be deleted")
  468. return nil, ErrInvalidAuthMgmt
  469. }
  470. tx := as.be.BatchTx()
  471. tx.Lock()
  472. defer tx.Unlock()
  473. role := getRole(tx, r.Role)
  474. if role == nil {
  475. return nil, ErrRoleNotFound
  476. }
  477. delRole(tx, r.Role)
  478. users := getAllUsers(tx)
  479. for _, user := range users {
  480. updatedUser := &authpb.User{
  481. Name: user.Name,
  482. Password: user.Password,
  483. }
  484. for _, role := range user.Roles {
  485. if strings.Compare(role, r.Role) != 0 {
  486. updatedUser.Roles = append(updatedUser.Roles, role)
  487. }
  488. }
  489. if len(updatedUser.Roles) == len(user.Roles) {
  490. continue
  491. }
  492. putUser(tx, updatedUser)
  493. as.invalidateCachedPerm(string(user.Name))
  494. }
  495. as.commitRevision(tx)
  496. plog.Noticef("deleted role %s", r.Role)
  497. return &pb.AuthRoleDeleteResponse{}, nil
  498. }
  499. func (as *authStore) RoleAdd(r *pb.AuthRoleAddRequest) (*pb.AuthRoleAddResponse, error) {
  500. tx := as.be.BatchTx()
  501. tx.Lock()
  502. defer tx.Unlock()
  503. role := getRole(tx, r.Name)
  504. if role != nil {
  505. return nil, ErrRoleAlreadyExist
  506. }
  507. newRole := &authpb.Role{
  508. Name: []byte(r.Name),
  509. }
  510. putRole(tx, newRole)
  511. as.commitRevision(tx)
  512. plog.Noticef("Role %s is created", r.Name)
  513. return &pb.AuthRoleAddResponse{}, nil
  514. }
  515. func (as *authStore) authInfoFromToken(ctx context.Context, token string) (*AuthInfo, bool) {
  516. return as.tokenProvider.info(ctx, token, as.Revision())
  517. }
  518. type permSlice []*authpb.Permission
  519. func (perms permSlice) Len() int {
  520. return len(perms)
  521. }
  522. func (perms permSlice) Less(i, j int) bool {
  523. return bytes.Compare(perms[i].Key, perms[j].Key) < 0
  524. }
  525. func (perms permSlice) Swap(i, j int) {
  526. perms[i], perms[j] = perms[j], perms[i]
  527. }
  528. func (as *authStore) RoleGrantPermission(r *pb.AuthRoleGrantPermissionRequest) (*pb.AuthRoleGrantPermissionResponse, error) {
  529. tx := as.be.BatchTx()
  530. tx.Lock()
  531. defer tx.Unlock()
  532. role := getRole(tx, r.Name)
  533. if role == nil {
  534. return nil, ErrRoleNotFound
  535. }
  536. idx := sort.Search(len(role.KeyPermission), func(i int) bool {
  537. return bytes.Compare(role.KeyPermission[i].Key, []byte(r.Perm.Key)) >= 0
  538. })
  539. if idx < len(role.KeyPermission) && bytes.Equal(role.KeyPermission[idx].Key, r.Perm.Key) && bytes.Equal(role.KeyPermission[idx].RangeEnd, r.Perm.RangeEnd) {
  540. // update existing permission
  541. role.KeyPermission[idx].PermType = r.Perm.PermType
  542. } else {
  543. // append new permission to the role
  544. newPerm := &authpb.Permission{
  545. Key: []byte(r.Perm.Key),
  546. RangeEnd: []byte(r.Perm.RangeEnd),
  547. PermType: r.Perm.PermType,
  548. }
  549. role.KeyPermission = append(role.KeyPermission, newPerm)
  550. sort.Sort(permSlice(role.KeyPermission))
  551. }
  552. putRole(tx, role)
  553. // TODO(mitake): currently single role update invalidates every cache
  554. // It should be optimized.
  555. as.clearCachedPerm()
  556. as.commitRevision(tx)
  557. 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)])
  558. return &pb.AuthRoleGrantPermissionResponse{}, nil
  559. }
  560. func (as *authStore) isOpPermitted(userName string, revision uint64, key, rangeEnd []byte, permTyp authpb.Permission_Type) error {
  561. // TODO(mitake): this function would be costly so we need a caching mechanism
  562. if !as.IsAuthEnabled() {
  563. return nil
  564. }
  565. // only gets rev == 0 when passed AuthInfo{}; no user given
  566. if revision == 0 {
  567. return ErrUserEmpty
  568. }
  569. if revision < as.Revision() {
  570. return ErrAuthOldRevision
  571. }
  572. tx := as.be.BatchTx()
  573. tx.Lock()
  574. defer tx.Unlock()
  575. user := getUser(tx, userName)
  576. if user == nil {
  577. plog.Errorf("invalid user name %s for permission checking", userName)
  578. return ErrPermissionDenied
  579. }
  580. // root role should have permission on all ranges
  581. if hasRootRole(user) {
  582. return nil
  583. }
  584. if as.isRangeOpPermitted(tx, userName, key, rangeEnd, permTyp) {
  585. return nil
  586. }
  587. return ErrPermissionDenied
  588. }
  589. func (as *authStore) IsPutPermitted(authInfo *AuthInfo, key []byte) error {
  590. return as.isOpPermitted(authInfo.Username, authInfo.Revision, key, nil, authpb.WRITE)
  591. }
  592. func (as *authStore) IsRangePermitted(authInfo *AuthInfo, key, rangeEnd []byte) error {
  593. return as.isOpPermitted(authInfo.Username, authInfo.Revision, key, rangeEnd, authpb.READ)
  594. }
  595. func (as *authStore) IsDeleteRangePermitted(authInfo *AuthInfo, key, rangeEnd []byte) error {
  596. return as.isOpPermitted(authInfo.Username, authInfo.Revision, key, rangeEnd, authpb.WRITE)
  597. }
  598. func (as *authStore) IsAdminPermitted(authInfo *AuthInfo) error {
  599. if !as.IsAuthEnabled() {
  600. return nil
  601. }
  602. if authInfo == nil {
  603. return ErrUserEmpty
  604. }
  605. tx := as.be.BatchTx()
  606. tx.Lock()
  607. u := getUser(tx, authInfo.Username)
  608. tx.Unlock()
  609. if u == nil {
  610. return ErrUserNotFound
  611. }
  612. if !hasRootRole(u) {
  613. return ErrPermissionDenied
  614. }
  615. return nil
  616. }
  617. func getUser(tx backend.BatchTx, username string) *authpb.User {
  618. _, vs := tx.UnsafeRange(authUsersBucketName, []byte(username), nil, 0)
  619. if len(vs) == 0 {
  620. return nil
  621. }
  622. user := &authpb.User{}
  623. err := user.Unmarshal(vs[0])
  624. if err != nil {
  625. plog.Panicf("failed to unmarshal user struct (name: %s): %s", username, err)
  626. }
  627. return user
  628. }
  629. func getAllUsers(tx backend.BatchTx) []*authpb.User {
  630. _, vs := tx.UnsafeRange(authUsersBucketName, []byte{0}, []byte{0xff}, -1)
  631. if len(vs) == 0 {
  632. return nil
  633. }
  634. users := make([]*authpb.User, len(vs))
  635. for i := range vs {
  636. user := &authpb.User{}
  637. err := user.Unmarshal(vs[i])
  638. if err != nil {
  639. plog.Panicf("failed to unmarshal user struct: %s", err)
  640. }
  641. users[i] = user
  642. }
  643. return users
  644. }
  645. func putUser(tx backend.BatchTx, user *authpb.User) {
  646. b, err := user.Marshal()
  647. if err != nil {
  648. plog.Panicf("failed to marshal user struct (name: %s): %s", user.Name, err)
  649. }
  650. tx.UnsafePut(authUsersBucketName, user.Name, b)
  651. }
  652. func delUser(tx backend.BatchTx, username string) {
  653. tx.UnsafeDelete(authUsersBucketName, []byte(username))
  654. }
  655. func getRole(tx backend.BatchTx, rolename string) *authpb.Role {
  656. _, vs := tx.UnsafeRange(authRolesBucketName, []byte(rolename), nil, 0)
  657. if len(vs) == 0 {
  658. return nil
  659. }
  660. role := &authpb.Role{}
  661. err := role.Unmarshal(vs[0])
  662. if err != nil {
  663. plog.Panicf("failed to unmarshal role struct (name: %s): %s", rolename, err)
  664. }
  665. return role
  666. }
  667. func getAllRoles(tx backend.BatchTx) []*authpb.Role {
  668. _, vs := tx.UnsafeRange(authRolesBucketName, []byte{0}, []byte{0xff}, -1)
  669. if len(vs) == 0 {
  670. return nil
  671. }
  672. roles := make([]*authpb.Role, len(vs))
  673. for i := range vs {
  674. role := &authpb.Role{}
  675. err := role.Unmarshal(vs[i])
  676. if err != nil {
  677. plog.Panicf("failed to unmarshal role struct: %s", err)
  678. }
  679. roles[i] = role
  680. }
  681. return roles
  682. }
  683. func putRole(tx backend.BatchTx, role *authpb.Role) {
  684. b, err := role.Marshal()
  685. if err != nil {
  686. plog.Panicf("failed to marshal role struct (name: %s): %s", role.Name, err)
  687. }
  688. tx.UnsafePut(authRolesBucketName, []byte(role.Name), b)
  689. }
  690. func delRole(tx backend.BatchTx, rolename string) {
  691. tx.UnsafeDelete(authRolesBucketName, []byte(rolename))
  692. }
  693. func (as *authStore) IsAuthEnabled() bool {
  694. as.enabledMu.RLock()
  695. defer as.enabledMu.RUnlock()
  696. return as.enabled
  697. }
  698. func NewAuthStore(be backend.Backend, tp TokenProvider) *authStore {
  699. tx := be.BatchTx()
  700. tx.Lock()
  701. tx.UnsafeCreateBucket(authBucketName)
  702. tx.UnsafeCreateBucket(authUsersBucketName)
  703. tx.UnsafeCreateBucket(authRolesBucketName)
  704. enabled := false
  705. _, vs := tx.UnsafeRange(authBucketName, enableFlagKey, nil, 0)
  706. if len(vs) == 1 {
  707. if bytes.Equal(vs[0], authEnabled) {
  708. enabled = true
  709. }
  710. }
  711. as := &authStore{
  712. be: be,
  713. revision: getRevision(tx),
  714. enabled: enabled,
  715. rangePermCache: make(map[string]*unifiedRangePermissions),
  716. tokenProvider: tp,
  717. }
  718. if enabled {
  719. as.tokenProvider.enable()
  720. }
  721. if as.Revision() == 0 {
  722. as.commitRevision(tx)
  723. }
  724. tx.Unlock()
  725. be.ForceCommit()
  726. return as
  727. }
  728. func hasRootRole(u *authpb.User) bool {
  729. // u.Roles is sorted in UserGrantRole(), so we can use binary search.
  730. idx := sort.SearchStrings(u.Roles, rootRole)
  731. return idx != len(u.Roles) && u.Roles[idx] == rootRole
  732. }
  733. func (as *authStore) commitRevision(tx backend.BatchTx) {
  734. atomic.AddUint64(&as.revision, 1)
  735. revBytes := make([]byte, revBytesLen)
  736. binary.BigEndian.PutUint64(revBytes, as.Revision())
  737. tx.UnsafePut(authBucketName, revisionKey, revBytes)
  738. }
  739. func getRevision(tx backend.BatchTx) uint64 {
  740. _, vs := tx.UnsafeRange(authBucketName, []byte(revisionKey), nil, 0)
  741. if len(vs) != 1 {
  742. // this can happen in the initialization phase
  743. return 0
  744. }
  745. return binary.BigEndian.Uint64(vs[0])
  746. }
  747. func (as *authStore) setRevision(rev uint64) {
  748. atomic.StoreUint64(&as.revision, rev)
  749. }
  750. func (as *authStore) Revision() uint64 {
  751. return atomic.LoadUint64(&as.revision)
  752. }
  753. func (as *authStore) AuthInfoFromTLS(ctx context.Context) *AuthInfo {
  754. peer, ok := peer.FromContext(ctx)
  755. if !ok || peer == nil || peer.AuthInfo == nil {
  756. return nil
  757. }
  758. tlsInfo := peer.AuthInfo.(credentials.TLSInfo)
  759. for _, chains := range tlsInfo.State.VerifiedChains {
  760. for _, chain := range chains {
  761. cn := chain.Subject.CommonName
  762. plog.Debugf("found common name %s", cn)
  763. return &AuthInfo{
  764. Username: cn,
  765. Revision: as.Revision(),
  766. }
  767. }
  768. }
  769. return nil
  770. }
  771. func (as *authStore) AuthInfoFromCtx(ctx context.Context) (*AuthInfo, error) {
  772. md, ok := metadata.FromIncomingContext(ctx)
  773. if !ok {
  774. return nil, nil
  775. }
  776. //TODO(mitake|hexfusion) review unifying key names
  777. ts, ok := md[rpctypes.TokenFieldNameGRPC]
  778. if !ok {
  779. ts, ok = md[rpctypes.TokenFieldNameSwagger]
  780. }
  781. if !ok {
  782. return nil, nil
  783. }
  784. token := ts[0]
  785. authInfo, uok := as.authInfoFromToken(ctx, token)
  786. if !uok {
  787. plog.Warningf("invalid auth token: %s", token)
  788. return nil, ErrInvalidAuthToken
  789. }
  790. return authInfo, nil
  791. }
  792. func (as *authStore) GenTokenPrefix() (string, error) {
  793. return as.tokenProvider.genTokenPrefix()
  794. }
  795. func decomposeOpts(optstr string) (string, map[string]string, error) {
  796. opts := strings.Split(optstr, ",")
  797. tokenType := opts[0]
  798. typeSpecificOpts := make(map[string]string)
  799. for i := 1; i < len(opts); i++ {
  800. pair := strings.Split(opts[i], "=")
  801. if len(pair) != 2 {
  802. plog.Errorf("invalid token specific option: %s", optstr)
  803. return "", nil, ErrInvalidAuthOpts
  804. }
  805. if _, ok := typeSpecificOpts[pair[0]]; ok {
  806. plog.Errorf("invalid token specific option, duplicated parameters (%s): %s", pair[0], optstr)
  807. return "", nil, ErrInvalidAuthOpts
  808. }
  809. typeSpecificOpts[pair[0]] = pair[1]
  810. }
  811. return tokenType, typeSpecificOpts, nil
  812. }
  813. func NewTokenProvider(tokenOpts string, indexWaiter func(uint64) <-chan struct{}) (TokenProvider, error) {
  814. tokenType, typeSpecificOpts, err := decomposeOpts(tokenOpts)
  815. if err != nil {
  816. return nil, ErrInvalidAuthOpts
  817. }
  818. switch tokenType {
  819. case "simple":
  820. plog.Warningf("simple token is not cryptographically signed")
  821. return newTokenProviderSimple(indexWaiter), nil
  822. case "jwt":
  823. return newTokenProviderJWT(typeSpecificOpts)
  824. case "":
  825. return newTokenProviderNop()
  826. default:
  827. plog.Errorf("unknown token type: %s", tokenType)
  828. return nil, ErrInvalidAuthOpts
  829. }
  830. }
  831. func (as *authStore) WithRoot(ctx context.Context) context.Context {
  832. if !as.IsAuthEnabled() {
  833. return ctx
  834. }
  835. var ctxForAssign context.Context
  836. if ts := as.tokenProvider.(*tokenSimple); ts != nil {
  837. ctx1 := context.WithValue(ctx, AuthenticateParamIndex{}, uint64(0))
  838. prefix, err := ts.genTokenPrefix()
  839. if err != nil {
  840. plog.Errorf("failed to generate prefix of internally used token")
  841. return ctx
  842. }
  843. ctxForAssign = context.WithValue(ctx1, AuthenticateParamSimpleTokenPrefix{}, prefix)
  844. } else {
  845. ctxForAssign = ctx
  846. }
  847. token, err := as.tokenProvider.assign(ctxForAssign, "root", as.Revision())
  848. if err != nil {
  849. // this must not happen
  850. plog.Errorf("failed to assign token for lease revoking: %s", err)
  851. return ctx
  852. }
  853. mdMap := map[string]string{
  854. rpctypes.TokenFieldNameGRPC: token,
  855. }
  856. tokenMD := metadata.New(mdMap)
  857. // use "mdIncomingKey{}" since it's called from local etcdserver
  858. return metadata.NewIncomingContext(ctx, tokenMD)
  859. }
  860. func (as *authStore) HasRole(user, role string) bool {
  861. tx := as.be.BatchTx()
  862. tx.Lock()
  863. u := getUser(tx, user)
  864. tx.Unlock()
  865. if u == nil {
  866. plog.Warningf("tried to check user %s has role %s, but user %s doesn't exist", user, role, user)
  867. return false
  868. }
  869. for _, r := range u.Roles {
  870. if role == r {
  871. return true
  872. }
  873. }
  874. return false
  875. }