store.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344
  1. // Copyright 2016 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package auth
  15. import (
  16. "bytes"
  17. "context"
  18. "encoding/binary"
  19. "errors"
  20. "sort"
  21. "strings"
  22. "sync"
  23. "sync/atomic"
  24. "github.com/coreos/etcd/auth/authpb"
  25. "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
  26. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  27. "github.com/coreos/etcd/mvcc/backend"
  28. "github.com/coreos/pkg/capnslog"
  29. "go.uber.org/zap"
  30. "golang.org/x/crypto/bcrypt"
  31. "google.golang.org/grpc/credentials"
  32. "google.golang.org/grpc/metadata"
  33. "google.golang.org/grpc/peer"
  34. )
  35. var (
  36. enableFlagKey = []byte("authEnabled")
  37. authEnabled = []byte{1}
  38. authDisabled = []byte{0}
  39. revisionKey = []byte("authRevision")
  40. authBucketName = []byte("auth")
  41. authUsersBucketName = []byte("authUsers")
  42. authRolesBucketName = []byte("authRoles")
  43. plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "auth")
  44. ErrRootUserNotExist = errors.New("auth: root user does not exist")
  45. ErrRootRoleNotExist = errors.New("auth: root user does not have root role")
  46. ErrUserAlreadyExist = errors.New("auth: user already exists")
  47. ErrUserEmpty = errors.New("auth: user name is empty")
  48. ErrUserNotFound = errors.New("auth: user not found")
  49. ErrRoleAlreadyExist = errors.New("auth: role already exists")
  50. ErrRoleNotFound = errors.New("auth: role not found")
  51. ErrAuthFailed = errors.New("auth: authentication failed, invalid user ID or password")
  52. ErrPermissionDenied = errors.New("auth: permission denied")
  53. ErrRoleNotGranted = errors.New("auth: role is not granted to the user")
  54. ErrPermissionNotGranted = errors.New("auth: permission is not granted to the role")
  55. ErrAuthNotEnabled = errors.New("auth: authentication is not enabled")
  56. ErrAuthOldRevision = errors.New("auth: revision in header is old")
  57. ErrInvalidAuthToken = errors.New("auth: invalid auth token")
  58. ErrInvalidAuthOpts = errors.New("auth: invalid auth options")
  59. ErrInvalidAuthMgmt = errors.New("auth: invalid auth management")
  60. // BcryptCost is the algorithm cost / strength for hashing auth passwords
  61. BcryptCost = bcrypt.DefaultCost
  62. )
  63. const (
  64. rootUser = "root"
  65. rootRole = "root"
  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. // AuthStore defines auth storage interface.
  77. type AuthStore interface {
  78. // AuthEnable turns on the authentication feature
  79. AuthEnable() error
  80. // AuthDisable turns off the authentication feature
  81. AuthDisable()
  82. // IsAuthEnabled returns true if the authentication feature is enabled.
  83. IsAuthEnabled() bool
  84. // Authenticate does authentication based on given user name and password
  85. Authenticate(ctx context.Context, username, password string) (*pb.AuthenticateResponse, error)
  86. // Recover recovers the state of auth store from the given backend
  87. Recover(b backend.Backend)
  88. // UserAdd adds a new user
  89. UserAdd(r *pb.AuthUserAddRequest) (*pb.AuthUserAddResponse, error)
  90. // UserDelete deletes a user
  91. UserDelete(r *pb.AuthUserDeleteRequest) (*pb.AuthUserDeleteResponse, error)
  92. // UserChangePassword changes a password of a user
  93. UserChangePassword(r *pb.AuthUserChangePasswordRequest) (*pb.AuthUserChangePasswordResponse, error)
  94. // UserGrantRole grants a role to the user
  95. UserGrantRole(r *pb.AuthUserGrantRoleRequest) (*pb.AuthUserGrantRoleResponse, error)
  96. // UserGet gets the detailed information of a users
  97. UserGet(r *pb.AuthUserGetRequest) (*pb.AuthUserGetResponse, error)
  98. // UserRevokeRole revokes a role of a user
  99. UserRevokeRole(r *pb.AuthUserRevokeRoleRequest) (*pb.AuthUserRevokeRoleResponse, error)
  100. // RoleAdd adds a new role
  101. RoleAdd(r *pb.AuthRoleAddRequest) (*pb.AuthRoleAddResponse, error)
  102. // RoleGrantPermission grants a permission to a role
  103. RoleGrantPermission(r *pb.AuthRoleGrantPermissionRequest) (*pb.AuthRoleGrantPermissionResponse, error)
  104. // RoleGet gets the detailed information of a role
  105. RoleGet(r *pb.AuthRoleGetRequest) (*pb.AuthRoleGetResponse, error)
  106. // RoleRevokePermission gets the detailed information of a role
  107. RoleRevokePermission(r *pb.AuthRoleRevokePermissionRequest) (*pb.AuthRoleRevokePermissionResponse, error)
  108. // RoleDelete gets the detailed information of a role
  109. RoleDelete(r *pb.AuthRoleDeleteRequest) (*pb.AuthRoleDeleteResponse, error)
  110. // UserList gets a list of all users
  111. UserList(r *pb.AuthUserListRequest) (*pb.AuthUserListResponse, error)
  112. // RoleList gets a list of all roles
  113. RoleList(r *pb.AuthRoleListRequest) (*pb.AuthRoleListResponse, error)
  114. // IsPutPermitted checks put permission of the user
  115. IsPutPermitted(authInfo *AuthInfo, key []byte) error
  116. // IsRangePermitted checks range permission of the user
  117. IsRangePermitted(authInfo *AuthInfo, key, rangeEnd []byte) error
  118. // IsDeleteRangePermitted checks delete-range permission of the user
  119. IsDeleteRangePermitted(authInfo *AuthInfo, key, rangeEnd []byte) error
  120. // IsAdminPermitted checks admin permission of the user
  121. IsAdminPermitted(authInfo *AuthInfo) error
  122. // GenTokenPrefix produces a random string in a case of simple token
  123. // in a case of JWT, it produces an empty string
  124. GenTokenPrefix() (string, error)
  125. // Revision gets current revision of authStore
  126. Revision() uint64
  127. // CheckPassword checks a given pair of username and password is correct
  128. CheckPassword(username, password string) (uint64, error)
  129. // Close does cleanup of AuthStore
  130. Close() error
  131. // AuthInfoFromCtx gets AuthInfo from gRPC's context
  132. AuthInfoFromCtx(ctx context.Context) (*AuthInfo, error)
  133. // AuthInfoFromTLS gets AuthInfo from TLS info of gRPC's context
  134. AuthInfoFromTLS(ctx context.Context) *AuthInfo
  135. // WithRoot generates and installs a token that can be used as a root credential
  136. WithRoot(ctx context.Context) context.Context
  137. // HasRole checks that user has role
  138. HasRole(user, role string) bool
  139. }
  140. type TokenProvider interface {
  141. info(ctx context.Context, token string, revision uint64) (*AuthInfo, bool)
  142. assign(ctx context.Context, username string, revision uint64) (string, error)
  143. enable()
  144. disable()
  145. invalidateUser(string)
  146. genTokenPrefix() (string, error)
  147. }
  148. type authStore struct {
  149. // atomic operations; need 64-bit align, or 32-bit tests will crash
  150. revision uint64
  151. lg *zap.Logger
  152. be backend.Backend
  153. enabled bool
  154. enabledMu sync.RWMutex
  155. rangePermCache map[string]*unifiedRangePermissions // username -> unifiedRangePermissions
  156. tokenProvider TokenProvider
  157. }
  158. func (as *authStore) AuthEnable() error {
  159. as.enabledMu.Lock()
  160. defer as.enabledMu.Unlock()
  161. if as.enabled {
  162. if as.lg != nil {
  163. as.lg.Info("authentication is already enabled; ignored auth enable request")
  164. } else {
  165. plog.Noticef("Authentication already enabled")
  166. }
  167. return nil
  168. }
  169. b := as.be
  170. tx := b.BatchTx()
  171. tx.Lock()
  172. defer func() {
  173. tx.Unlock()
  174. b.ForceCommit()
  175. }()
  176. u := getUser(as.lg, tx, rootUser)
  177. if u == nil {
  178. return ErrRootUserNotExist
  179. }
  180. if !hasRootRole(u) {
  181. return ErrRootRoleNotExist
  182. }
  183. tx.UnsafePut(authBucketName, enableFlagKey, authEnabled)
  184. as.enabled = true
  185. as.tokenProvider.enable()
  186. as.rangePermCache = make(map[string]*unifiedRangePermissions)
  187. as.setRevision(getRevision(tx))
  188. if as.lg != nil {
  189. as.lg.Info("enabled authentication")
  190. } else {
  191. plog.Noticef("Authentication enabled")
  192. }
  193. return nil
  194. }
  195. func (as *authStore) AuthDisable() {
  196. as.enabledMu.Lock()
  197. defer as.enabledMu.Unlock()
  198. if !as.enabled {
  199. return
  200. }
  201. b := as.be
  202. tx := b.BatchTx()
  203. tx.Lock()
  204. tx.UnsafePut(authBucketName, enableFlagKey, authDisabled)
  205. as.commitRevision(tx)
  206. tx.Unlock()
  207. b.ForceCommit()
  208. as.enabled = false
  209. as.tokenProvider.disable()
  210. if as.lg != nil {
  211. as.lg.Info("disabled authentication")
  212. } else {
  213. plog.Noticef("Authentication disabled")
  214. }
  215. }
  216. func (as *authStore) Close() error {
  217. as.enabledMu.Lock()
  218. defer as.enabledMu.Unlock()
  219. if !as.enabled {
  220. return nil
  221. }
  222. as.tokenProvider.disable()
  223. return nil
  224. }
  225. func (as *authStore) Authenticate(ctx context.Context, username, password string) (*pb.AuthenticateResponse, error) {
  226. if !as.IsAuthEnabled() {
  227. return nil, ErrAuthNotEnabled
  228. }
  229. tx := as.be.BatchTx()
  230. tx.Lock()
  231. defer tx.Unlock()
  232. user := getUser(as.lg, tx, username)
  233. if user == nil {
  234. return nil, ErrAuthFailed
  235. }
  236. // Password checking is already performed in the API layer, so we don't need to check for now.
  237. // Staleness of password can be detected with OCC in the API layer, too.
  238. token, err := as.tokenProvider.assign(ctx, username, as.Revision())
  239. if err != nil {
  240. return nil, err
  241. }
  242. if as.lg != nil {
  243. as.lg.Debug(
  244. "authenticated a user",
  245. zap.String("user-name", username),
  246. zap.String("token", token),
  247. )
  248. } else {
  249. plog.Debugf("authorized %s, token is %s", username, token)
  250. }
  251. return &pb.AuthenticateResponse{Token: token}, nil
  252. }
  253. func (as *authStore) CheckPassword(username, password string) (uint64, error) {
  254. if !as.IsAuthEnabled() {
  255. return 0, ErrAuthNotEnabled
  256. }
  257. tx := as.be.BatchTx()
  258. tx.Lock()
  259. defer tx.Unlock()
  260. user := getUser(as.lg, tx, username)
  261. if user == nil {
  262. return 0, ErrAuthFailed
  263. }
  264. if bcrypt.CompareHashAndPassword(user.Password, []byte(password)) != nil {
  265. if as.lg != nil {
  266. as.lg.Info("invalid password", zap.String("user-name", username))
  267. } else {
  268. plog.Noticef("authentication failed, invalid password for user %s", username)
  269. }
  270. return 0, ErrAuthFailed
  271. }
  272. return getRevision(tx), nil
  273. }
  274. func (as *authStore) Recover(be backend.Backend) {
  275. enabled := false
  276. as.be = be
  277. tx := be.BatchTx()
  278. tx.Lock()
  279. _, vs := tx.UnsafeRange(authBucketName, enableFlagKey, nil, 0)
  280. if len(vs) == 1 {
  281. if bytes.Equal(vs[0], authEnabled) {
  282. enabled = true
  283. }
  284. }
  285. as.setRevision(getRevision(tx))
  286. tx.Unlock()
  287. as.enabledMu.Lock()
  288. as.enabled = enabled
  289. as.enabledMu.Unlock()
  290. }
  291. func (as *authStore) UserAdd(r *pb.AuthUserAddRequest) (*pb.AuthUserAddResponse, error) {
  292. if len(r.Name) == 0 {
  293. return nil, ErrUserEmpty
  294. }
  295. hashed, err := bcrypt.GenerateFromPassword([]byte(r.Password), BcryptCost)
  296. if err != nil {
  297. if as.lg != nil {
  298. as.lg.Warn(
  299. "failed to bcrypt hash password",
  300. zap.String("user-name", r.Name),
  301. zap.Error(err),
  302. )
  303. } else {
  304. plog.Errorf("failed to hash password: %s", err)
  305. }
  306. return nil, err
  307. }
  308. tx := as.be.BatchTx()
  309. tx.Lock()
  310. defer tx.Unlock()
  311. user := getUser(as.lg, tx, r.Name)
  312. if user != nil {
  313. return nil, ErrUserAlreadyExist
  314. }
  315. newUser := &authpb.User{
  316. Name: []byte(r.Name),
  317. Password: hashed,
  318. }
  319. putUser(as.lg, tx, newUser)
  320. as.commitRevision(tx)
  321. if as.lg != nil {
  322. as.lg.Info("added a user", zap.String("user-name", r.Name))
  323. } else {
  324. plog.Noticef("added a new user: %s", r.Name)
  325. }
  326. return &pb.AuthUserAddResponse{}, nil
  327. }
  328. func (as *authStore) UserDelete(r *pb.AuthUserDeleteRequest) (*pb.AuthUserDeleteResponse, error) {
  329. if as.enabled && r.Name == rootUser {
  330. if as.lg != nil {
  331. as.lg.Warn("cannot delete 'root' user", zap.String("user-name", r.Name))
  332. } else {
  333. plog.Errorf("the user root must not be deleted")
  334. }
  335. return nil, ErrInvalidAuthMgmt
  336. }
  337. tx := as.be.BatchTx()
  338. tx.Lock()
  339. defer tx.Unlock()
  340. user := getUser(as.lg, tx, r.Name)
  341. if user == nil {
  342. return nil, ErrUserNotFound
  343. }
  344. delUser(tx, r.Name)
  345. as.commitRevision(tx)
  346. as.invalidateCachedPerm(r.Name)
  347. as.tokenProvider.invalidateUser(r.Name)
  348. if as.lg != nil {
  349. as.lg.Info(
  350. "deleted a user",
  351. zap.String("user-name", r.Name),
  352. zap.Strings("user-roles", user.Roles),
  353. )
  354. } else {
  355. plog.Noticef("deleted a user: %s", r.Name)
  356. }
  357. return &pb.AuthUserDeleteResponse{}, nil
  358. }
  359. func (as *authStore) UserChangePassword(r *pb.AuthUserChangePasswordRequest) (*pb.AuthUserChangePasswordResponse, error) {
  360. // TODO(mitake): measure the cost of bcrypt.GenerateFromPassword()
  361. // If the cost is too high, we should move the encryption to outside of the raft
  362. hashed, err := bcrypt.GenerateFromPassword([]byte(r.Password), BcryptCost)
  363. if err != nil {
  364. if as.lg != nil {
  365. as.lg.Warn(
  366. "failed to bcrypt hash password",
  367. zap.String("user-name", r.Name),
  368. zap.Error(err),
  369. )
  370. } else {
  371. plog.Errorf("failed to hash password: %s", err)
  372. }
  373. return nil, err
  374. }
  375. tx := as.be.BatchTx()
  376. tx.Lock()
  377. defer tx.Unlock()
  378. user := getUser(as.lg, tx, r.Name)
  379. if user == nil {
  380. return nil, ErrUserNotFound
  381. }
  382. updatedUser := &authpb.User{
  383. Name: []byte(r.Name),
  384. Roles: user.Roles,
  385. Password: hashed,
  386. }
  387. putUser(as.lg, tx, updatedUser)
  388. as.commitRevision(tx)
  389. as.invalidateCachedPerm(r.Name)
  390. as.tokenProvider.invalidateUser(r.Name)
  391. if as.lg != nil {
  392. as.lg.Info(
  393. "changed a password of a user",
  394. zap.String("user-name", r.Name),
  395. zap.Strings("user-roles", user.Roles),
  396. )
  397. } else {
  398. plog.Noticef("changed a password of a user: %s", r.Name)
  399. }
  400. return &pb.AuthUserChangePasswordResponse{}, nil
  401. }
  402. func (as *authStore) UserGrantRole(r *pb.AuthUserGrantRoleRequest) (*pb.AuthUserGrantRoleResponse, error) {
  403. tx := as.be.BatchTx()
  404. tx.Lock()
  405. defer tx.Unlock()
  406. user := getUser(as.lg, tx, r.User)
  407. if user == nil {
  408. return nil, ErrUserNotFound
  409. }
  410. if r.Role != rootRole {
  411. role := getRole(tx, r.Role)
  412. if role == nil {
  413. return nil, ErrRoleNotFound
  414. }
  415. }
  416. idx := sort.SearchStrings(user.Roles, r.Role)
  417. if idx < len(user.Roles) && user.Roles[idx] == r.Role {
  418. if as.lg != nil {
  419. as.lg.Warn(
  420. "ignored grant role request to a user",
  421. zap.String("user-name", r.User),
  422. zap.Strings("user-roles", user.Roles),
  423. zap.String("duplicate-role-name", r.Role),
  424. )
  425. } else {
  426. plog.Warningf("user %s is already granted role %s", r.User, r.Role)
  427. }
  428. return &pb.AuthUserGrantRoleResponse{}, nil
  429. }
  430. user.Roles = append(user.Roles, r.Role)
  431. sort.Strings(user.Roles)
  432. putUser(as.lg, tx, user)
  433. as.invalidateCachedPerm(r.User)
  434. as.commitRevision(tx)
  435. if as.lg != nil {
  436. as.lg.Info(
  437. "granted a role to a user",
  438. zap.String("user-name", r.User),
  439. zap.Strings("user-roles", user.Roles),
  440. zap.String("added-role-name", r.Role),
  441. )
  442. } else {
  443. plog.Noticef("granted role %s to user %s", r.Role, r.User)
  444. }
  445. return &pb.AuthUserGrantRoleResponse{}, nil
  446. }
  447. func (as *authStore) UserGet(r *pb.AuthUserGetRequest) (*pb.AuthUserGetResponse, error) {
  448. tx := as.be.BatchTx()
  449. tx.Lock()
  450. user := getUser(as.lg, tx, r.Name)
  451. tx.Unlock()
  452. if user == nil {
  453. return nil, ErrUserNotFound
  454. }
  455. var resp pb.AuthUserGetResponse
  456. resp.Roles = append(resp.Roles, user.Roles...)
  457. return &resp, nil
  458. }
  459. func (as *authStore) UserList(r *pb.AuthUserListRequest) (*pb.AuthUserListResponse, error) {
  460. tx := as.be.BatchTx()
  461. tx.Lock()
  462. users := getAllUsers(as.lg, tx)
  463. tx.Unlock()
  464. resp := &pb.AuthUserListResponse{Users: make([]string, len(users))}
  465. for i := range users {
  466. resp.Users[i] = string(users[i].Name)
  467. }
  468. return resp, nil
  469. }
  470. func (as *authStore) UserRevokeRole(r *pb.AuthUserRevokeRoleRequest) (*pb.AuthUserRevokeRoleResponse, error) {
  471. if as.enabled && r.Name == rootUser && r.Role == rootRole {
  472. if as.lg != nil {
  473. as.lg.Warn(
  474. "'root' user cannot revoke 'root' role",
  475. zap.String("user-name", r.Name),
  476. zap.String("role-name", r.Role),
  477. )
  478. } else {
  479. plog.Errorf("the role root must not be revoked from the user root")
  480. }
  481. return nil, ErrInvalidAuthMgmt
  482. }
  483. tx := as.be.BatchTx()
  484. tx.Lock()
  485. defer tx.Unlock()
  486. user := getUser(as.lg, tx, r.Name)
  487. if user == nil {
  488. return nil, ErrUserNotFound
  489. }
  490. updatedUser := &authpb.User{
  491. Name: user.Name,
  492. Password: user.Password,
  493. }
  494. for _, role := range user.Roles {
  495. if role != r.Role {
  496. updatedUser.Roles = append(updatedUser.Roles, role)
  497. }
  498. }
  499. if len(updatedUser.Roles) == len(user.Roles) {
  500. return nil, ErrRoleNotGranted
  501. }
  502. putUser(as.lg, tx, updatedUser)
  503. as.invalidateCachedPerm(r.Name)
  504. as.commitRevision(tx)
  505. if as.lg != nil {
  506. as.lg.Info(
  507. "revoked a role from a user",
  508. zap.String("user-name", r.Name),
  509. zap.Strings("old-user-roles", user.Roles),
  510. zap.Strings("new-user-roles", updatedUser.Roles),
  511. zap.String("revoked-role-name", r.Role),
  512. )
  513. } else {
  514. plog.Noticef("revoked role %s from user %s", r.Role, r.Name)
  515. }
  516. return &pb.AuthUserRevokeRoleResponse{}, nil
  517. }
  518. func (as *authStore) RoleGet(r *pb.AuthRoleGetRequest) (*pb.AuthRoleGetResponse, error) {
  519. tx := as.be.BatchTx()
  520. tx.Lock()
  521. defer tx.Unlock()
  522. var resp pb.AuthRoleGetResponse
  523. role := getRole(tx, r.Role)
  524. if role == nil {
  525. return nil, ErrRoleNotFound
  526. }
  527. resp.Perm = append(resp.Perm, role.KeyPermission...)
  528. return &resp, nil
  529. }
  530. func (as *authStore) RoleList(r *pb.AuthRoleListRequest) (*pb.AuthRoleListResponse, error) {
  531. tx := as.be.BatchTx()
  532. tx.Lock()
  533. roles := getAllRoles(as.lg, tx)
  534. tx.Unlock()
  535. resp := &pb.AuthRoleListResponse{Roles: make([]string, len(roles))}
  536. for i := range roles {
  537. resp.Roles[i] = string(roles[i].Name)
  538. }
  539. return resp, nil
  540. }
  541. func (as *authStore) RoleRevokePermission(r *pb.AuthRoleRevokePermissionRequest) (*pb.AuthRoleRevokePermissionResponse, error) {
  542. tx := as.be.BatchTx()
  543. tx.Lock()
  544. defer tx.Unlock()
  545. role := getRole(tx, r.Role)
  546. if role == nil {
  547. return nil, ErrRoleNotFound
  548. }
  549. updatedRole := &authpb.Role{
  550. Name: role.Name,
  551. }
  552. for _, perm := range role.KeyPermission {
  553. if !bytes.Equal(perm.Key, r.Key) || !bytes.Equal(perm.RangeEnd, r.RangeEnd) {
  554. updatedRole.KeyPermission = append(updatedRole.KeyPermission, perm)
  555. }
  556. }
  557. if len(role.KeyPermission) == len(updatedRole.KeyPermission) {
  558. return nil, ErrPermissionNotGranted
  559. }
  560. putRole(as.lg, tx, updatedRole)
  561. // TODO(mitake): currently single role update invalidates every cache
  562. // It should be optimized.
  563. as.clearCachedPerm()
  564. as.commitRevision(tx)
  565. if as.lg != nil {
  566. as.lg.Info(
  567. "revoked a permission on range",
  568. zap.String("role-name", r.Role),
  569. zap.String("key", string(r.Key)),
  570. zap.String("range-end", string(r.RangeEnd)),
  571. )
  572. } else {
  573. plog.Noticef("revoked key %s from role %s", r.Key, r.Role)
  574. }
  575. return &pb.AuthRoleRevokePermissionResponse{}, nil
  576. }
  577. func (as *authStore) RoleDelete(r *pb.AuthRoleDeleteRequest) (*pb.AuthRoleDeleteResponse, error) {
  578. if as.enabled && r.Role == rootRole {
  579. if as.lg != nil {
  580. as.lg.Warn("cannot delete 'root' role", zap.String("role-name", r.Role))
  581. } else {
  582. plog.Errorf("the role root must not be deleted")
  583. }
  584. return nil, ErrInvalidAuthMgmt
  585. }
  586. tx := as.be.BatchTx()
  587. tx.Lock()
  588. defer tx.Unlock()
  589. role := getRole(tx, r.Role)
  590. if role == nil {
  591. return nil, ErrRoleNotFound
  592. }
  593. delRole(tx, r.Role)
  594. users := getAllUsers(as.lg, tx)
  595. for _, user := range users {
  596. updatedUser := &authpb.User{
  597. Name: user.Name,
  598. Password: user.Password,
  599. }
  600. for _, role := range user.Roles {
  601. if role != r.Role {
  602. updatedUser.Roles = append(updatedUser.Roles, role)
  603. }
  604. }
  605. if len(updatedUser.Roles) == len(user.Roles) {
  606. continue
  607. }
  608. putUser(as.lg, tx, updatedUser)
  609. as.invalidateCachedPerm(string(user.Name))
  610. }
  611. as.commitRevision(tx)
  612. if as.lg != nil {
  613. as.lg.Info("deleted a role", zap.String("role-name", r.Role))
  614. } else {
  615. plog.Noticef("deleted role %s", r.Role)
  616. }
  617. return &pb.AuthRoleDeleteResponse{}, nil
  618. }
  619. func (as *authStore) RoleAdd(r *pb.AuthRoleAddRequest) (*pb.AuthRoleAddResponse, error) {
  620. tx := as.be.BatchTx()
  621. tx.Lock()
  622. defer tx.Unlock()
  623. role := getRole(tx, r.Name)
  624. if role != nil {
  625. return nil, ErrRoleAlreadyExist
  626. }
  627. newRole := &authpb.Role{
  628. Name: []byte(r.Name),
  629. }
  630. putRole(as.lg, tx, newRole)
  631. as.commitRevision(tx)
  632. if as.lg != nil {
  633. as.lg.Info("created a role", zap.String("role-name", r.Name))
  634. } else {
  635. plog.Noticef("Role %s is created", r.Name)
  636. }
  637. return &pb.AuthRoleAddResponse{}, nil
  638. }
  639. func (as *authStore) authInfoFromToken(ctx context.Context, token string) (*AuthInfo, bool) {
  640. return as.tokenProvider.info(ctx, token, as.Revision())
  641. }
  642. type permSlice []*authpb.Permission
  643. func (perms permSlice) Len() int {
  644. return len(perms)
  645. }
  646. func (perms permSlice) Less(i, j int) bool {
  647. return bytes.Compare(perms[i].Key, perms[j].Key) < 0
  648. }
  649. func (perms permSlice) Swap(i, j int) {
  650. perms[i], perms[j] = perms[j], perms[i]
  651. }
  652. func (as *authStore) RoleGrantPermission(r *pb.AuthRoleGrantPermissionRequest) (*pb.AuthRoleGrantPermissionResponse, error) {
  653. tx := as.be.BatchTx()
  654. tx.Lock()
  655. defer tx.Unlock()
  656. role := getRole(tx, r.Name)
  657. if role == nil {
  658. return nil, ErrRoleNotFound
  659. }
  660. idx := sort.Search(len(role.KeyPermission), func(i int) bool {
  661. return bytes.Compare(role.KeyPermission[i].Key, r.Perm.Key) >= 0
  662. })
  663. if idx < len(role.KeyPermission) && bytes.Equal(role.KeyPermission[idx].Key, r.Perm.Key) && bytes.Equal(role.KeyPermission[idx].RangeEnd, r.Perm.RangeEnd) {
  664. // update existing permission
  665. role.KeyPermission[idx].PermType = r.Perm.PermType
  666. } else {
  667. // append new permission to the role
  668. newPerm := &authpb.Permission{
  669. Key: r.Perm.Key,
  670. RangeEnd: r.Perm.RangeEnd,
  671. PermType: r.Perm.PermType,
  672. }
  673. role.KeyPermission = append(role.KeyPermission, newPerm)
  674. sort.Sort(permSlice(role.KeyPermission))
  675. }
  676. putRole(as.lg, tx, role)
  677. // TODO(mitake): currently single role update invalidates every cache
  678. // It should be optimized.
  679. as.clearCachedPerm()
  680. as.commitRevision(tx)
  681. if as.lg != nil {
  682. as.lg.Info(
  683. "granted/updated a permission to a user",
  684. zap.String("user-name", r.Name),
  685. zap.String("permission-name", authpb.Permission_Type_name[int32(r.Perm.PermType)]),
  686. )
  687. } else {
  688. 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)])
  689. }
  690. return &pb.AuthRoleGrantPermissionResponse{}, nil
  691. }
  692. func (as *authStore) isOpPermitted(userName string, revision uint64, key, rangeEnd []byte, permTyp authpb.Permission_Type) error {
  693. // TODO(mitake): this function would be costly so we need a caching mechanism
  694. if !as.IsAuthEnabled() {
  695. return nil
  696. }
  697. // only gets rev == 0 when passed AuthInfo{}; no user given
  698. if revision == 0 {
  699. return ErrUserEmpty
  700. }
  701. if revision < as.Revision() {
  702. return ErrAuthOldRevision
  703. }
  704. tx := as.be.BatchTx()
  705. tx.Lock()
  706. defer tx.Unlock()
  707. user := getUser(as.lg, tx, userName)
  708. if user == nil {
  709. if as.lg != nil {
  710. as.lg.Warn("cannot find a user for permission check", zap.String("user-name", userName))
  711. } else {
  712. plog.Errorf("invalid user name %s for permission checking", userName)
  713. }
  714. return ErrPermissionDenied
  715. }
  716. // root role should have permission on all ranges
  717. if hasRootRole(user) {
  718. return nil
  719. }
  720. if as.isRangeOpPermitted(tx, userName, key, rangeEnd, permTyp) {
  721. return nil
  722. }
  723. return ErrPermissionDenied
  724. }
  725. func (as *authStore) IsPutPermitted(authInfo *AuthInfo, key []byte) error {
  726. return as.isOpPermitted(authInfo.Username, authInfo.Revision, key, nil, authpb.WRITE)
  727. }
  728. func (as *authStore) IsRangePermitted(authInfo *AuthInfo, key, rangeEnd []byte) error {
  729. return as.isOpPermitted(authInfo.Username, authInfo.Revision, key, rangeEnd, authpb.READ)
  730. }
  731. func (as *authStore) IsDeleteRangePermitted(authInfo *AuthInfo, key, rangeEnd []byte) error {
  732. return as.isOpPermitted(authInfo.Username, authInfo.Revision, key, rangeEnd, authpb.WRITE)
  733. }
  734. func (as *authStore) IsAdminPermitted(authInfo *AuthInfo) error {
  735. if !as.IsAuthEnabled() {
  736. return nil
  737. }
  738. if authInfo == nil {
  739. return ErrUserEmpty
  740. }
  741. tx := as.be.BatchTx()
  742. tx.Lock()
  743. u := getUser(as.lg, tx, authInfo.Username)
  744. tx.Unlock()
  745. if u == nil {
  746. return ErrUserNotFound
  747. }
  748. if !hasRootRole(u) {
  749. return ErrPermissionDenied
  750. }
  751. return nil
  752. }
  753. func getUser(lg *zap.Logger, tx backend.BatchTx, username string) *authpb.User {
  754. _, vs := tx.UnsafeRange(authUsersBucketName, []byte(username), nil, 0)
  755. if len(vs) == 0 {
  756. return nil
  757. }
  758. user := &authpb.User{}
  759. err := user.Unmarshal(vs[0])
  760. if err != nil {
  761. if lg != nil {
  762. lg.Panic(
  763. "failed to unmarshal 'authpb.User'",
  764. zap.String("user-name", username),
  765. zap.Error(err),
  766. )
  767. } else {
  768. plog.Panicf("failed to unmarshal user struct (name: %s): %s", username, err)
  769. }
  770. }
  771. return user
  772. }
  773. func getAllUsers(lg *zap.Logger, tx backend.BatchTx) []*authpb.User {
  774. _, vs := tx.UnsafeRange(authUsersBucketName, []byte{0}, []byte{0xff}, -1)
  775. if len(vs) == 0 {
  776. return nil
  777. }
  778. users := make([]*authpb.User, len(vs))
  779. for i := range vs {
  780. user := &authpb.User{}
  781. err := user.Unmarshal(vs[i])
  782. if err != nil {
  783. if lg != nil {
  784. lg.Panic("failed to unmarshal 'authpb.User'", zap.Error(err))
  785. } else {
  786. plog.Panicf("failed to unmarshal user struct: %s", err)
  787. }
  788. }
  789. users[i] = user
  790. }
  791. return users
  792. }
  793. func putUser(lg *zap.Logger, tx backend.BatchTx, user *authpb.User) {
  794. b, err := user.Marshal()
  795. if err != nil {
  796. if lg != nil {
  797. lg.Panic("failed to unmarshal 'authpb.User'", zap.Error(err))
  798. } else {
  799. plog.Panicf("failed to marshal user struct (name: %s): %s", user.Name, err)
  800. }
  801. }
  802. tx.UnsafePut(authUsersBucketName, user.Name, b)
  803. }
  804. func delUser(tx backend.BatchTx, username string) {
  805. tx.UnsafeDelete(authUsersBucketName, []byte(username))
  806. }
  807. func getRole(tx backend.BatchTx, rolename string) *authpb.Role {
  808. _, vs := tx.UnsafeRange(authRolesBucketName, []byte(rolename), nil, 0)
  809. if len(vs) == 0 {
  810. return nil
  811. }
  812. role := &authpb.Role{}
  813. err := role.Unmarshal(vs[0])
  814. if err != nil {
  815. plog.Panicf("failed to unmarshal role struct (name: %s): %s", rolename, err)
  816. }
  817. return role
  818. }
  819. func getAllRoles(lg *zap.Logger, tx backend.BatchTx) []*authpb.Role {
  820. _, vs := tx.UnsafeRange(authRolesBucketName, []byte{0}, []byte{0xff}, -1)
  821. if len(vs) == 0 {
  822. return nil
  823. }
  824. roles := make([]*authpb.Role, len(vs))
  825. for i := range vs {
  826. role := &authpb.Role{}
  827. err := role.Unmarshal(vs[i])
  828. if err != nil {
  829. if lg != nil {
  830. lg.Panic("failed to unmarshal 'authpb.Role'", zap.Error(err))
  831. } else {
  832. plog.Panicf("failed to unmarshal role struct: %s", err)
  833. }
  834. }
  835. roles[i] = role
  836. }
  837. return roles
  838. }
  839. func putRole(lg *zap.Logger, tx backend.BatchTx, role *authpb.Role) {
  840. b, err := role.Marshal()
  841. if err != nil {
  842. if lg != nil {
  843. lg.Panic(
  844. "failed to marshal 'authpb.Role'",
  845. zap.String("role-name", string(role.Name)),
  846. zap.Error(err),
  847. )
  848. } else {
  849. plog.Panicf("failed to marshal role struct (name: %s): %s", role.Name, err)
  850. }
  851. }
  852. tx.UnsafePut(authRolesBucketName, role.Name, b)
  853. }
  854. func delRole(tx backend.BatchTx, rolename string) {
  855. tx.UnsafeDelete(authRolesBucketName, []byte(rolename))
  856. }
  857. func (as *authStore) IsAuthEnabled() bool {
  858. as.enabledMu.RLock()
  859. defer as.enabledMu.RUnlock()
  860. return as.enabled
  861. }
  862. // NewAuthStore creates a new AuthStore.
  863. func NewAuthStore(lg *zap.Logger, be backend.Backend, tp TokenProvider) *authStore {
  864. tx := be.BatchTx()
  865. tx.Lock()
  866. tx.UnsafeCreateBucket(authBucketName)
  867. tx.UnsafeCreateBucket(authUsersBucketName)
  868. tx.UnsafeCreateBucket(authRolesBucketName)
  869. enabled := false
  870. _, vs := tx.UnsafeRange(authBucketName, enableFlagKey, nil, 0)
  871. if len(vs) == 1 {
  872. if bytes.Equal(vs[0], authEnabled) {
  873. enabled = true
  874. }
  875. }
  876. as := &authStore{
  877. revision: getRevision(tx),
  878. lg: lg,
  879. be: be,
  880. enabled: enabled,
  881. rangePermCache: make(map[string]*unifiedRangePermissions),
  882. tokenProvider: tp,
  883. }
  884. if enabled {
  885. as.tokenProvider.enable()
  886. }
  887. if as.Revision() == 0 {
  888. as.commitRevision(tx)
  889. }
  890. tx.Unlock()
  891. be.ForceCommit()
  892. return as
  893. }
  894. func hasRootRole(u *authpb.User) bool {
  895. // u.Roles is sorted in UserGrantRole(), so we can use binary search.
  896. idx := sort.SearchStrings(u.Roles, rootRole)
  897. return idx != len(u.Roles) && u.Roles[idx] == rootRole
  898. }
  899. func (as *authStore) commitRevision(tx backend.BatchTx) {
  900. atomic.AddUint64(&as.revision, 1)
  901. revBytes := make([]byte, revBytesLen)
  902. binary.BigEndian.PutUint64(revBytes, as.Revision())
  903. tx.UnsafePut(authBucketName, revisionKey, revBytes)
  904. }
  905. func getRevision(tx backend.BatchTx) uint64 {
  906. _, vs := tx.UnsafeRange(authBucketName, revisionKey, nil, 0)
  907. if len(vs) != 1 {
  908. // this can happen in the initialization phase
  909. return 0
  910. }
  911. return binary.BigEndian.Uint64(vs[0])
  912. }
  913. func (as *authStore) setRevision(rev uint64) {
  914. atomic.StoreUint64(&as.revision, rev)
  915. }
  916. func (as *authStore) Revision() uint64 {
  917. return atomic.LoadUint64(&as.revision)
  918. }
  919. func (as *authStore) AuthInfoFromTLS(ctx context.Context) (ai *AuthInfo) {
  920. peer, ok := peer.FromContext(ctx)
  921. if !ok || peer == nil || peer.AuthInfo == nil {
  922. return nil
  923. }
  924. tlsInfo := peer.AuthInfo.(credentials.TLSInfo)
  925. for _, chains := range tlsInfo.State.VerifiedChains {
  926. if len(chains) < 1 {
  927. continue
  928. }
  929. ai = &AuthInfo{
  930. Username: chains[0].Subject.CommonName,
  931. Revision: as.Revision(),
  932. }
  933. if as.lg != nil {
  934. as.lg.Debug(
  935. "found command name",
  936. zap.String("common-name", ai.Username),
  937. zap.String("user-name", ai.Username),
  938. zap.Uint64("revision", ai.Revision),
  939. )
  940. } else {
  941. plog.Debugf("found common name %s", ai.Username)
  942. }
  943. break
  944. }
  945. return ai
  946. }
  947. func (as *authStore) AuthInfoFromCtx(ctx context.Context) (*AuthInfo, error) {
  948. md, ok := metadata.FromIncomingContext(ctx)
  949. if !ok {
  950. return nil, nil
  951. }
  952. //TODO(mitake|hexfusion) review unifying key names
  953. ts, ok := md[rpctypes.TokenFieldNameGRPC]
  954. if !ok {
  955. ts, ok = md[rpctypes.TokenFieldNameSwagger]
  956. }
  957. if !ok {
  958. return nil, nil
  959. }
  960. token := ts[0]
  961. authInfo, uok := as.authInfoFromToken(ctx, token)
  962. if !uok {
  963. if as.lg != nil {
  964. as.lg.Warn("invalid auth token", zap.String("token", token))
  965. } else {
  966. plog.Warningf("invalid auth token: %s", token)
  967. }
  968. return nil, ErrInvalidAuthToken
  969. }
  970. return authInfo, nil
  971. }
  972. func (as *authStore) GenTokenPrefix() (string, error) {
  973. return as.tokenProvider.genTokenPrefix()
  974. }
  975. func decomposeOpts(lg *zap.Logger, optstr string) (string, map[string]string, error) {
  976. opts := strings.Split(optstr, ",")
  977. tokenType := opts[0]
  978. typeSpecificOpts := make(map[string]string)
  979. for i := 1; i < len(opts); i++ {
  980. pair := strings.Split(opts[i], "=")
  981. if len(pair) != 2 {
  982. if lg != nil {
  983. lg.Warn("invalid token option", zap.String("option", optstr))
  984. } else {
  985. plog.Errorf("invalid token specific option: %s", optstr)
  986. }
  987. return "", nil, ErrInvalidAuthOpts
  988. }
  989. if _, ok := typeSpecificOpts[pair[0]]; ok {
  990. if lg != nil {
  991. lg.Warn(
  992. "invalid token option",
  993. zap.String("option", optstr),
  994. zap.String("duplicate-parameter", pair[0]),
  995. )
  996. } else {
  997. plog.Errorf("invalid token specific option, duplicated parameters (%s): %s", pair[0], optstr)
  998. }
  999. return "", nil, ErrInvalidAuthOpts
  1000. }
  1001. typeSpecificOpts[pair[0]] = pair[1]
  1002. }
  1003. return tokenType, typeSpecificOpts, nil
  1004. }
  1005. // NewTokenProvider creates a new token provider.
  1006. func NewTokenProvider(
  1007. lg *zap.Logger,
  1008. tokenOpts string,
  1009. indexWaiter func(uint64) <-chan struct{}) (TokenProvider, error) {
  1010. tokenType, typeSpecificOpts, err := decomposeOpts(lg, tokenOpts)
  1011. if err != nil {
  1012. return nil, ErrInvalidAuthOpts
  1013. }
  1014. switch tokenType {
  1015. case "simple":
  1016. if lg != nil {
  1017. lg.Warn("simple token is not cryptographically signed")
  1018. } else {
  1019. plog.Warningf("simple token is not cryptographically signed")
  1020. }
  1021. return newTokenProviderSimple(lg, indexWaiter), nil
  1022. case "jwt":
  1023. return newTokenProviderJWT(lg, typeSpecificOpts)
  1024. case "":
  1025. return newTokenProviderNop()
  1026. default:
  1027. if lg != nil {
  1028. lg.Warn(
  1029. "unknown token type",
  1030. zap.String("type", tokenType),
  1031. zap.Error(ErrInvalidAuthOpts),
  1032. )
  1033. } else {
  1034. plog.Errorf("unknown token type: %s", tokenType)
  1035. }
  1036. return nil, ErrInvalidAuthOpts
  1037. }
  1038. }
  1039. func (as *authStore) WithRoot(ctx context.Context) context.Context {
  1040. if !as.IsAuthEnabled() {
  1041. return ctx
  1042. }
  1043. var ctxForAssign context.Context
  1044. if ts := as.tokenProvider.(*tokenSimple); ts != nil {
  1045. ctx1 := context.WithValue(ctx, AuthenticateParamIndex{}, uint64(0))
  1046. prefix, err := ts.genTokenPrefix()
  1047. if err != nil {
  1048. if as.lg != nil {
  1049. as.lg.Warn(
  1050. "failed to generate prefix of internally used token",
  1051. zap.Error(err),
  1052. )
  1053. } else {
  1054. plog.Errorf("failed to generate prefix of internally used token")
  1055. }
  1056. return ctx
  1057. }
  1058. ctxForAssign = context.WithValue(ctx1, AuthenticateParamSimpleTokenPrefix{}, prefix)
  1059. } else {
  1060. ctxForAssign = ctx
  1061. }
  1062. token, err := as.tokenProvider.assign(ctxForAssign, "root", as.Revision())
  1063. if err != nil {
  1064. // this must not happen
  1065. if as.lg != nil {
  1066. as.lg.Warn(
  1067. "failed to assign token for lease revoking",
  1068. zap.Error(err),
  1069. )
  1070. } else {
  1071. plog.Errorf("failed to assign token for lease revoking: %s", err)
  1072. }
  1073. return ctx
  1074. }
  1075. mdMap := map[string]string{
  1076. rpctypes.TokenFieldNameGRPC: token,
  1077. }
  1078. tokenMD := metadata.New(mdMap)
  1079. // use "mdIncomingKey{}" since it's called from local etcdserver
  1080. return metadata.NewIncomingContext(ctx, tokenMD)
  1081. }
  1082. func (as *authStore) HasRole(user, role string) bool {
  1083. tx := as.be.BatchTx()
  1084. tx.Lock()
  1085. u := getUser(as.lg, tx, user)
  1086. tx.Unlock()
  1087. if u == nil {
  1088. if as.lg != nil {
  1089. as.lg.Warn(
  1090. "'has-role' requested for non-existing user",
  1091. zap.String("user-name", user),
  1092. zap.String("role-name", role),
  1093. )
  1094. } else {
  1095. plog.Warningf("tried to check user %s has role %s, but user %s doesn't exist", user, role, user)
  1096. }
  1097. return false
  1098. }
  1099. for _, r := range u.Roles {
  1100. if role == r {
  1101. return true
  1102. }
  1103. }
  1104. return false
  1105. }