login.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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. AllowedDomains string `xorm:"TEXT"`
  61. TLS bool
  62. SkipVerify bool
  63. }
  64. func (cfg *SMTPConfig) FromDB(bs []byte) error {
  65. return json.Unmarshal(bs, cfg)
  66. }
  67. func (cfg *SMTPConfig) ToDB() ([]byte, error) {
  68. return json.Marshal(cfg)
  69. }
  70. type PAMConfig struct {
  71. ServiceName string // pam service (e.g. system-auth)
  72. }
  73. func (cfg *PAMConfig) FromDB(bs []byte) error {
  74. return json.Unmarshal(bs, &cfg)
  75. }
  76. func (cfg *PAMConfig) ToDB() ([]byte, error) {
  77. return json.Marshal(cfg)
  78. }
  79. type LoginSource struct {
  80. ID int64 `xorm:"pk autoincr"`
  81. Type LoginType
  82. Name string `xorm:"UNIQUE"`
  83. IsActived bool `xorm:"NOT NULL DEFAULT false"`
  84. Cfg core.Conversion `xorm:"TEXT"`
  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. // .____ ________ _____ __________
  174. // | | \______ \ / _ \\______ \
  175. // | | | | \ / /_\ \| ___/
  176. // | |___ | ` \/ | \ |
  177. // |_______ \/_______ /\____|__ /____|
  178. // \/ \/ \/
  179. // Query if name/passwd can login against the LDAP directory pool
  180. // Create a local user if success
  181. // Return the same LoginUserPlain semantic
  182. // FIXME: https://github.com/gogits/gogs/issues/672
  183. func LoginUserLDAPSource(u *User, name, passwd string, source *LoginSource, autoRegister bool) (*User, error) {
  184. cfg := source.Cfg.(*LDAPConfig)
  185. directBind := (source.Type == DLDAP)
  186. fn, sn, mail, admin, logged := cfg.Ldapsource.SearchEntry(name, passwd, directBind)
  187. if !logged {
  188. // User not in LDAP, do nothing
  189. return nil, ErrUserNotExist{0, name}
  190. }
  191. if !autoRegister {
  192. return u, nil
  193. }
  194. // Fallback.
  195. if len(mail) == 0 {
  196. mail = fmt.Sprintf("%s@localhost", name)
  197. }
  198. u = &User{
  199. LowerName: strings.ToLower(name),
  200. Name: name,
  201. FullName: strings.TrimSpace(fn + " " + sn),
  202. LoginType: source.Type,
  203. LoginSource: source.ID,
  204. LoginName: name,
  205. Email: mail,
  206. IsAdmin: admin,
  207. IsActive: true,
  208. }
  209. return u, CreateUser(u)
  210. }
  211. // _________ __________________________
  212. // / _____/ / \__ ___/\______ \
  213. // \_____ \ / \ / \| | | ___/
  214. // / \/ Y \ | | |
  215. // /_______ /\____|__ /____| |____|
  216. // \/ \/
  217. type loginAuth struct {
  218. username, password string
  219. }
  220. func LoginAuth(username, password string) smtp.Auth {
  221. return &loginAuth{username, password}
  222. }
  223. func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
  224. return "LOGIN", []byte(a.username), nil
  225. }
  226. func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
  227. if more {
  228. switch string(fromServer) {
  229. case "Username:":
  230. return []byte(a.username), nil
  231. case "Password:":
  232. return []byte(a.password), nil
  233. }
  234. }
  235. return nil, nil
  236. }
  237. const (
  238. SMTP_PLAIN = "PLAIN"
  239. SMTP_LOGIN = "LOGIN"
  240. )
  241. var SMTPAuths = []string{SMTP_PLAIN, SMTP_LOGIN}
  242. func SMTPAuth(a smtp.Auth, cfg *SMTPConfig) error {
  243. c, err := smtp.Dial(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port))
  244. if err != nil {
  245. return err
  246. }
  247. defer c.Close()
  248. if err = c.Hello("gogs"); err != nil {
  249. return err
  250. }
  251. if cfg.TLS {
  252. if ok, _ := c.Extension("STARTTLS"); ok {
  253. if err = c.StartTLS(&tls.Config{
  254. InsecureSkipVerify: cfg.SkipVerify,
  255. ServerName: cfg.Host,
  256. }); err != nil {
  257. return err
  258. }
  259. } else {
  260. return errors.New("SMTP server unsupports TLS")
  261. }
  262. }
  263. if ok, _ := c.Extension("AUTH"); ok {
  264. if err = c.Auth(a); err != nil {
  265. return err
  266. }
  267. return nil
  268. }
  269. return ErrUnsupportedLoginType
  270. }
  271. // Query if name/passwd can login against the LDAP directory pool
  272. // Create a local user if success
  273. // Return the same LoginUserPlain semantic
  274. func LoginUserSMTPSource(u *User, name, passwd string, sourceId int64, cfg *SMTPConfig, autoRegister bool) (*User, error) {
  275. // Verify allowed domains.
  276. if len(cfg.AllowedDomains) > 0 {
  277. idx := strings.Index(name, "@")
  278. if idx == -1 {
  279. return nil, ErrUserNotExist{0, name}
  280. } else if !com.IsSliceContainsStr(strings.Split(cfg.AllowedDomains, ","), name[idx+1:]) {
  281. return nil, ErrUserNotExist{0, name}
  282. }
  283. }
  284. var auth smtp.Auth
  285. if cfg.Auth == SMTP_PLAIN {
  286. auth = smtp.PlainAuth("", name, passwd, cfg.Host)
  287. } else if cfg.Auth == SMTP_LOGIN {
  288. auth = LoginAuth(name, passwd)
  289. } else {
  290. return nil, errors.New("Unsupported SMTP auth type")
  291. }
  292. if err := SMTPAuth(auth, cfg); err != nil {
  293. if strings.Contains(err.Error(), "Username and Password not accepted") {
  294. return nil, ErrUserNotExist{0, name}
  295. }
  296. return nil, err
  297. }
  298. if !autoRegister {
  299. return u, nil
  300. }
  301. var loginName = name
  302. idx := strings.Index(name, "@")
  303. if idx > -1 {
  304. loginName = name[:idx]
  305. }
  306. // fake a local user creation
  307. u = &User{
  308. LowerName: strings.ToLower(loginName),
  309. Name: strings.ToLower(loginName),
  310. LoginType: SMTP,
  311. LoginSource: sourceId,
  312. LoginName: name,
  313. IsActive: true,
  314. Passwd: passwd,
  315. Email: name,
  316. }
  317. err := CreateUser(u)
  318. return u, err
  319. }
  320. // __________ _____ _____
  321. // \______ \/ _ \ / \
  322. // | ___/ /_\ \ / \ / \
  323. // | | / | \/ Y \
  324. // |____| \____|__ /\____|__ /
  325. // \/ \/
  326. // Query if name/passwd can login against PAM
  327. // Create a local user if success
  328. // Return the same LoginUserPlain semantic
  329. func LoginUserPAMSource(u *User, name, passwd string, sourceId int64, cfg *PAMConfig, autoRegister bool) (*User, error) {
  330. if err := pam.PAMAuth(cfg.ServiceName, name, passwd); err != nil {
  331. if strings.Contains(err.Error(), "Authentication failure") {
  332. return nil, ErrUserNotExist{u.Id, u.Name}
  333. }
  334. return nil, err
  335. }
  336. if !autoRegister {
  337. return u, nil
  338. }
  339. // fake a local user creation
  340. u = &User{
  341. LowerName: strings.ToLower(name),
  342. Name: strings.ToLower(name),
  343. LoginType: PAM,
  344. LoginSource: sourceId,
  345. LoginName: name,
  346. IsActive: true,
  347. Passwd: passwd,
  348. Email: name,
  349. }
  350. err := CreateUser(u)
  351. return u, err
  352. }
  353. func ExternalUserLogin(u *User, name, passwd string, source *LoginSource, autoRegister bool) (*User, error) {
  354. if !source.IsActived {
  355. return nil, ErrLoginSourceNotActived
  356. }
  357. switch source.Type {
  358. case LDAP, DLDAP:
  359. return LoginUserLDAPSource(u, name, passwd, source, autoRegister)
  360. case SMTP:
  361. return LoginUserSMTPSource(u, name, passwd, source.ID, source.Cfg.(*SMTPConfig), autoRegister)
  362. case PAM:
  363. return LoginUserPAMSource(u, name, passwd, source.ID, source.Cfg.(*PAMConfig), autoRegister)
  364. }
  365. return nil, ErrUnsupportedLoginType
  366. }
  367. // UserSignIn validates user name and password.
  368. func UserSignIn(uname, passwd string) (*User, error) {
  369. var u *User
  370. if strings.Contains(uname, "@") {
  371. u = &User{Email: uname}
  372. } else {
  373. u = &User{LowerName: strings.ToLower(uname)}
  374. }
  375. userExists, err := x.Get(u)
  376. if err != nil {
  377. return nil, err
  378. }
  379. if userExists {
  380. switch u.LoginType {
  381. case NOTYPE, PLAIN:
  382. if u.ValidatePassword(passwd) {
  383. return u, nil
  384. }
  385. return nil, ErrUserNotExist{u.Id, u.Name}
  386. default:
  387. var source LoginSource
  388. hasSource, err := x.Id(u.LoginSource).Get(&source)
  389. if err != nil {
  390. return nil, err
  391. } else if !hasSource {
  392. return nil, ErrLoginSourceNotExist
  393. }
  394. return ExternalUserLogin(u, u.LoginName, passwd, &source, false)
  395. }
  396. }
  397. var sources []LoginSource
  398. if err = x.UseBool().Find(&sources, &LoginSource{IsActived: true}); err != nil {
  399. return nil, err
  400. }
  401. for _, source := range sources {
  402. u, err := ExternalUserLogin(nil, uname, passwd, &source, true)
  403. if err == nil {
  404. return u, nil
  405. }
  406. log.Warn("Failed to login '%s' via '%s': %v", uname, source.Name, err)
  407. }
  408. return nil, ErrUserNotExist{u.Id, u.Name}
  409. }