store.go 28 KB

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