login.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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. package models
  5. import (
  6. "crypto/tls"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "net/smtp"
  11. "strings"
  12. "time"
  13. "github.com/go-xorm/core"
  14. "github.com/go-xorm/xorm"
  15. "github.com/gogits/gogs/modules/auth/ldap"
  16. "github.com/gogits/gogs/modules/auth/pam"
  17. "github.com/gogits/gogs/modules/log"
  18. )
  19. type LoginType int
  20. const (
  21. NOTYPE LoginType = iota
  22. PLAIN
  23. LDAP
  24. DLDAP
  25. SMTP
  26. PAM
  27. )
  28. var (
  29. ErrAuthenticationAlreadyExist = errors.New("Authentication already exist")
  30. ErrAuthenticationNotExist = errors.New("Authentication does not exist")
  31. ErrAuthenticationUserUsed = errors.New("Authentication has been used by some users")
  32. )
  33. var LoginTypes = map[LoginType]string{
  34. LDAP: "LDAP (via BindDN)",
  35. DLDAP: "LDAP (simple auth)",
  36. SMTP: "SMTP",
  37. PAM: "PAM",
  38. }
  39. // Ensure structs implemented interface.
  40. var (
  41. _ core.Conversion = &LDAPConfig{}
  42. _ core.Conversion = &SMTPConfig{}
  43. _ core.Conversion = &PAMConfig{}
  44. )
  45. type LDAPConfig struct {
  46. ldap.Ldapsource
  47. }
  48. func (cfg *LDAPConfig) FromDB(bs []byte) error {
  49. return json.Unmarshal(bs, &cfg.Ldapsource)
  50. }
  51. func (cfg *LDAPConfig) ToDB() ([]byte, error) {
  52. return json.Marshal(cfg.Ldapsource)
  53. }
  54. type SMTPConfig struct {
  55. Auth string
  56. Host string
  57. Port int
  58. TLS bool
  59. SkipVerify bool
  60. }
  61. func (cfg *SMTPConfig) FromDB(bs []byte) error {
  62. return json.Unmarshal(bs, cfg)
  63. }
  64. func (cfg *SMTPConfig) ToDB() ([]byte, error) {
  65. return json.Marshal(cfg)
  66. }
  67. type PAMConfig struct {
  68. ServiceName string // pam service (e.g. system-auth)
  69. }
  70. func (cfg *PAMConfig) FromDB(bs []byte) error {
  71. return json.Unmarshal(bs, &cfg)
  72. }
  73. func (cfg *PAMConfig) ToDB() ([]byte, error) {
  74. return json.Marshal(cfg)
  75. }
  76. type LoginSource struct {
  77. ID int64 `xorm:"pk autoincr"`
  78. Type LoginType
  79. Name string `xorm:"UNIQUE"`
  80. IsActived bool `xorm:"NOT NULL DEFAULT false"`
  81. Cfg core.Conversion `xorm:"TEXT"`
  82. AllowAutoRegister bool `xorm:"NOT NULL DEFAULT false"`
  83. Created time.Time `xorm:"CREATED"`
  84. Updated time.Time `xorm:"UPDATED"`
  85. }
  86. func (source *LoginSource) BeforeSet(colName string, val xorm.Cell) {
  87. switch colName {
  88. case "type":
  89. switch LoginType((*val).(int64)) {
  90. case LDAP:
  91. fallthrough
  92. case DLDAP:
  93. source.Cfg = new(LDAPConfig)
  94. case SMTP:
  95. source.Cfg = new(SMTPConfig)
  96. case PAM:
  97. source.Cfg = new(PAMConfig)
  98. }
  99. }
  100. }
  101. func (source *LoginSource) TypeString() string {
  102. return LoginTypes[source.Type]
  103. }
  104. func (source *LoginSource) LDAP() *LDAPConfig {
  105. return source.Cfg.(*LDAPConfig)
  106. }
  107. func (source *LoginSource) SMTP() *SMTPConfig {
  108. return source.Cfg.(*SMTPConfig)
  109. }
  110. func (source *LoginSource) PAM() *PAMConfig {
  111. return source.Cfg.(*PAMConfig)
  112. }
  113. func CreateSource(source *LoginSource) error {
  114. _, err := x.Insert(source)
  115. return err
  116. }
  117. func GetAuths() ([]*LoginSource, error) {
  118. auths := make([]*LoginSource, 0, 5)
  119. return auths, x.Find(&auths)
  120. }
  121. func GetLoginSourceByID(id int64) (*LoginSource, error) {
  122. source := new(LoginSource)
  123. has, err := x.Id(id).Get(source)
  124. if err != nil {
  125. return nil, err
  126. } else if !has {
  127. return nil, ErrAuthenticationNotExist
  128. }
  129. return source, nil
  130. }
  131. func UpdateSource(source *LoginSource) error {
  132. _, err := x.Id(source.ID).AllCols().Update(source)
  133. return err
  134. }
  135. func DelLoginSource(source *LoginSource) error {
  136. cnt, err := x.Count(&User{LoginSource: source.ID})
  137. if err != nil {
  138. return err
  139. }
  140. if cnt > 0 {
  141. return ErrAuthenticationUserUsed
  142. }
  143. _, err = x.Id(source.ID).Delete(&LoginSource{})
  144. return err
  145. }
  146. // UserSignIn validates user name and password.
  147. func UserSignIn(uname, passwd string) (*User, error) {
  148. var u *User
  149. if strings.Contains(uname, "@") {
  150. u = &User{Email: uname}
  151. } else {
  152. u = &User{LowerName: strings.ToLower(uname)}
  153. }
  154. userExists, err := x.Get(u)
  155. if err != nil {
  156. return nil, err
  157. }
  158. if userExists {
  159. switch u.LoginType {
  160. case NOTYPE:
  161. fallthrough
  162. case PLAIN:
  163. if u.ValidatePassword(passwd) {
  164. return u, nil
  165. }
  166. return nil, ErrUserNotExist{u.Id, u.Name}
  167. default:
  168. var source LoginSource
  169. hasSource, err := x.Id(u.LoginSource).Get(&source)
  170. if err != nil {
  171. return nil, err
  172. } else if !hasSource {
  173. return nil, ErrLoginSourceNotExist
  174. }
  175. return ExternalUserLogin(u, u.LoginName, passwd, &source, false)
  176. }
  177. }
  178. var sources []LoginSource
  179. if err = x.UseBool().Find(&sources, &LoginSource{IsActived: true, AllowAutoRegister: true}); err != nil {
  180. return nil, err
  181. }
  182. for _, source := range sources {
  183. u, err := ExternalUserLogin(nil, uname, passwd, &source, true)
  184. if err == nil {
  185. return u, nil
  186. }
  187. log.Warn("Failed to login '%s' via '%s': %v", uname, source.Name, err)
  188. }
  189. return nil, ErrUserNotExist{u.Id, u.Name}
  190. }
  191. func ExternalUserLogin(u *User, name, passwd string, source *LoginSource, autoRegister bool) (*User, error) {
  192. if !source.IsActived {
  193. return nil, ErrLoginSourceNotActived
  194. }
  195. switch source.Type {
  196. case LDAP:
  197. fallthrough
  198. case DLDAP:
  199. return LoginUserLdapSource(u, name, passwd, source, autoRegister)
  200. case SMTP:
  201. return LoginUserSMTPSource(u, name, passwd, source.ID, source.Cfg.(*SMTPConfig), autoRegister)
  202. case PAM:
  203. return LoginUserPAMSource(u, name, passwd, source.ID, source.Cfg.(*PAMConfig), autoRegister)
  204. }
  205. return nil, ErrUnsupportedLoginType
  206. }
  207. // Query if name/passwd can login against the LDAP directory pool
  208. // Create a local user if success
  209. // Return the same LoginUserPlain semantic
  210. // FIXME: https://github.com/gogits/gogs/issues/672
  211. func LoginUserLdapSource(u *User, name, passwd string, source *LoginSource, autoRegister bool) (*User, error) {
  212. cfg := source.Cfg.(*LDAPConfig)
  213. directBind := (source.Type == DLDAP)
  214. fn, sn, mail, admin, logged := cfg.Ldapsource.SearchEntry(name, passwd, directBind)
  215. if !logged {
  216. // User not in LDAP, do nothing
  217. return nil, ErrUserNotExist{0, name}
  218. }
  219. if !autoRegister {
  220. return u, nil
  221. }
  222. // Fallback.
  223. if len(mail) == 0 {
  224. mail = fmt.Sprintf("%s@localhost", name)
  225. }
  226. u = &User{
  227. LowerName: strings.ToLower(name),
  228. Name: name,
  229. FullName: fn + " " + sn,
  230. LoginType: source.Type,
  231. LoginSource: source.ID,
  232. LoginName: name,
  233. Passwd: passwd,
  234. Email: mail,
  235. IsAdmin: admin,
  236. IsActive: true,
  237. }
  238. return u, CreateUser(u)
  239. }
  240. type loginAuth struct {
  241. username, password string
  242. }
  243. func LoginAuth(username, password string) smtp.Auth {
  244. return &loginAuth{username, password}
  245. }
  246. func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
  247. return "LOGIN", []byte(a.username), nil
  248. }
  249. func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
  250. if more {
  251. switch string(fromServer) {
  252. case "Username:":
  253. return []byte(a.username), nil
  254. case "Password:":
  255. return []byte(a.password), nil
  256. }
  257. }
  258. return nil, nil
  259. }
  260. const (
  261. SMTP_PLAIN = "PLAIN"
  262. SMTP_LOGIN = "LOGIN"
  263. )
  264. var (
  265. SMTPAuths = []string{SMTP_PLAIN, SMTP_LOGIN}
  266. )
  267. func SMTPAuth(a smtp.Auth, cfg *SMTPConfig) error {
  268. c, err := smtp.Dial(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port))
  269. if err != nil {
  270. return err
  271. }
  272. defer c.Close()
  273. if err = c.Hello("gogs"); err != nil {
  274. return err
  275. }
  276. if cfg.TLS {
  277. if ok, _ := c.Extension("STARTTLS"); ok {
  278. if err = c.StartTLS(&tls.Config{
  279. InsecureSkipVerify: cfg.SkipVerify,
  280. ServerName: cfg.Host,
  281. }); err != nil {
  282. return err
  283. }
  284. } else {
  285. return errors.New("SMTP server unsupports TLS")
  286. }
  287. }
  288. if ok, _ := c.Extension("AUTH"); ok {
  289. if err = c.Auth(a); err != nil {
  290. return err
  291. }
  292. return nil
  293. }
  294. return ErrUnsupportedLoginType
  295. }
  296. // Query if name/passwd can login against the LDAP directory pool
  297. // Create a local user if success
  298. // Return the same LoginUserPlain semantic
  299. func LoginUserSMTPSource(u *User, name, passwd string, sourceId int64, cfg *SMTPConfig, autoRegister bool) (*User, error) {
  300. var auth smtp.Auth
  301. if cfg.Auth == SMTP_PLAIN {
  302. auth = smtp.PlainAuth("", name, passwd, cfg.Host)
  303. } else if cfg.Auth == SMTP_LOGIN {
  304. auth = LoginAuth(name, passwd)
  305. } else {
  306. return nil, errors.New("Unsupported SMTP auth type")
  307. }
  308. if err := SMTPAuth(auth, cfg); err != nil {
  309. if strings.Contains(err.Error(), "Username and Password not accepted") {
  310. return nil, ErrUserNotExist{u.Id, u.Name}
  311. }
  312. return nil, err
  313. }
  314. if !autoRegister {
  315. return u, nil
  316. }
  317. var loginName = name
  318. idx := strings.Index(name, "@")
  319. if idx > -1 {
  320. loginName = name[:idx]
  321. }
  322. // fake a local user creation
  323. u = &User{
  324. LowerName: strings.ToLower(loginName),
  325. Name: strings.ToLower(loginName),
  326. LoginType: SMTP,
  327. LoginSource: sourceId,
  328. LoginName: name,
  329. IsActive: true,
  330. Passwd: passwd,
  331. Email: name,
  332. }
  333. err := CreateUser(u)
  334. return u, err
  335. }
  336. // Query if name/passwd can login against PAM
  337. // Create a local user if success
  338. // Return the same LoginUserPlain semantic
  339. func LoginUserPAMSource(u *User, name, passwd string, sourceId int64, cfg *PAMConfig, autoRegister bool) (*User, error) {
  340. if err := pam.PAMAuth(cfg.ServiceName, name, passwd); err != nil {
  341. if strings.Contains(err.Error(), "Authentication failure") {
  342. return nil, ErrUserNotExist{u.Id, u.Name}
  343. }
  344. return nil, err
  345. }
  346. if !autoRegister {
  347. return u, nil
  348. }
  349. // fake a local user creation
  350. u = &User{
  351. LowerName: strings.ToLower(name),
  352. Name: strings.ToLower(name),
  353. LoginType: PAM,
  354. LoginSource: sourceId,
  355. LoginName: name,
  356. IsActive: true,
  357. Passwd: passwd,
  358. Email: name,
  359. }
  360. err := CreateUser(u)
  361. return u, err
  362. }