auth.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. package syncserv
  2. import (
  3. "crypto/hmac"
  4. "crypto/sha256"
  5. "errors"
  6. "net/http"
  7. "strings"
  8. "sync"
  9. "time"
  10. "golang.org/x/crypto/bcrypt"
  11. )
  12. /*
  13. auth.go
  14. How an upload request signs in: the user name in the Username header and
  15. the password as Authorization: Bearer <password>. HTTP Basic works too,
  16. for curl and for a browser opening the address to test the password.
  17. */
  18. const (
  19. refusedSignIn = "Invalid username or password"
  20. minPasswordLen = 8
  21. maxPasswordLen = 72 //bcrypt reads no further
  22. verifiedFor = 10 * time.Minute
  23. )
  24. var errRefused = errors.New(refusedSignIn)
  25. func firstHeader(r *http.Request, names ...string) string {
  26. for _, name := range names {
  27. if value := strings.TrimSpace(r.Header.Get(name)); value != "" {
  28. return value
  29. }
  30. }
  31. return ""
  32. }
  33. // stripBearer drops a "Bearer " in front of a password.
  34. func stripBearer(value string) (string, bool) {
  35. value = strings.TrimSpace(value)
  36. if len(value) > 7 && strings.EqualFold(value[:7], "bearer ") {
  37. return strings.TrimSpace(value[7:]), true
  38. }
  39. return value, false
  40. }
  41. // credentials reads the user name and password of an upload request.
  42. //
  43. // X-User-Name and X-User-Cred come first: a proxy in front of the server
  44. // (Cloudflare Access, a tunnel) may remove the Authorization header or put
  45. // its own in it, and these headers pass untouched. X-User-Cred holds the
  46. // password alone; a "Bearer " in front is tolerated.
  47. func credentials(r *http.Request) (string, string) {
  48. username := firstHeader(r, "X-User-Name", "Username", "X-Username")
  49. if cred := r.Header.Get("X-User-Cred"); strings.TrimSpace(cred) != "" {
  50. password, _ := stripBearer(cred)
  51. return username, password
  52. }
  53. if basicUser, basicPassword, ok := r.BasicAuth(); ok {
  54. if strings.TrimSpace(basicUser) != "" {
  55. username = strings.TrimSpace(basicUser)
  56. }
  57. return username, basicPassword
  58. }
  59. password, bearer := stripBearer(r.Header.Get("Authorization"))
  60. if !bearer {
  61. password = ""
  62. }
  63. return username, password
  64. }
  65. // ValidateSyncPassword checks a new sync password.
  66. func ValidateSyncPassword(password string) error {
  67. if len(password) < minPasswordLen {
  68. return errors.New("The sync password must be at least 8 characters long")
  69. }
  70. if len(password) > maxPasswordLen {
  71. return errors.New("The sync password must be at most 72 bytes long")
  72. }
  73. if strings.TrimSpace(password) != password {
  74. return errors.New("The sync password cannot start or end with a space")
  75. }
  76. for _, r := range password {
  77. if r < 0x20 || r == 0x7f {
  78. return errors.New("The sync password cannot contain control characters")
  79. }
  80. }
  81. return nil
  82. }
  83. // setSyncPassword stores the hash of a user's sync password.
  84. func (m *Manager) setSyncPassword(username, password string) error {
  85. if err := ValidateSyncPassword(password); err != nil {
  86. return err
  87. }
  88. hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
  89. if err != nil {
  90. return err
  91. }
  92. m.cache.forget(username)
  93. return m.opt.Sysdb.Write(settingsTable, prefixSecret+username, string(hash))
  94. }
  95. // checkPassword decides the password of an upload request.
  96. func (m *Manager) checkPassword(username, password string, settings UserSettings) error {
  97. if password == "" {
  98. return errRefused
  99. }
  100. if settings.LoginPassword {
  101. if m.opt.CheckLoginPassword != nil && m.opt.CheckLoginPassword(username, password) {
  102. return nil
  103. }
  104. return errRefused
  105. }
  106. if len(password) > maxPasswordLen {
  107. return errRefused
  108. }
  109. if m.cache.match(username, password) {
  110. return nil
  111. }
  112. hash := ""
  113. if err := m.opt.Sysdb.Read(settingsTable, prefixSecret+username, &hash); err != nil || hash == "" {
  114. return errRefused
  115. }
  116. if bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) != nil {
  117. return errRefused
  118. }
  119. m.cache.store(username, password)
  120. return nil
  121. }
  122. /*
  123. Verified passwords
  124. bcrypt takes a good part of a second on a small board, and a phone sends
  125. one request per photo, so a password that was right is remembered (as a
  126. keyed hash, in memory only) for ten minutes.
  127. */
  128. type verified struct {
  129. sum []byte
  130. until time.Time
  131. }
  132. type passwordCache struct {
  133. key []byte
  134. mu sync.Mutex
  135. m map[string]verified
  136. }
  137. func newPasswordCache(key []byte) *passwordCache {
  138. return &passwordCache{key: key, m: map[string]verified{}}
  139. }
  140. func (c *passwordCache) sum(username, password string) []byte {
  141. mac := hmac.New(sha256.New, c.key)
  142. mac.Write([]byte(username))
  143. mac.Write([]byte{0})
  144. mac.Write([]byte(password))
  145. return mac.Sum(nil)
  146. }
  147. func (c *passwordCache) match(username, password string) bool {
  148. c.mu.Lock()
  149. entry, ok := c.m[username]
  150. c.mu.Unlock()
  151. if !ok || time.Now().After(entry.until) {
  152. return false
  153. }
  154. return hmac.Equal(entry.sum, c.sum(username, password))
  155. }
  156. func (c *passwordCache) store(username, password string) {
  157. sum := c.sum(username, password)
  158. c.mu.Lock()
  159. c.m[username] = verified{sum: sum, until: time.Now().Add(verifiedFor)}
  160. c.mu.Unlock()
  161. }
  162. func (c *passwordCache) forget(username string) {
  163. c.mu.Lock()
  164. delete(c.m, username)
  165. c.mu.Unlock()
  166. }
  167. /*
  168. Wrong passwords
  169. After a few wrong passwords from one address for one user, and after
  170. more from anywhere for one user, requests for that user wait: two
  171. seconds, then twice as long after every further miss, up to 15 minutes.
  172. A right password clears both counts.
  173. */
  174. const (
  175. freeMissesPerAddress = 5
  176. freeMissesPerUser = 30
  177. maxWait = 15 * time.Minute
  178. forgetMissesAfter = time.Hour
  179. )
  180. type strike struct {
  181. misses int
  182. until time.Time
  183. last time.Time
  184. }
  185. type limiter struct {
  186. mu sync.Mutex
  187. m map[string]*strike
  188. }
  189. func newLimiter() *limiter {
  190. return &limiter{m: map[string]*strike{}}
  191. }
  192. func limiterKeys(username, address string) (string, string) {
  193. return "a/" + address + "/" + username, "u/" + username
  194. }
  195. // wait is how long requests for this user from this address must wait.
  196. func (l *limiter) wait(username, address string, now time.Time) time.Duration {
  197. byAddress, byUser := limiterKeys(username, address)
  198. l.mu.Lock()
  199. defer l.mu.Unlock()
  200. longest := time.Duration(0)
  201. for _, key := range []string{byAddress, byUser} {
  202. if s, ok := l.m[key]; ok && s.until.After(now) && s.until.Sub(now) > longest {
  203. longest = s.until.Sub(now)
  204. }
  205. }
  206. return longest
  207. }
  208. func (l *limiter) miss(username, address string, now time.Time) {
  209. byAddress, byUser := limiterKeys(username, address)
  210. l.mu.Lock()
  211. defer l.mu.Unlock()
  212. if len(l.m) > 4096 {
  213. for key, s := range l.m {
  214. if now.Sub(s.last) > forgetMissesAfter {
  215. delete(l.m, key)
  216. }
  217. }
  218. }
  219. for key, free := range map[string]int{byAddress: freeMissesPerAddress, byUser: freeMissesPerUser} {
  220. s, ok := l.m[key]
  221. if !ok || now.Sub(s.last) > forgetMissesAfter {
  222. s = &strike{}
  223. l.m[key] = s
  224. }
  225. s.misses++
  226. s.last = now
  227. if over := s.misses - free; over > 0 {
  228. wait := maxWait
  229. if over < 10 {
  230. wait = time.Duration(1<<uint(over)) * time.Second
  231. if wait > maxWait {
  232. wait = maxWait
  233. }
  234. }
  235. s.until = now.Add(wait)
  236. }
  237. }
  238. }
  239. func (l *limiter) clear(username, address string) {
  240. byAddress, byUser := limiterKeys(username, address)
  241. l.mu.Lock()
  242. delete(l.m, byAddress)
  243. delete(l.m, byUser)
  244. l.mu.Unlock()
  245. }