login.go 9.6 KB

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