store.go 28 KB

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