login_source.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. // FIXME: Put this file into its own package and separate into different files based on login sources.
  5. package db
  6. import (
  7. "crypto/tls"
  8. "fmt"
  9. "net/smtp"
  10. "net/textproto"
  11. "strings"
  12. "github.com/go-macaron/binding"
  13. "github.com/unknwon/com"
  14. "gogs.io/gogs/internal/auth/github"
  15. "gogs.io/gogs/internal/auth/ldap"
  16. "gogs.io/gogs/internal/auth/pam"
  17. "gogs.io/gogs/internal/db/errors"
  18. )
  19. type LoginType int
  20. // Note: new type must append to the end of list to maintain compatibility.
  21. // TODO: Move to authutil.
  22. const (
  23. LoginNotype LoginType = iota
  24. LoginPlain // 1
  25. LoginLDAP // 2
  26. LoginSMTP // 3
  27. LoginPAM // 4
  28. LoginDLDAP // 5
  29. LoginGitHub // 6
  30. )
  31. var LoginNames = map[LoginType]string{
  32. LoginLDAP: "LDAP (via BindDN)",
  33. LoginDLDAP: "LDAP (simple auth)", // Via direct bind
  34. LoginSMTP: "SMTP",
  35. LoginPAM: "PAM",
  36. LoginGitHub: "GitHub",
  37. }
  38. // ***********************
  39. // ----- LDAP config -----
  40. // ***********************
  41. type LDAPConfig struct {
  42. ldap.Source `ini:"config"`
  43. }
  44. var SecurityProtocolNames = map[ldap.SecurityProtocol]string{
  45. ldap.SecurityProtocolUnencrypted: "Unencrypted",
  46. ldap.SecurityProtocolLDAPS: "LDAPS",
  47. ldap.SecurityProtocolStartTLS: "StartTLS",
  48. }
  49. func (cfg *LDAPConfig) SecurityProtocolName() string {
  50. return SecurityProtocolNames[cfg.SecurityProtocol]
  51. }
  52. func composeFullName(firstname, surname, username string) string {
  53. switch {
  54. case len(firstname) == 0 && len(surname) == 0:
  55. return username
  56. case len(firstname) == 0:
  57. return surname
  58. case len(surname) == 0:
  59. return firstname
  60. default:
  61. return firstname + " " + surname
  62. }
  63. }
  64. // LoginViaLDAP queries if login/password is valid against the LDAP directory pool,
  65. // and create a local user if success when enabled.
  66. func LoginViaLDAP(login, password string, source *LoginSource, autoRegister bool) (*User, error) {
  67. username, fn, sn, mail, isAdmin, succeed := source.Config.(*LDAPConfig).SearchEntry(login, password, source.Type == LoginDLDAP)
  68. if !succeed {
  69. // User not in LDAP, do nothing
  70. return nil, ErrUserNotExist{args: map[string]interface{}{"login": login}}
  71. }
  72. if !autoRegister {
  73. return nil, nil
  74. }
  75. // Fallback.
  76. if len(username) == 0 {
  77. username = login
  78. }
  79. // Validate username make sure it satisfies requirement.
  80. if binding.AlphaDashDotPattern.MatchString(username) {
  81. return nil, fmt.Errorf("Invalid pattern for attribute 'username' [%s]: must be valid alpha or numeric or dash(-_) or dot characters", username)
  82. }
  83. if len(mail) == 0 {
  84. mail = fmt.Sprintf("%s@localhost", username)
  85. }
  86. user := &User{
  87. LowerName: strings.ToLower(username),
  88. Name: username,
  89. FullName: composeFullName(fn, sn, username),
  90. Email: mail,
  91. LoginType: source.Type,
  92. LoginSource: source.ID,
  93. LoginName: login,
  94. IsActive: true,
  95. IsAdmin: isAdmin,
  96. }
  97. ok, err := IsUserExist(0, user.Name)
  98. if err != nil {
  99. return user, err
  100. }
  101. if ok {
  102. return user, UpdateUser(user)
  103. }
  104. return user, CreateUser(user)
  105. }
  106. // ***********************
  107. // ----- SMTP config -----
  108. // ***********************
  109. type SMTPConfig struct {
  110. Auth string
  111. Host string
  112. Port int
  113. AllowedDomains string
  114. TLS bool `ini:"tls"`
  115. SkipVerify bool
  116. }
  117. type smtpLoginAuth struct {
  118. username, password string
  119. }
  120. func (auth *smtpLoginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
  121. return "LOGIN", []byte(auth.username), nil
  122. }
  123. func (auth *smtpLoginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
  124. if more {
  125. switch string(fromServer) {
  126. case "Username:":
  127. return []byte(auth.username), nil
  128. case "Password:":
  129. return []byte(auth.password), nil
  130. }
  131. }
  132. return nil, nil
  133. }
  134. const (
  135. SMTPPlain = "PLAIN"
  136. SMTPLogin = "LOGIN"
  137. )
  138. var SMTPAuths = []string{SMTPPlain, SMTPLogin}
  139. func SMTPAuth(a smtp.Auth, cfg *SMTPConfig) error {
  140. c, err := smtp.Dial(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port))
  141. if err != nil {
  142. return err
  143. }
  144. defer c.Close()
  145. if err = c.Hello("gogs"); err != nil {
  146. return err
  147. }
  148. if cfg.TLS {
  149. if ok, _ := c.Extension("STARTTLS"); ok {
  150. if err = c.StartTLS(&tls.Config{
  151. InsecureSkipVerify: cfg.SkipVerify,
  152. ServerName: cfg.Host,
  153. }); err != nil {
  154. return err
  155. }
  156. } else {
  157. return errors.New("SMTP server unsupports TLS")
  158. }
  159. }
  160. if ok, _ := c.Extension("AUTH"); ok {
  161. if err = c.Auth(a); err != nil {
  162. return err
  163. }
  164. return nil
  165. }
  166. return errors.New("Unsupported SMTP authentication method")
  167. }
  168. // LoginViaSMTP queries if login/password is valid against the SMTP,
  169. // and create a local user if success when enabled.
  170. func LoginViaSMTP(login, password string, sourceID int64, cfg *SMTPConfig, autoRegister bool) (*User, error) {
  171. // Verify allowed domains.
  172. if len(cfg.AllowedDomains) > 0 {
  173. idx := strings.Index(login, "@")
  174. if idx == -1 {
  175. return nil, ErrUserNotExist{args: map[string]interface{}{"login": login}}
  176. } else if !com.IsSliceContainsStr(strings.Split(cfg.AllowedDomains, ","), login[idx+1:]) {
  177. return nil, ErrUserNotExist{args: map[string]interface{}{"login": login}}
  178. }
  179. }
  180. var auth smtp.Auth
  181. if cfg.Auth == SMTPPlain {
  182. auth = smtp.PlainAuth("", login, password, cfg.Host)
  183. } else if cfg.Auth == SMTPLogin {
  184. auth = &smtpLoginAuth{login, password}
  185. } else {
  186. return nil, errors.New("Unsupported SMTP authentication type")
  187. }
  188. if err := SMTPAuth(auth, cfg); err != nil {
  189. // Check standard error format first,
  190. // then fallback to worse case.
  191. tperr, ok := err.(*textproto.Error)
  192. if (ok && tperr.Code == 535) ||
  193. strings.Contains(err.Error(), "Username and Password not accepted") {
  194. return nil, ErrUserNotExist{args: map[string]interface{}{"login": login}}
  195. }
  196. return nil, err
  197. }
  198. if !autoRegister {
  199. return nil, nil
  200. }
  201. username := login
  202. idx := strings.Index(login, "@")
  203. if idx > -1 {
  204. username = login[:idx]
  205. }
  206. user := &User{
  207. LowerName: strings.ToLower(username),
  208. Name: strings.ToLower(username),
  209. Email: login,
  210. Passwd: password,
  211. LoginType: LoginSMTP,
  212. LoginSource: sourceID,
  213. LoginName: login,
  214. IsActive: true,
  215. }
  216. return user, CreateUser(user)
  217. }
  218. // **********************
  219. // ----- PAM config -----
  220. // **********************
  221. type PAMConfig struct {
  222. // The name of the PAM service, e.g. system-auth.
  223. ServiceName string
  224. }
  225. // LoginViaPAM queries if login/password is valid against the PAM,
  226. // and create a local user if success when enabled.
  227. func LoginViaPAM(login, password string, sourceID int64, cfg *PAMConfig, autoRegister bool) (*User, error) {
  228. if err := pam.PAMAuth(cfg.ServiceName, login, password); err != nil {
  229. if strings.Contains(err.Error(), "Authentication failure") {
  230. return nil, ErrUserNotExist{args: map[string]interface{}{"login": login}}
  231. }
  232. return nil, err
  233. }
  234. if !autoRegister {
  235. return nil, nil
  236. }
  237. user := &User{
  238. LowerName: strings.ToLower(login),
  239. Name: login,
  240. Email: login,
  241. Passwd: password,
  242. LoginType: LoginPAM,
  243. LoginSource: sourceID,
  244. LoginName: login,
  245. IsActive: true,
  246. }
  247. return user, CreateUser(user)
  248. }
  249. // *************************
  250. // ----- GitHub config -----
  251. // *************************
  252. type GitHubConfig struct {
  253. // the GitHub service endpoint, e.g. https://api.github.com/.
  254. APIEndpoint string
  255. }
  256. func LoginViaGitHub(login, password string, sourceID int64, cfg *GitHubConfig, autoRegister bool) (*User, error) {
  257. fullname, email, url, location, err := github.Authenticate(cfg.APIEndpoint, login, password)
  258. if err != nil {
  259. if strings.Contains(err.Error(), "401") {
  260. return nil, ErrUserNotExist{args: map[string]interface{}{"login": login}}
  261. }
  262. return nil, err
  263. }
  264. if !autoRegister {
  265. return nil, nil
  266. }
  267. user := &User{
  268. LowerName: strings.ToLower(login),
  269. Name: login,
  270. FullName: fullname,
  271. Email: email,
  272. Website: url,
  273. Passwd: password,
  274. LoginType: LoginGitHub,
  275. LoginSource: sourceID,
  276. LoginName: login,
  277. IsActive: true,
  278. Location: location,
  279. }
  280. return user, CreateUser(user)
  281. }
  282. func authenticateViaLoginSource(source *LoginSource, login, password string, autoRegister bool) (*User, error) {
  283. if !source.IsActived {
  284. return nil, errors.LoginSourceNotActivated{SourceID: source.ID}
  285. }
  286. switch source.Type {
  287. case LoginLDAP, LoginDLDAP:
  288. return LoginViaLDAP(login, password, source, autoRegister)
  289. case LoginSMTP:
  290. return LoginViaSMTP(login, password, source.ID, source.Config.(*SMTPConfig), autoRegister)
  291. case LoginPAM:
  292. return LoginViaPAM(login, password, source.ID, source.Config.(*PAMConfig), autoRegister)
  293. case LoginGitHub:
  294. return LoginViaGitHub(login, password, source.ID, source.Config.(*GitHubConfig), autoRegister)
  295. }
  296. return nil, errors.InvalidLoginSourceType{Type: source.Type}
  297. }