auth.go 7.4 KB

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