login.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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. "net/textproto"
  12. "strings"
  13. "time"
  14. "github.com/Unknwon/com"
  15. "github.com/go-macaron/binding"
  16. "github.com/go-xorm/core"
  17. "github.com/go-xorm/xorm"
  18. "github.com/gogits/gogs/modules/auth/ldap"
  19. "github.com/gogits/gogs/modules/auth/pam"
  20. "github.com/gogits/gogs/modules/log"
  21. )
  22. var (
  23. ErrAuthenticationUserUsed = errors.New("Authentication has been used by some users")
  24. )
  25. type LoginType int
  26. // Note: new type must be added at the end of list to maintain compatibility.
  27. const (
  28. LOGIN_NOTYPE LoginType = iota
  29. LOGIN_PLAIN // 1
  30. LOGIN_LDAP // 2
  31. LOGIN_SMTP // 3
  32. LOGIN_PAM // 4
  33. LOGIN_DLDAP // 5
  34. )
  35. var LoginNames = map[LoginType]string{
  36. LOGIN_LDAP: "LDAP (via BindDN)",
  37. LOGIN_DLDAP: "LDAP (simple auth)", // Via direct bind
  38. LOGIN_SMTP: "SMTP",
  39. LOGIN_PAM: "PAM",
  40. }
  41. var SecurityProtocolNames = map[ldap.SecurityProtocol]string{
  42. ldap.SECURITY_PROTOCOL_UNENCRYPTED: "Unencrypted",
  43. ldap.SECURITY_PROTOCOL_LDAPS: "LDAPS",
  44. ldap.SECURITY_PROTOCOL_START_TLS: "StartTLS",
  45. }
  46. // Ensure structs implemented interface.
  47. var (
  48. _ core.Conversion = &LDAPConfig{}
  49. _ core.Conversion = &SMTPConfig{}
  50. _ core.Conversion = &PAMConfig{}
  51. )
  52. type LDAPConfig struct {
  53. *ldap.Source
  54. }
  55. func (cfg *LDAPConfig) FromDB(bs []byte) error {
  56. return json.Unmarshal(bs, &cfg)
  57. }
  58. func (cfg *LDAPConfig) ToDB() ([]byte, error) {
  59. return json.Marshal(cfg)
  60. }
  61. func (cfg *LDAPConfig) SecurityProtocolName() string {
  62. return SecurityProtocolNames[cfg.SecurityProtocol]
  63. }
  64. type SMTPConfig struct {
  65. Auth string
  66. Host string
  67. Port int
  68. AllowedDomains string `xorm:"TEXT"`
  69. TLS bool
  70. SkipVerify bool
  71. }
  72. func (cfg *SMTPConfig) FromDB(bs []byte) error {
  73. return json.Unmarshal(bs, cfg)
  74. }
  75. func (cfg *SMTPConfig) ToDB() ([]byte, error) {
  76. return json.Marshal(cfg)
  77. }
  78. type PAMConfig struct {
  79. ServiceName string // pam service (e.g. system-auth)
  80. }
  81. func (cfg *PAMConfig) FromDB(bs []byte) error {
  82. return json.Unmarshal(bs, &cfg)
  83. }
  84. func (cfg *PAMConfig) ToDB() ([]byte, error) {
  85. return json.Marshal(cfg)
  86. }
  87. type LoginSource struct {
  88. ID int64 `xorm:"pk autoincr"`
  89. Type LoginType
  90. Name string `xorm:"UNIQUE"`
  91. IsActived bool `xorm:"NOT NULL DEFAULT false"`
  92. Cfg core.Conversion `xorm:"TEXT"`
  93. Created time.Time `xorm:"-"`
  94. CreatedUnix int64
  95. Updated time.Time `xorm:"-"`
  96. UpdatedUnix int64
  97. }
  98. func (s *LoginSource) BeforeInsert() {
  99. s.CreatedUnix = time.Now().Unix()
  100. s.UpdatedUnix = s.CreatedUnix
  101. }
  102. func (s *LoginSource) BeforeUpdate() {
  103. s.UpdatedUnix = time.Now().Unix()
  104. }
  105. // Cell2Int64 converts a xorm.Cell type to int64,
  106. // and handles possible irregular cases.
  107. func Cell2Int64(val xorm.Cell) int64 {
  108. switch (*val).(type) {
  109. case []uint8:
  110. log.Trace("Cell2Int64 ([]uint8): %v", *val)
  111. return com.StrTo(string((*val).([]uint8))).MustInt64()
  112. }
  113. return (*val).(int64)
  114. }
  115. func (source *LoginSource) BeforeSet(colName string, val xorm.Cell) {
  116. switch colName {
  117. case "type":
  118. switch LoginType(Cell2Int64(val)) {
  119. case LOGIN_LDAP, LOGIN_DLDAP:
  120. source.Cfg = new(LDAPConfig)
  121. case LOGIN_SMTP:
  122. source.Cfg = new(SMTPConfig)
  123. case LOGIN_PAM:
  124. source.Cfg = new(PAMConfig)
  125. default:
  126. panic("unrecognized login source type: " + com.ToStr(*val))
  127. }
  128. }
  129. }
  130. func (s *LoginSource) AfterSet(colName string, _ xorm.Cell) {
  131. switch colName {
  132. case "created_unix":
  133. s.Created = time.Unix(s.CreatedUnix, 0).Local()
  134. case "updated_unix":
  135. s.Updated = time.Unix(s.UpdatedUnix, 0).Local()
  136. }
  137. }
  138. func (source *LoginSource) TypeName() string {
  139. return LoginNames[source.Type]
  140. }
  141. func (source *LoginSource) IsLDAP() bool {
  142. return source.Type == LOGIN_LDAP
  143. }
  144. func (source *LoginSource) IsDLDAP() bool {
  145. return source.Type == LOGIN_DLDAP
  146. }
  147. func (source *LoginSource) IsSMTP() bool {
  148. return source.Type == LOGIN_SMTP
  149. }
  150. func (source *LoginSource) IsPAM() bool {
  151. return source.Type == LOGIN_PAM
  152. }
  153. func (source *LoginSource) HasTLS() bool {
  154. return ((source.IsLDAP() || source.IsDLDAP()) &&
  155. source.LDAP().SecurityProtocol > ldap.SECURITY_PROTOCOL_UNENCRYPTED) ||
  156. source.IsSMTP()
  157. }
  158. func (source *LoginSource) UseTLS() bool {
  159. switch source.Type {
  160. case LOGIN_LDAP, LOGIN_DLDAP:
  161. return source.LDAP().SecurityProtocol != ldap.SECURITY_PROTOCOL_UNENCRYPTED
  162. case LOGIN_SMTP:
  163. return source.SMTP().TLS
  164. }
  165. return false
  166. }
  167. func (source *LoginSource) SkipVerify() bool {
  168. switch source.Type {
  169. case LOGIN_LDAP, LOGIN_DLDAP:
  170. return source.LDAP().SkipVerify
  171. case LOGIN_SMTP:
  172. return source.SMTP().SkipVerify
  173. }
  174. return false
  175. }
  176. func (source *LoginSource) LDAP() *LDAPConfig {
  177. return source.Cfg.(*LDAPConfig)
  178. }
  179. func (source *LoginSource) SMTP() *SMTPConfig {
  180. return source.Cfg.(*SMTPConfig)
  181. }
  182. func (source *LoginSource) PAM() *PAMConfig {
  183. return source.Cfg.(*PAMConfig)
  184. }
  185. // CountLoginSources returns number of login sources.
  186. func CountLoginSources() int64 {
  187. count, _ := x.Count(new(LoginSource))
  188. return count
  189. }
  190. func CreateLoginSource(source *LoginSource) error {
  191. has, err := x.Get(&LoginSource{Name: source.Name})
  192. if err != nil {
  193. return err
  194. } else if has {
  195. return ErrLoginSourceAlreadyExist{source.Name}
  196. }
  197. _, err = x.Insert(source)
  198. return err
  199. }
  200. func LoginSources() ([]*LoginSource, error) {
  201. auths := make([]*LoginSource, 0, 5)
  202. return auths, x.Find(&auths)
  203. }
  204. // GetLoginSourceByID returns login source by given ID.
  205. func GetLoginSourceByID(id int64) (*LoginSource, error) {
  206. source := new(LoginSource)
  207. has, err := x.Id(id).Get(source)
  208. if err != nil {
  209. return nil, err
  210. } else if !has {
  211. return nil, ErrLoginSourceNotExist{id}
  212. }
  213. return source, nil
  214. }
  215. func UpdateSource(source *LoginSource) error {
  216. _, err := x.Id(source.ID).AllCols().Update(source)
  217. return err
  218. }
  219. func DeleteSource(source *LoginSource) error {
  220. count, err := x.Count(&User{LoginSource: source.ID})
  221. if err != nil {
  222. return err
  223. } else if count > 0 {
  224. return ErrAuthenticationUserUsed
  225. }
  226. _, err = x.Id(source.ID).Delete(new(LoginSource))
  227. return err
  228. }
  229. // .____ ________ _____ __________
  230. // | | \______ \ / _ \\______ \
  231. // | | | | \ / /_\ \| ___/
  232. // | |___ | ` \/ | \ |
  233. // |_______ \/_______ /\____|__ /____|
  234. // \/ \/ \/
  235. // LoginUserLDAPSource queries if loginName/passwd can login against the LDAP directory pool,
  236. // and create a local user if success when enabled.
  237. // It returns the same LoginUserPlain semantic.
  238. func LoginUserLDAPSource(u *User, loginName, passwd string, source *LoginSource, autoRegister bool) (*User, error) {
  239. cfg := source.Cfg.(*LDAPConfig)
  240. directBind := (source.Type == LOGIN_DLDAP)
  241. username, fn, sn, mail, isAdmin, logged := cfg.SearchEntry(loginName, passwd, directBind)
  242. if !logged {
  243. // User not in LDAP, do nothing
  244. return nil, ErrUserNotExist{0, loginName}
  245. }
  246. if !autoRegister {
  247. return u, nil
  248. }
  249. // Fallback.
  250. if len(username) == 0 {
  251. username = loginName
  252. }
  253. // Validate username make sure it satisfies requirement.
  254. if binding.AlphaDashDotPattern.MatchString(username) {
  255. return nil, fmt.Errorf("Invalid pattern for attribute 'username' [%s]: must be valid alpha or numeric or dash(-_) or dot characters", username)
  256. }
  257. if len(mail) == 0 {
  258. mail = fmt.Sprintf("%s@localhost", username)
  259. }
  260. u = &User{
  261. LowerName: strings.ToLower(username),
  262. Name: username,
  263. FullName: composeFullName(fn, sn, username),
  264. LoginType: source.Type,
  265. LoginSource: source.ID,
  266. LoginName: loginName,
  267. Email: mail,
  268. IsAdmin: isAdmin,
  269. IsActive: true,
  270. }
  271. return u, CreateUser(u)
  272. }
  273. func composeFullName(firstname, surname, username string) string {
  274. switch {
  275. case len(firstname) == 0 && len(surname) == 0:
  276. return username
  277. case len(firstname) == 0:
  278. return surname
  279. case len(surname) == 0:
  280. return firstname
  281. default:
  282. return firstname + " " + surname
  283. }
  284. }
  285. // _________ __________________________
  286. // / _____/ / \__ ___/\______ \
  287. // \_____ \ / \ / \| | | ___/
  288. // / \/ Y \ | | |
  289. // /_______ /\____|__ /____| |____|
  290. // \/ \/
  291. type loginAuth struct {
  292. username, password string
  293. }
  294. func LoginAuth(username, password string) smtp.Auth {
  295. return &loginAuth{username, password}
  296. }
  297. func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
  298. return "LOGIN", []byte(a.username), nil
  299. }
  300. func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
  301. if more {
  302. switch string(fromServer) {
  303. case "Username:":
  304. return []byte(a.username), nil
  305. case "Password:":
  306. return []byte(a.password), nil
  307. }
  308. }
  309. return nil, nil
  310. }
  311. const (
  312. SMTP_PLAIN = "PLAIN"
  313. SMTP_LOGIN = "LOGIN"
  314. )
  315. var SMTPAuths = []string{SMTP_PLAIN, SMTP_LOGIN}
  316. func SMTPAuth(a smtp.Auth, cfg *SMTPConfig) error {
  317. c, err := smtp.Dial(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port))
  318. if err != nil {
  319. return err
  320. }
  321. defer c.Close()
  322. if err = c.Hello("gogs"); err != nil {
  323. return err
  324. }
  325. if cfg.TLS {
  326. if ok, _ := c.Extension("STARTTLS"); ok {
  327. if err = c.StartTLS(&tls.Config{
  328. InsecureSkipVerify: cfg.SkipVerify,
  329. ServerName: cfg.Host,
  330. }); err != nil {
  331. return err
  332. }
  333. } else {
  334. return errors.New("SMTP server unsupports TLS")
  335. }
  336. }
  337. if ok, _ := c.Extension("AUTH"); ok {
  338. if err = c.Auth(a); err != nil {
  339. return err
  340. }
  341. return nil
  342. }
  343. return ErrUnsupportedLoginType
  344. }
  345. // Query if name/passwd can login against the LDAP directory pool
  346. // Create a local user if success
  347. // Return the same LoginUserPlain semantic
  348. func LoginUserSMTPSource(u *User, name, passwd string, sourceID int64, cfg *SMTPConfig, autoRegister bool) (*User, error) {
  349. // Verify allowed domains.
  350. if len(cfg.AllowedDomains) > 0 {
  351. idx := strings.Index(name, "@")
  352. if idx == -1 {
  353. return nil, ErrUserNotExist{0, name}
  354. } else if !com.IsSliceContainsStr(strings.Split(cfg.AllowedDomains, ","), name[idx+1:]) {
  355. return nil, ErrUserNotExist{0, name}
  356. }
  357. }
  358. var auth smtp.Auth
  359. if cfg.Auth == SMTP_PLAIN {
  360. auth = smtp.PlainAuth("", name, passwd, cfg.Host)
  361. } else if cfg.Auth == SMTP_LOGIN {
  362. auth = LoginAuth(name, passwd)
  363. } else {
  364. return nil, errors.New("Unsupported SMTP auth type")
  365. }
  366. if err := SMTPAuth(auth, cfg); err != nil {
  367. // Check standard error format first,
  368. // then fallback to worse case.
  369. tperr, ok := err.(*textproto.Error)
  370. if (ok && tperr.Code == 535) ||
  371. strings.Contains(err.Error(), "Username and Password not accepted") {
  372. return nil, ErrUserNotExist{0, name}
  373. }
  374. return nil, err
  375. }
  376. if !autoRegister {
  377. return u, nil
  378. }
  379. var loginName = name
  380. idx := strings.Index(name, "@")
  381. if idx > -1 {
  382. loginName = name[:idx]
  383. }
  384. // fake a local user creation
  385. u = &User{
  386. LowerName: strings.ToLower(loginName),
  387. Name: strings.ToLower(loginName),
  388. LoginType: LOGIN_SMTP,
  389. LoginSource: sourceID,
  390. LoginName: name,
  391. IsActive: true,
  392. Passwd: passwd,
  393. Email: name,
  394. }
  395. err := CreateUser(u)
  396. return u, err
  397. }
  398. // __________ _____ _____
  399. // \______ \/ _ \ / \
  400. // | ___/ /_\ \ / \ / \
  401. // | | / | \/ Y \
  402. // |____| \____|__ /\____|__ /
  403. // \/ \/
  404. // Query if name/passwd can login against PAM
  405. // Create a local user if success
  406. // Return the same LoginUserPlain semantic
  407. func LoginUserPAMSource(u *User, name, passwd string, sourceID int64, cfg *PAMConfig, autoRegister bool) (*User, error) {
  408. if err := pam.PAMAuth(cfg.ServiceName, name, passwd); err != nil {
  409. if strings.Contains(err.Error(), "Authentication failure") {
  410. return nil, ErrUserNotExist{0, name}
  411. }
  412. return nil, err
  413. }
  414. if !autoRegister {
  415. return u, nil
  416. }
  417. // fake a local user creation
  418. u = &User{
  419. LowerName: strings.ToLower(name),
  420. Name: name,
  421. LoginType: LOGIN_PAM,
  422. LoginSource: sourceID,
  423. LoginName: name,
  424. IsActive: true,
  425. Passwd: passwd,
  426. Email: name,
  427. }
  428. return u, CreateUser(u)
  429. }
  430. func ExternalUserLogin(u *User, name, passwd string, source *LoginSource, autoRegister bool) (*User, error) {
  431. if !source.IsActived {
  432. return nil, ErrLoginSourceNotActived
  433. }
  434. switch source.Type {
  435. case LOGIN_LDAP, LOGIN_DLDAP:
  436. return LoginUserLDAPSource(u, name, passwd, source, autoRegister)
  437. case LOGIN_SMTP:
  438. return LoginUserSMTPSource(u, name, passwd, source.ID, source.Cfg.(*SMTPConfig), autoRegister)
  439. case LOGIN_PAM:
  440. return LoginUserPAMSource(u, name, passwd, source.ID, source.Cfg.(*PAMConfig), autoRegister)
  441. }
  442. return nil, ErrUnsupportedLoginType
  443. }
  444. // UserSignIn validates user name and password.
  445. func UserSignIn(uname, passwd string) (*User, error) {
  446. var u *User
  447. if strings.Contains(uname, "@") {
  448. u = &User{Email: strings.ToLower(uname)}
  449. } else {
  450. u = &User{LowerName: strings.ToLower(uname)}
  451. }
  452. userExists, err := x.Get(u)
  453. if err != nil {
  454. return nil, err
  455. }
  456. if userExists {
  457. switch u.LoginType {
  458. case LOGIN_NOTYPE, LOGIN_PLAIN:
  459. if u.ValidatePassword(passwd) {
  460. return u, nil
  461. }
  462. return nil, ErrUserNotExist{u.ID, u.Name}
  463. default:
  464. var source LoginSource
  465. hasSource, err := x.Id(u.LoginSource).Get(&source)
  466. if err != nil {
  467. return nil, err
  468. } else if !hasSource {
  469. return nil, ErrLoginSourceNotExist{u.LoginSource}
  470. }
  471. return ExternalUserLogin(u, u.LoginName, passwd, &source, false)
  472. }
  473. }
  474. var sources []LoginSource
  475. if err = x.UseBool().Find(&sources, &LoginSource{IsActived: true}); err != nil {
  476. return nil, err
  477. }
  478. for _, source := range sources {
  479. u, err := ExternalUserLogin(nil, uname, passwd, &source, true)
  480. if err == nil {
  481. return u, nil
  482. }
  483. log.Warn("Failed to login '%s' via '%s': %v", uname, source.Name, err)
  484. }
  485. return nil, ErrUserNotExist{u.ID, u.Name}
  486. }