auth.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. // the same but the other way
  94. func RemoveFromAuthMap(tokenId string, fromAuthorized bool) error {
  95. if fromAuthorized {
  96. AuthenticatedClients.Lock()
  97. if _, ok := AuthenticatedClients.Conns[tokenId]; ok {
  98. delete(AuthenticatedClients.Conns, tokenId)
  99. }
  100. AuthenticatedClients.Unlock()
  101. } else {
  102. UnauthClients.Lock()
  103. if _, ok := UnauthClients.Conns[tokenId]; ok {
  104. delete(UnauthClients.Conns, tokenId)
  105. }
  106. UnauthClients.Unlock()
  107. }
  108. return nil
  109. }
  110. // check the validity of the token
  111. func CheckToken(token map[string]string, conn *websocket.Conn, r *http.Request, setup bool) bool {
  112. // great you have token. we see if valid.
  113. if token["token"] == "" {
  114. return false
  115. }
  116. config.Logger.Info(fmt.Sprintf("Checking token %s",token["id"]))
  117. conf := config.Conf()
  118. key := conf.KeyFile
  119. res, err := KeyfileDecrypt(token["token"], key)
  120. if err != nil {
  121. config.Logger.Warn("Invalid token provided")
  122. return false
  123. } else {
  124. // so you decrypt. now we see the useragent and ip.
  125. var ip string
  126. if forwarded := r.Header.Get("X-Forwarded-For"); forwarded != "" {
  127. ip = strings.Split(forwarded, ",")[0]
  128. } else {
  129. ip, _, _ = net.SplitHostPort(r.RemoteAddr)
  130. }
  131. userAgent := r.Header.Get("User-Agent")
  132. hashed := sha512.Sum512([]byte(token["token"]))
  133. hash := hex.EncodeToString(hashed[:])
  134. // you in auth map?
  135. if WsIsAuthenticated(conn, hash) {
  136. if ip == res["ip"] && userAgent == res["user_agent"] {
  137. config.Logger.Info("Token authenticated")
  138. return true
  139. } else {
  140. config.Logger.Warn("Token doesn't match session!")
  141. return false
  142. }
  143. } else {
  144. config.Logger.Warn("Token isn't an authenticated session")
  145. return false
  146. }
  147. }
  148. return false
  149. }
  150. // create a new session token
  151. func CreateToken(conn *websocket.Conn, r *http.Request, setup bool) (map[string]string, error) {
  152. // extract conn info
  153. var ip string
  154. if forwarded := r.Header.Get("X-Forwarded-For"); forwarded != "" {
  155. ip = strings.Split(forwarded, ",")[0]
  156. } else {
  157. ip, _, _ = net.SplitHostPort(r.RemoteAddr)
  158. }
  159. userAgent := r.Header.Get("User-Agent")
  160. conf := config.Conf()
  161. now := time.Now().Format("2006-01-02_15:04:05")
  162. // generate random strings for id, secret, and padding
  163. id := config.RandString(32)
  164. secret := config.RandString(128)
  165. padding := config.RandString(32)
  166. contents := map[string]string{
  167. "id": id,
  168. "ip": ip,
  169. "user_agent": userAgent,
  170. "secret": secret,
  171. "padding": padding,
  172. "authorized": fmt.Sprintf("%v", setup),
  173. "created": now,
  174. }
  175. // encrypt the contents
  176. key := conf.KeyFile
  177. encryptedText, err := KeyfileEncrypt(contents, key)
  178. if err != nil {
  179. config.Logger.Error(fmt.Sprintf("failed to encrypt token: %v", err))
  180. return nil, fmt.Errorf("failed to encrypt token: %v", err)
  181. }
  182. token := map[string]string{
  183. "id": id,
  184. "token": encryptedText,
  185. }
  186. // Update sessions in the system's configuration
  187. AddToAuthMap(conn, token, setup)
  188. return token, nil
  189. }
  190. // take session details and add to SysConfig
  191. func AddSession(tokenID string, hash string, created string, authorized bool) error {
  192. session := structs.SessionInfo{
  193. Hash: hash,
  194. Created: created,
  195. }
  196. if authorized {
  197. update := map[string]interface{}{
  198. "Sessions": map[string]interface{}{
  199. "Authorized": map[string]structs.SessionInfo{
  200. tokenID: session,
  201. },
  202. },
  203. }
  204. if err := config.UpdateConf(update); err != nil {
  205. return fmt.Errorf("Error adding session: %v", err)
  206. }
  207. if err := RemoveFromAuthMap(tokenID, false); err != nil {
  208. return fmt.Errorf("Error removing session: %v", err)
  209. }
  210. } else {
  211. update := map[string]interface{}{
  212. "Sessions": map[string]interface{}{
  213. "Unauthorized": map[string]structs.SessionInfo{
  214. tokenID: session,
  215. },
  216. },
  217. }
  218. if err := config.UpdateConf(update); err != nil {
  219. return fmt.Errorf("Error adding session: %v", err)
  220. }
  221. if err := RemoveFromAuthMap(tokenID, true); err != nil {
  222. return fmt.Errorf("Error removing session: %v", err)
  223. }
  224. }
  225. return nil
  226. }
  227. // encrypt the contents using stored keyfile val
  228. func KeyfileEncrypt(contents map[string]string, keyStr string) (string, error) {
  229. fileBytes, err := ioutil.ReadFile(keyStr)
  230. if err != nil {
  231. return "", err
  232. }
  233. contentBytes, err := json.Marshal(contents)
  234. if err != nil {
  235. return "", err
  236. }
  237. key, err := fernet.DecodeKey(string(fileBytes))
  238. if err != nil {
  239. return "", err
  240. }
  241. tok, err := fernet.EncryptAndSign(contentBytes, key)
  242. if err != nil {
  243. return "", err
  244. }
  245. return string(tok), nil
  246. }
  247. func KeyfileDecrypt(tokenStr string, keyStr string) (map[string]string, error) {
  248. fileBytes, err := ioutil.ReadFile(keyStr)
  249. if err != nil {
  250. return nil, err
  251. }
  252. key, err := fernet.DecodeKey(string(fileBytes))
  253. if err != nil {
  254. return nil, err
  255. }
  256. decrypted := fernet.VerifyAndDecrypt([]byte(tokenStr), 60*time.Second, []*fernet.Key{key})
  257. if decrypted == nil {
  258. return nil, fmt.Errorf("verification or decryption failed")
  259. }
  260. var contents map[string]string
  261. err = json.Unmarshal(decrypted, &contents)
  262. if err != nil {
  263. return nil, err
  264. }
  265. return contents, nil
  266. }
  267. // salted sha512
  268. func Hasher(password string) string {
  269. conf := config.Conf()
  270. salt := conf.Salt
  271. toHash := salt + password
  272. res := sha512.Sum512([]byte(toHash))
  273. return hex.EncodeToString(res[:])
  274. }
  275. // check if pw matches sysconfig
  276. func AuthenticateLogin(password string) bool {
  277. conf := config.Conf()
  278. hash := Hasher(password)
  279. if hash == conf.PwHash {
  280. return true
  281. } else {
  282. config.Logger.Warn(fmt.Sprintf("debug: failed pw hash: %v", hash))
  283. return false
  284. }
  285. }