user_linux.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. package cmd
  2. import (
  3. "crypto/subtle"
  4. "errors"
  5. "fmt"
  6. "github.com/urfave/cli/v2"
  7. "github.com/urfave/cli/v2/altsrc"
  8. "heckel.io/ntfy/auth"
  9. "heckel.io/ntfy/util"
  10. "strings"
  11. )
  12. func init() {
  13. commands = append(commands, cmdUser)
  14. }
  15. var flagsUser = userCommandFlags()
  16. var cmdUser = &cli.Command{
  17. Name: "user",
  18. Usage: "Manage/show users",
  19. UsageText: "ntfy user [list|add|remove|change-pass|change-role] ...",
  20. Flags: flagsUser,
  21. Before: initConfigFileInputSourceFunc("config", flagsUser),
  22. Category: categoryServer,
  23. Subcommands: []*cli.Command{
  24. {
  25. Name: "add",
  26. Aliases: []string{"a"},
  27. Usage: "Adds a new user",
  28. UsageText: "ntfy user add [--role=admin|user] USERNAME",
  29. Action: execUserAdd,
  30. Flags: []cli.Flag{
  31. &cli.StringFlag{Name: "role", Aliases: []string{"r"}, Value: string(auth.RoleUser), Usage: "user role"},
  32. },
  33. Description: `Add a new user to the ntfy user database.
  34. A user can be either a regular user, or an admin. A regular user has no read or write access (unless
  35. granted otherwise by the auth-default-access setting). An admin user has read and write access to all
  36. topics.
  37. Examples:
  38. ntfy user add phil # Add regular user phil
  39. ntfy user add --role=admin phil # Add admin user phil
  40. `,
  41. },
  42. {
  43. Name: "remove",
  44. Aliases: []string{"del", "rm"},
  45. Usage: "Removes a user",
  46. UsageText: "ntfy user remove USERNAME",
  47. Action: execUserDel,
  48. Description: `Remove a user from the ntfy user database.
  49. Example:
  50. ntfy user del phil
  51. `,
  52. },
  53. {
  54. Name: "change-pass",
  55. Aliases: []string{"chp"},
  56. Usage: "Changes a user's password",
  57. UsageText: "ntfy user change-pass USERNAME",
  58. Action: execUserChangePass,
  59. Description: `Change the password for the given user.
  60. The new password will be read from STDIN, and it'll be confirmed by typing
  61. it twice.
  62. Example:
  63. ntfy user change-pass phil
  64. `,
  65. },
  66. {
  67. Name: "change-role",
  68. Aliases: []string{"chr"},
  69. Usage: "Changes the role of a user",
  70. UsageText: "ntfy user change-role USERNAME ROLE",
  71. Action: execUserChangeRole,
  72. Description: `Change the role for the given user to admin or user.
  73. This command can be used to change the role of a user either from a regular user
  74. to an admin user, or the other way around:
  75. - admin: an admin has read/write access to all topics
  76. - user: a regular user only has access to what was explicitly granted via 'ntfy access'
  77. When changing the role of a user to "admin", all access control entries for that
  78. user are removed, since they are no longer necessary.
  79. Example:
  80. ntfy user change-role phil admin # Make user phil an admin
  81. ntfy user change-role phil user # Remove admin role from user phil
  82. `,
  83. },
  84. {
  85. Name: "list",
  86. Aliases: []string{"l"},
  87. Usage: "Shows a list of users",
  88. Action: execUserList,
  89. Description: `Shows a list of all configured users, including the everyone ('*') user.
  90. This is a server-only command. It directly reads from the user.db as defined in the server config
  91. file server.yml. The command only works if 'auth-file' is properly defined.
  92. This command is an alias to calling 'ntfy access' (display access control list).
  93. `,
  94. },
  95. },
  96. Description: `Manage users of the ntfy server.
  97. This is a server-only command. It directly manages the user.db as defined in the server config
  98. file server.yml. The command only works if 'auth-file' is properly defined. Please also refer
  99. to the related command 'ntfy access'.
  100. The command allows you to add/remove/change users in the ntfy user database, as well as change
  101. passwords or roles.
  102. Examples:
  103. ntfy user list # Shows list of users (alias: 'ntfy access')
  104. ntfy user add phil # Add regular user phil
  105. ntfy user add --role=admin phil # Add admin user phil
  106. ntfy user del phil # Delete user phil
  107. ntfy user change-pass phil # Change password for user phil
  108. ntfy user change-role phil admin # Make user phil an admin
  109. `,
  110. }
  111. func execUserAdd(c *cli.Context) error {
  112. username := c.Args().Get(0)
  113. role := auth.Role(c.String("role"))
  114. if username == "" {
  115. return errors.New("username expected, type 'ntfy user add --help' for help")
  116. } else if username == userEveryone {
  117. return errors.New("username not allowed")
  118. } else if !auth.AllowedRole(role) {
  119. return errors.New("role must be either 'user' or 'admin'")
  120. }
  121. manager, err := createAuthManager(c)
  122. if err != nil {
  123. return err
  124. }
  125. if user, _ := manager.User(username); user != nil {
  126. return fmt.Errorf("user %s already exists", username)
  127. }
  128. password, err := readPasswordAndConfirm(c)
  129. if err != nil {
  130. return err
  131. }
  132. if err := manager.AddUser(username, password, role); err != nil {
  133. return err
  134. }
  135. fmt.Fprintf(c.App.ErrWriter, "user %s added with role %s\n", username, role)
  136. return nil
  137. }
  138. func execUserDel(c *cli.Context) error {
  139. username := c.Args().Get(0)
  140. if username == "" {
  141. return errors.New("username expected, type 'ntfy user del --help' for help")
  142. } else if username == userEveryone {
  143. return errors.New("username not allowed")
  144. }
  145. manager, err := createAuthManager(c)
  146. if err != nil {
  147. return err
  148. }
  149. if _, err := manager.User(username); err == auth.ErrNotFound {
  150. return fmt.Errorf("user %s does not exist", username)
  151. }
  152. if err := manager.RemoveUser(username); err != nil {
  153. return err
  154. }
  155. fmt.Fprintf(c.App.ErrWriter, "user %s removed\n", username)
  156. return nil
  157. }
  158. func execUserChangePass(c *cli.Context) error {
  159. username := c.Args().Get(0)
  160. if username == "" {
  161. return errors.New("username expected, type 'ntfy user change-pass --help' for help")
  162. } else if username == userEveryone {
  163. return errors.New("username not allowed")
  164. }
  165. manager, err := createAuthManager(c)
  166. if err != nil {
  167. return err
  168. }
  169. if _, err := manager.User(username); err == auth.ErrNotFound {
  170. return fmt.Errorf("user %s does not exist", username)
  171. }
  172. password, err := readPasswordAndConfirm(c)
  173. if err != nil {
  174. return err
  175. }
  176. if err := manager.ChangePassword(username, password); err != nil {
  177. return err
  178. }
  179. fmt.Fprintf(c.App.ErrWriter, "changed password for user %s\n", username)
  180. return nil
  181. }
  182. func execUserChangeRole(c *cli.Context) error {
  183. username := c.Args().Get(0)
  184. role := auth.Role(c.Args().Get(1))
  185. if username == "" || !auth.AllowedRole(role) {
  186. return errors.New("username and new role expected, type 'ntfy user change-role --help' for help")
  187. } else if username == userEveryone {
  188. return errors.New("username not allowed")
  189. }
  190. manager, err := createAuthManager(c)
  191. if err != nil {
  192. return err
  193. }
  194. if _, err := manager.User(username); err == auth.ErrNotFound {
  195. return fmt.Errorf("user %s does not exist", username)
  196. }
  197. if err := manager.ChangeRole(username, role); err != nil {
  198. return err
  199. }
  200. fmt.Fprintf(c.App.ErrWriter, "changed role for user %s to %s\n", username, role)
  201. return nil
  202. }
  203. func execUserList(c *cli.Context) error {
  204. manager, err := createAuthManager(c)
  205. if err != nil {
  206. return err
  207. }
  208. users, err := manager.Users()
  209. if err != nil {
  210. return err
  211. }
  212. return showUsers(c, manager, users)
  213. }
  214. func createAuthManager(c *cli.Context) (auth.Manager, error) {
  215. authFile := c.String("auth-file")
  216. authDefaultAccess := c.String("auth-default-access")
  217. if authFile == "" {
  218. return nil, errors.New("option auth-file not set; auth is unconfigured for this server")
  219. } else if !util.FileExists(authFile) {
  220. return nil, errors.New("auth-file does not exist; please start the server at least once to create it")
  221. } else if !util.InStringList([]string{"read-write", "read-only", "write-only", "deny-all"}, authDefaultAccess) {
  222. return nil, errors.New("if set, auth-default-access must start set to 'read-write', 'read-only' or 'deny-all'")
  223. }
  224. authDefaultRead := authDefaultAccess == "read-write" || authDefaultAccess == "read-only"
  225. authDefaultWrite := authDefaultAccess == "read-write" || authDefaultAccess == "write-only"
  226. return auth.NewSQLiteAuth(authFile, authDefaultRead, authDefaultWrite)
  227. }
  228. func readPasswordAndConfirm(c *cli.Context) (string, error) {
  229. fmt.Fprint(c.App.ErrWriter, "password: ")
  230. password, err := util.ReadPassword(c.App.Reader)
  231. if err != nil {
  232. return "", err
  233. }
  234. fmt.Fprintf(c.App.ErrWriter, "\r%s\rconfirm: ", strings.Repeat(" ", 25))
  235. confirm, err := util.ReadPassword(c.App.Reader)
  236. if err != nil {
  237. return "", err
  238. }
  239. fmt.Fprintf(c.App.ErrWriter, "\r%s\r", strings.Repeat(" ", 25))
  240. if subtle.ConstantTimeCompare(confirm, password) != 1 {
  241. return "", errors.New("passwords do not match: try it again, but this time type slooowwwlly")
  242. }
  243. return string(password), nil
  244. }
  245. func userCommandFlags() []cli.Flag {
  246. return []cli.Flag{
  247. &cli.StringFlag{Name: "config", Aliases: []string{"c"}, EnvVars: []string{"NTFY_CONFIG_FILE"}, Value: "/etc/ntfy/server.yml", DefaultText: "/etc/ntfy/server.yml", Usage: "config file"},
  248. altsrc.NewStringFlag(&cli.StringFlag{Name: "auth-file", Aliases: []string{"H"}, EnvVars: []string{"NTFY_AUTH_FILE"}, Usage: "auth database file used for access control"}),
  249. altsrc.NewStringFlag(&cli.StringFlag{Name: "auth-default-access", Aliases: []string{"p"}, EnvVars: []string{"NTFY_AUTH_DEFAULT_ACCESS"}, Value: "read-write", Usage: "default permissions if no matching entries in the auth database are found"}),
  250. }
  251. }