auth.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. package auth
  2. // package for authenticating websockets
  3. // we use a homespun jwt knock-off because no tls on lan
  4. // authentication adds you to the AuthenticatedClients map
  5. // broadcasts get sent to members of this map
  6. import (
  7. "crypto/rand"
  8. "crypto/sha256"
  9. "encoding/base64"
  10. "encoding/hex"
  11. "encoding/json"
  12. "fmt"
  13. "goseg/config"
  14. "goseg/structs"
  15. "net"
  16. "net/http"
  17. "strings"
  18. "sync"
  19. "time"
  20. "github.com/gorilla/websocket"
  21. "golang.org/x/crypto/nacl/secretbox"
  22. )
  23. var (
  24. // maps a websocket conn to a tokenid
  25. // tokenid's can be referenced from the global conf
  26. AuthenticatedClients = struct {
  27. Conns map[*websocket.Conn]string
  28. sync.RWMutex
  29. }{
  30. Conns: make(map[*websocket.Conn]string),
  31. }
  32. UnauthClients = struct {
  33. Conns map[*websocket.Conn]string
  34. sync.RWMutex
  35. }{
  36. Conns: make(map[*websocket.Conn]string),
  37. }
  38. )
  39. // check if websocket session is in the auth map
  40. func WsIsAuthenticated(conn *websocket.Conn) bool {
  41. AuthenticatedClients.Lock()
  42. defer AuthenticatedClients.Unlock()
  43. _, exists := AuthenticatedClients.Conns[conn]
  44. return exists
  45. }
  46. // check if a hash is in the auth map
  47. func hashAuthenticated(hash string) bool {
  48. AuthenticatedClients.RLock() // Acquire read lock
  49. defer AuthenticatedClients.RUnlock() // Release read lock
  50. for _, v := range AuthenticatedClients.Conns {
  51. if v == hash {
  52. return true
  53. }
  54. }
  55. return false
  56. }
  57. // check the validity of the token
  58. func CheckToken(token string, conn *websocket.Conn, r *http.Request, setup bool) (bool, string, error) {
  59. if token == "" {
  60. authStatus := false
  61. if setup {
  62. authStatus = true
  63. }
  64. newToken, err := CreateToken(conn, r, setup)
  65. if err != nil {
  66. return false, "", err
  67. }
  68. return authStatus, newToken["token"], nil
  69. } else {
  70. conf := config.Conf()
  71. key := conf.KeyFile
  72. res, err := KeyfileDecrypt(token, key)
  73. if err != nil {
  74. config.Logger.Warn("Invalid token provided")
  75. return false, "", err
  76. } else {
  77. var ip string
  78. if forwarded := r.Header.Get("X-Forwarded-For"); forwarded != "" {
  79. ip = strings.Split(forwarded, ",")[0]
  80. } else {
  81. ip, _, _ = net.SplitHostPort(r.RemoteAddr)
  82. }
  83. userAgent := r.Header.Get("User-Agent")
  84. hashed := sha256.Sum256([]byte(token))
  85. hash := hex.EncodeToString(hashed[:])
  86. if hashAuthenticated(hash) {
  87. if ip == res["ip"] && userAgent == res["user_agent"] {
  88. return true, res["id"], nil
  89. } else {
  90. config.Logger.Warn("Token doesn't match session!")
  91. return false, res["id"], err
  92. }
  93. } else {
  94. config.Logger.Warn("Token isn't an authenticated session")
  95. return false, res["id"], err
  96. }
  97. }
  98. }
  99. return false, "", nil
  100. }
  101. // create a new session token
  102. func CreateToken(conn *websocket.Conn, r *http.Request, setup bool) (map[string]string, error) {
  103. // extract conn info
  104. var ip string
  105. if forwarded := r.Header.Get("X-Forwarded-For"); forwarded != "" {
  106. ip = strings.Split(forwarded, ",")[0]
  107. } else {
  108. ip, _, _ = net.SplitHostPort(r.RemoteAddr)
  109. }
  110. userAgent := r.Header.Get("User-Agent")
  111. conf := config.Conf()
  112. now := time.Now().Format("2006-01-02_15:04:05")
  113. // generate random strings for id, secret, and padding
  114. id := config.RandString(32)
  115. secret := config.RandString(128)
  116. padding := config.RandString(32)
  117. contents := map[string]string{
  118. "id": id,
  119. "ip": ip,
  120. "user_agent": userAgent,
  121. "secret": secret,
  122. "padding": padding,
  123. "authorized": fmt.Sprintf("%v", setup),
  124. "created": now,
  125. }
  126. // encrypt the contents
  127. key := conf.KeyFile
  128. encryptedText, err := KeyfileEncrypt(contents, key)
  129. if err != nil {
  130. return nil, fmt.Errorf("failed to encrypt token: %v", err)
  131. }
  132. hashed := sha256.Sum256([]byte(encryptedText))
  133. hash := hex.EncodeToString(hashed[:])
  134. // Update sessions in the system's configuration
  135. AddSession(id, hash, now, setup)
  136. return map[string]string{
  137. "id": id,
  138. "token": encryptedText,
  139. }, nil
  140. }
  141. // take session details and add to SysConfig
  142. func AddSession(tokenID string, hash string, created string, authorized bool) error {
  143. session := structs.SessionInfo{
  144. Hash: hash,
  145. Created: created,
  146. }
  147. if authorized {
  148. update := map[string]interface{}{
  149. "Sessions": map[string]interface{}{
  150. "Authorized": map[string]string{
  151. "Hash": session.Hash,
  152. "Created": session.Created,
  153. },
  154. },
  155. }
  156. if err := config.UpdateConf(update); err != nil {
  157. return fmt.Errorf("Error adding session: %v", err)
  158. }
  159. if err := config.RemoveSession(tokenID, false); err != nil {
  160. return fmt.Errorf("Error removing session: %v", err)
  161. }
  162. } else {
  163. update := map[string]interface{}{
  164. "Sessions": map[string]interface{}{
  165. "Unauthorized": map[string]string{
  166. "Hash": session.Hash,
  167. "Created": session.Created,
  168. },
  169. },
  170. }
  171. if err := config.UpdateConf(update); err != nil {
  172. return fmt.Errorf("Error adding session: %v", err)
  173. }
  174. if err := config.RemoveSession(tokenID, true); err != nil {
  175. return fmt.Errorf("Error removing session: %v", err)
  176. }
  177. }
  178. return nil
  179. }
  180. // encrypt the contents using stored keyfile val
  181. func KeyfileEncrypt(contents map[string]string, key string) (string, error) {
  182. contentBytes, err := json.Marshal(contents)
  183. if err != nil {
  184. return "", err
  185. }
  186. // convert key to bytes
  187. keyBytes := []byte(key)
  188. if len(keyBytes) != 32 {
  189. return "", fmt.Errorf("key must be 32 bytes in length")
  190. }
  191. var keyArray [32]byte
  192. copy(keyArray[:], keyBytes)
  193. // generate nonce
  194. var nonce [24]byte
  195. if _, err := rand.Read(nonce[:]); err != nil {
  196. return "", err
  197. }
  198. // encrypt contents
  199. encrypted := secretbox.Seal(nonce[:], contentBytes, &nonce, &keyArray)
  200. return base64.URLEncoding.EncodeToString(encrypted), nil
  201. }
  202. // decrypt routine
  203. func KeyfileDecrypt(encryptedText string, key string) (map[string]string, error) {
  204. // get bytes
  205. keyBytes := []byte(key)
  206. var keyArray [32]byte
  207. copy(keyArray[:], keyBytes)
  208. encryptedBytes, err := base64.URLEncoding.DecodeString(encryptedText)
  209. if err != nil {
  210. return nil, err
  211. }
  212. // get nonce
  213. var nonce [24]byte
  214. copy(nonce[:], encryptedBytes[:24])
  215. // attempt decrypt
  216. decrypted, ok := secretbox.Open(nil, encryptedBytes[24:], &nonce, &keyArray)
  217. if !ok {
  218. return nil, fmt.Errorf("Decryption failed")
  219. }
  220. var contents map[string]string
  221. if err := json.Unmarshal(decrypted, &contents); err != nil {
  222. return nil, err
  223. }
  224. return contents, nil
  225. }
  226. // salted sha256
  227. func Hasher(password string) string {
  228. conf := config.Conf()
  229. salt := conf.Salt
  230. toHash := salt + password
  231. res := sha256.Sum256([]byte(toHash))
  232. return hex.EncodeToString(res[:])
  233. }
  234. // check if pw matches sysconfig
  235. func AuthenticateLogin(password string) bool {
  236. conf := config.Conf()
  237. hash := Hasher(password)
  238. if hash == conf.PwHash {
  239. return true
  240. } else {
  241. config.Logger.Warn(fmt.Sprintf("debug: failed pw hash: %v",hash))
  242. return false
  243. }
  244. }