A clean, Markdown-based publishing platform made for writers. Write together, and build a community. https://writefreely.org
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

75 lines
2.1 KiB

  1. /*
  2. * Copyright © 2018-2019, 2021 Musing Studio LLC.
  3. *
  4. * This file is part of WriteFreely.
  5. *
  6. * WriteFreely is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License, included
  8. * in the LICENSE file in this source code package.
  9. */
  10. package writefreely
  11. import (
  12. "github.com/writeas/web-core/log"
  13. "github.com/writefreely/writefreely/key"
  14. "os"
  15. "path/filepath"
  16. )
  17. const (
  18. keysDir = "keys"
  19. )
  20. var (
  21. emailKeyPath = filepath.Join(keysDir, "email.aes256")
  22. cookieAuthKeyPath = filepath.Join(keysDir, "cookies_auth.aes256")
  23. cookieKeyPath = filepath.Join(keysDir, "cookies_enc.aes256")
  24. csrfKeyPath = filepath.Join(keysDir, "csrf.aes256")
  25. )
  26. // InitKeys loads encryption keys into memory via the given Apper interface
  27. func InitKeys(apper Apper) error {
  28. log.Info("Loading encryption keys...")
  29. err := apper.LoadKeys()
  30. if err != nil {
  31. return err
  32. }
  33. return nil
  34. }
  35. func initKeyPaths(app *App) {
  36. emailKeyPath = filepath.Join(app.cfg.Server.KeysParentDir, emailKeyPath)
  37. cookieAuthKeyPath = filepath.Join(app.cfg.Server.KeysParentDir, cookieAuthKeyPath)
  38. cookieKeyPath = filepath.Join(app.cfg.Server.KeysParentDir, cookieKeyPath)
  39. csrfKeyPath = filepath.Join(app.cfg.Server.KeysParentDir, csrfKeyPath)
  40. }
  41. // generateKey generates a key at the given path used for the encryption of
  42. // certain user data. Because user data becomes unrecoverable without these
  43. // keys, this won't overwrite any existing key, and instead outputs a message.
  44. func generateKey(path string) error {
  45. // Check if key file exists
  46. if _, err := os.Stat(path); err == nil {
  47. log.Info("%s already exists. rm the file if you understand the consequences.", path)
  48. return nil
  49. } else if !os.IsNotExist(err) {
  50. log.Error("%s", err)
  51. return err
  52. }
  53. log.Info("Generating %s.", path)
  54. b, err := key.GenerateBytes(key.EncKeysBytes)
  55. if err != nil {
  56. log.Error("FAILED. %s. Run writefreely --gen-keys again.", err)
  57. return err
  58. }
  59. err = os.WriteFile(path, b, 0600)
  60. if err != nil {
  61. log.Error("FAILED writing file: %s", err)
  62. return err
  63. }
  64. log.Info("Success.")
  65. return nil
  66. }