auth.go 7.9 KB

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