auth.go 7.4 KB

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