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.
 
 
 
 
 

94 lines
2.0 KiB

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