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.
 
 
 
 
 

84 rivejä
1.7 KiB

  1. package writefreely
  2. import (
  3. "crypto/rand"
  4. "github.com/writeas/web-core/log"
  5. "io/ioutil"
  6. "os"
  7. "path/filepath"
  8. )
  9. const (
  10. keysDir = "keys"
  11. encKeysBytes = 32
  12. )
  13. var (
  14. emailKeyPath = filepath.Join(keysDir, "email.aes256")
  15. cookieAuthKeyPath = filepath.Join(keysDir, "cookies_auth.aes256")
  16. cookieKeyPath = filepath.Join(keysDir, "cookies_enc.aes256")
  17. )
  18. type keychain struct {
  19. emailKey, cookieAuthKey, cookieKey []byte
  20. }
  21. func initKeys(app *app) error {
  22. var err error
  23. app.keys = &keychain{}
  24. app.keys.emailKey, err = ioutil.ReadFile(emailKeyPath)
  25. if err != nil {
  26. return err
  27. }
  28. app.keys.cookieAuthKey, err = ioutil.ReadFile(cookieAuthKeyPath)
  29. if err != nil {
  30. return err
  31. }
  32. app.keys.cookieKey, err = ioutil.ReadFile(cookieKeyPath)
  33. if err != nil {
  34. return err
  35. }
  36. return nil
  37. }
  38. // generateKey generates a key at the given path used for the encryption of
  39. // certain user data. Because user data becomes unrecoverable without these
  40. // keys, this won't overwrite any existing key, and instead outputs a message.
  41. func generateKey(path string) error {
  42. // Check if key file exists
  43. if _, err := os.Stat(path); !os.IsNotExist(err) {
  44. log.Info("%s already exists. rm the file if you understand the consquences.", path)
  45. return nil
  46. }
  47. log.Info("Generating %s.", path)
  48. b, err := generateBytes(encKeysBytes)
  49. if err != nil {
  50. log.Error("FAILED. %s. Run writefreely --gen-keys again.", err)
  51. return err
  52. }
  53. err = ioutil.WriteFile(path, b, 0600)
  54. if err != nil {
  55. log.Error("FAILED writing file: %s", err)
  56. return err
  57. }
  58. log.Info("Success.")
  59. return nil
  60. }
  61. // generateBytes returns securely generated random bytes.
  62. func generateBytes(n int) ([]byte, error) {
  63. b := make([]byte, n)
  64. _, err := rand.Read(b)
  65. if err != nil {
  66. return nil, err
  67. }
  68. return b, nil
  69. }