auth.go 7.2 KB

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