login.go 9.4 KB

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