From 5acfae3d0d80affd0ba27533aff467a87237b712 Mon Sep 17 00:00:00 2001 From: Harvey Kandola Date: Fri, 21 Jul 2017 12:20:13 +0100 Subject: [PATCH] refactored salt code --- core/secrets/salt.go | 38 ++++++++++++++++++++++++++++++++++++++ edition/boot/runtime.go | 23 +++++------------------ 2 files changed, 43 insertions(+), 18 deletions(-) create mode 100644 core/secrets/salt.go diff --git a/core/secrets/salt.go b/core/secrets/salt.go new file mode 100644 index 00000000..b56d2ed7 --- /dev/null +++ b/core/secrets/salt.go @@ -0,0 +1,38 @@ +// Copyright 2016 Documize Inc. . All rights reserved. +// +// This software (Documize Community Edition) is licensed under +// GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html +// +// You can operate outside the AGPL restrictions by purchasing +// Documize Enterprise Edition and obtaining a commercial license +// by contacting . +// +// https://documize.com + +package secrets + +import ( + "crypto/rand" + "fmt" +) + +// RandSalt generates 16 character value for use in JWT token as salt. +func RandSalt() string { + b := make([]byte, 17) + + _, err := rand.Read(b) + if err != nil { + return "" + } + + for k, v := range b { + if (v >= 'a' && v <= 'z') || (v >= 'A' && v <= 'Z') || (v >= '0' && v <= '0') { + b[k] = v + } else { + s := fmt.Sprintf("%x", v) + b[k] = s[0] + } + } + + return string(b) +} diff --git a/edition/boot/runtime.go b/edition/boot/runtime.go index b89db022..561094c9 100644 --- a/edition/boot/runtime.go +++ b/edition/boot/runtime.go @@ -13,43 +13,30 @@ package boot import ( - "crypto/rand" - "fmt" "strings" "time" "github.com/documize/community/core/database" "github.com/documize/community/core/env" + "github.com/documize/community/core/secrets" "github.com/documize/community/core/web" "github.com/jmoiron/sqlx" ) // InitRuntime prepares runtime using command line and environment variables. func InitRuntime(r *env.Runtime) bool { - // Prepare SALT + // We need SALT to hash auth JWT tokens if r.Flags.Salt == "" { - b := make([]byte, 17) + r.Flags.Salt = secrets.RandSalt() - _, err := rand.Read(b) - if err != nil { - r.Log.Error("problem using crypto/rand", err) + if r.Flags.Salt == "" { return false } - for k, v := range b { - if (v >= 'a' && v <= 'z') || (v >= 'A' && v <= 'Z') || (v >= '0' && v <= '0') { - b[k] = v - } else { - s := fmt.Sprintf("%x", v) - b[k] = s[0] - } - } - - r.Flags.Salt = string(b) r.Log.Info("please set DOCUMIZESALT or use -salt with this value: " + r.Flags.Salt) } - // Prepare HTTP ports + // We can use either or both HTTP and HTTPS ports if r.Flags.SSLCertFile == "" && r.Flags.SSLKeyFile == "" { if r.Flags.HTTPPort == "" { r.Flags.HTTPPort = "80"