login.go 10 KB

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