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