A clean, Markdown-based publishing platform made for writers. Write together, and build a community. https://writefreely.org
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 

76 行
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. "io/ioutil"
  15. "os"
  16. "path/filepath"
  17. )
  18. const (
  19. keysDir = "keys"
  20. )
  21. var (
  22. emailKeyPath = filepath.Join(keysDir, "email.aes256")
  23. cookieAuthKeyPath = filepath.Join(keysDir, "cookies_auth.aes256")
  24. cookieKeyPath = filepath.Join(keysDir, "cookies_enc.aes256")
  25. csrfKeyPath = filepath.Join(keysDir, "csrf.aes256")
  26. )
  27. // InitKeys loads encryption keys into memory via the given Apper interface
  28. func InitKeys(apper Apper) error {
  29. log.Info("Loading encryption keys...")
  30. err := apper.LoadKeys()
  31. if err != nil {
  32. return err
  33. }
  34. return nil
  35. }
  36. func initKeyPaths(app *App) {
  37. emailKeyPath = filepath.Join(app.cfg.Server.KeysParentDir, emailKeyPath)
  38. cookieAuthKeyPath = filepath.Join(app.cfg.Server.KeysParentDir, cookieAuthKeyPath)
  39. cookieKeyPath = filepath.Join(app.cfg.Server.KeysParentDir, cookieKeyPath)
  40. csrfKeyPath = filepath.Join(app.cfg.Server.KeysParentDir, csrfKeyPath)
  41. }
  42. // generateKey generates a key at the given path used for the encryption of
  43. // certain user data. Because user data becomes unrecoverable without these
  44. // keys, this won't overwrite any existing key, and instead outputs a message.
  45. func generateKey(path string) error {
  46. // Check if key file exists
  47. if _, err := os.Stat(path); err == nil {
  48. log.Info("%s already exists. rm the file if you understand the consquences.", path)
  49. return nil
  50. } else if !os.IsNotExist(err) {
  51. log.Error("%s", err)
  52. return err
  53. }
  54. log.Info("Generating %s.", path)
  55. b, err := key.GenerateBytes(key.EncKeysBytes)
  56. if err != nil {
  57. log.Error("FAILED. %s. Run writefreely --gen-keys again.", err)
  58. return err
  59. }
  60. err = ioutil.WriteFile(path, b, 0600)
  61. if err != nil {
  62. log.Error("FAILED writing file: %s", err)
  63. return err
  64. }
  65. log.Info("Success.")
  66. return nil
  67. }