You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

login_source.go 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "crypto/tls"
  8. "encoding/json"
  9. "errors"
  10. "fmt"
  11. "net/smtp"
  12. "net/textproto"
  13. "strings"
  14. "code.gitea.io/gitea/modules/auth/ldap"
  15. "code.gitea.io/gitea/modules/auth/oauth2"
  16. "code.gitea.io/gitea/modules/auth/pam"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/setting"
  19. "code.gitea.io/gitea/modules/timeutil"
  20. "github.com/unknwon/com"
  21. "xorm.io/core"
  22. "xorm.io/xorm"
  23. )
  24. // LoginType represents an login type.
  25. type LoginType int
  26. // Note: new type must append to the end of list to maintain compatibility.
  27. const (
  28. LoginNoType LoginType = iota
  29. LoginPlain // 1
  30. LoginLDAP // 2
  31. LoginSMTP // 3
  32. LoginPAM // 4
  33. LoginDLDAP // 5
  34. LoginOAuth2 // 6
  35. LoginSSPI // 7
  36. )
  37. // LoginNames contains the name of LoginType values.
  38. var LoginNames = map[LoginType]string{
  39. LoginLDAP: "LDAP (via BindDN)",
  40. LoginDLDAP: "LDAP (simple auth)", // Via direct bind
  41. LoginSMTP: "SMTP",
  42. LoginPAM: "PAM",
  43. LoginOAuth2: "OAuth2",
  44. LoginSSPI: "SPNEGO with SSPI",
  45. }
  46. // SecurityProtocolNames contains the name of SecurityProtocol values.
  47. var SecurityProtocolNames = map[ldap.SecurityProtocol]string{
  48. ldap.SecurityProtocolUnencrypted: "Unencrypted",
  49. ldap.SecurityProtocolLDAPS: "LDAPS",
  50. ldap.SecurityProtocolStartTLS: "StartTLS",
  51. }
  52. // Ensure structs implemented interface.
  53. var (
  54. _ core.Conversion = &LDAPConfig{}
  55. _ core.Conversion = &SMTPConfig{}
  56. _ core.Conversion = &PAMConfig{}
  57. _ core.Conversion = &OAuth2Config{}
  58. _ core.Conversion = &SSPIConfig{}
  59. )
  60. // LDAPConfig holds configuration for LDAP login source.
  61. type LDAPConfig struct {
  62. *ldap.Source
  63. }
  64. // FromDB fills up a LDAPConfig from serialized format.
  65. func (cfg *LDAPConfig) FromDB(bs []byte) error {
  66. return json.Unmarshal(bs, &cfg)
  67. }
  68. // ToDB exports a LDAPConfig to a serialized format.
  69. func (cfg *LDAPConfig) ToDB() ([]byte, error) {
  70. return json.Marshal(cfg)
  71. }
  72. // SecurityProtocolName returns the name of configured security
  73. // protocol.
  74. func (cfg *LDAPConfig) SecurityProtocolName() string {
  75. return SecurityProtocolNames[cfg.SecurityProtocol]
  76. }
  77. // SMTPConfig holds configuration for the SMTP login source.
  78. type SMTPConfig struct {
  79. Auth string
  80. Host string
  81. Port int
  82. AllowedDomains string `xorm:"TEXT"`
  83. TLS bool
  84. SkipVerify bool
  85. }
  86. // FromDB fills up an SMTPConfig from serialized format.
  87. func (cfg *SMTPConfig) FromDB(bs []byte) error {
  88. return json.Unmarshal(bs, cfg)
  89. }
  90. // ToDB exports an SMTPConfig to a serialized format.
  91. func (cfg *SMTPConfig) ToDB() ([]byte, error) {
  92. return json.Marshal(cfg)
  93. }
  94. // PAMConfig holds configuration for the PAM login source.
  95. type PAMConfig struct {
  96. ServiceName string // pam service (e.g. system-auth)
  97. }
  98. // FromDB fills up a PAMConfig from serialized format.
  99. func (cfg *PAMConfig) FromDB(bs []byte) error {
  100. return json.Unmarshal(bs, &cfg)
  101. }
  102. // ToDB exports a PAMConfig to a serialized format.
  103. func (cfg *PAMConfig) ToDB() ([]byte, error) {
  104. return json.Marshal(cfg)
  105. }
  106. // OAuth2Config holds configuration for the OAuth2 login source.
  107. type OAuth2Config struct {
  108. Provider string
  109. ClientID string
  110. ClientSecret string
  111. OpenIDConnectAutoDiscoveryURL string
  112. CustomURLMapping *oauth2.CustomURLMapping
  113. }
  114. // FromDB fills up an OAuth2Config from serialized format.
  115. func (cfg *OAuth2Config) FromDB(bs []byte) error {
  116. return json.Unmarshal(bs, cfg)
  117. }
  118. // ToDB exports an SMTPConfig to a serialized format.
  119. func (cfg *OAuth2Config) ToDB() ([]byte, error) {
  120. return json.Marshal(cfg)
  121. }
  122. // SSPIConfig holds configuration for SSPI single sign-on.
  123. type SSPIConfig struct {
  124. AutoCreateUsers bool
  125. AutoActivateUsers bool
  126. StripDomainNames bool
  127. SeparatorReplacement string
  128. DefaultLanguage string
  129. }
  130. // FromDB fills up an SSPIConfig from serialized format.
  131. func (cfg *SSPIConfig) FromDB(bs []byte) error {
  132. return json.Unmarshal(bs, cfg)
  133. }
  134. // ToDB exports an SSPIConfig to a serialized format.
  135. func (cfg *SSPIConfig) ToDB() ([]byte, error) {
  136. return json.Marshal(cfg)
  137. }
  138. // LoginSource represents an external way for authorizing users.
  139. type LoginSource struct {
  140. ID int64 `xorm:"pk autoincr"`
  141. Type LoginType
  142. Name string `xorm:"UNIQUE"`
  143. IsActived bool `xorm:"INDEX NOT NULL DEFAULT false"`
  144. IsSyncEnabled bool `xorm:"INDEX NOT NULL DEFAULT false"`
  145. Cfg core.Conversion `xorm:"TEXT"`
  146. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  147. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  148. }
  149. // Cell2Int64 converts a xorm.Cell type to int64,
  150. // and handles possible irregular cases.
  151. func Cell2Int64(val xorm.Cell) int64 {
  152. switch (*val).(type) {
  153. case []uint8:
  154. log.Trace("Cell2Int64 ([]uint8): %v", *val)
  155. return com.StrTo(string((*val).([]uint8))).MustInt64()
  156. }
  157. return (*val).(int64)
  158. }
  159. // BeforeSet is invoked from XORM before setting the value of a field of this object.
  160. func (source *LoginSource) BeforeSet(colName string, val xorm.Cell) {
  161. if colName == "type" {
  162. switch LoginType(Cell2Int64(val)) {
  163. case LoginLDAP, LoginDLDAP:
  164. source.Cfg = new(LDAPConfig)
  165. case LoginSMTP:
  166. source.Cfg = new(SMTPConfig)
  167. case LoginPAM:
  168. source.Cfg = new(PAMConfig)
  169. case LoginOAuth2:
  170. source.Cfg = new(OAuth2Config)
  171. case LoginSSPI:
  172. source.Cfg = new(SSPIConfig)
  173. default:
  174. panic("unrecognized login source type: " + com.ToStr(*val))
  175. }
  176. }
  177. }
  178. // TypeName return name of this login source type.
  179. func (source *LoginSource) TypeName() string {
  180. return LoginNames[source.Type]
  181. }
  182. // IsLDAP returns true of this source is of the LDAP type.
  183. func (source *LoginSource) IsLDAP() bool {
  184. return source.Type == LoginLDAP
  185. }
  186. // IsDLDAP returns true of this source is of the DLDAP type.
  187. func (source *LoginSource) IsDLDAP() bool {
  188. return source.Type == LoginDLDAP
  189. }
  190. // IsSMTP returns true of this source is of the SMTP type.
  191. func (source *LoginSource) IsSMTP() bool {
  192. return source.Type == LoginSMTP
  193. }
  194. // IsPAM returns true of this source is of the PAM type.
  195. func (source *LoginSource) IsPAM() bool {
  196. return source.Type == LoginPAM
  197. }
  198. // IsOAuth2 returns true of this source is of the OAuth2 type.
  199. func (source *LoginSource) IsOAuth2() bool {
  200. return source.Type == LoginOAuth2
  201. }
  202. // IsSSPI returns true of this source is of the SSPI type.
  203. func (source *LoginSource) IsSSPI() bool {
  204. return source.Type == LoginSSPI
  205. }
  206. // HasTLS returns true of this source supports TLS.
  207. func (source *LoginSource) HasTLS() bool {
  208. return ((source.IsLDAP() || source.IsDLDAP()) &&
  209. source.LDAP().SecurityProtocol > ldap.SecurityProtocolUnencrypted) ||
  210. source.IsSMTP()
  211. }
  212. // UseTLS returns true of this source is configured to use TLS.
  213. func (source *LoginSource) UseTLS() bool {
  214. switch source.Type {
  215. case LoginLDAP, LoginDLDAP:
  216. return source.LDAP().SecurityProtocol != ldap.SecurityProtocolUnencrypted
  217. case LoginSMTP:
  218. return source.SMTP().TLS
  219. }
  220. return false
  221. }
  222. // SkipVerify returns true if this source is configured to skip SSL
  223. // verification.
  224. func (source *LoginSource) SkipVerify() bool {
  225. switch source.Type {
  226. case LoginLDAP, LoginDLDAP:
  227. return source.LDAP().SkipVerify
  228. case LoginSMTP:
  229. return source.SMTP().SkipVerify
  230. }
  231. return false
  232. }
  233. // LDAP returns LDAPConfig for this source, if of LDAP type.
  234. func (source *LoginSource) LDAP() *LDAPConfig {
  235. return source.Cfg.(*LDAPConfig)
  236. }
  237. // SMTP returns SMTPConfig for this source, if of SMTP type.
  238. func (source *LoginSource) SMTP() *SMTPConfig {
  239. return source.Cfg.(*SMTPConfig)
  240. }
  241. // PAM returns PAMConfig for this source, if of PAM type.
  242. func (source *LoginSource) PAM() *PAMConfig {
  243. return source.Cfg.(*PAMConfig)
  244. }
  245. // OAuth2 returns OAuth2Config for this source, if of OAuth2 type.
  246. func (source *LoginSource) OAuth2() *OAuth2Config {
  247. return source.Cfg.(*OAuth2Config)
  248. }
  249. // SSPI returns SSPIConfig for this source, if of SSPI type.
  250. func (source *LoginSource) SSPI() *SSPIConfig {
  251. return source.Cfg.(*SSPIConfig)
  252. }
  253. // CreateLoginSource inserts a LoginSource in the DB if not already
  254. // existing with the given name.
  255. func CreateLoginSource(source *LoginSource) error {
  256. has, err := x.Where("name=?", source.Name).Exist(new(LoginSource))
  257. if err != nil {
  258. return err
  259. } else if has {
  260. return ErrLoginSourceAlreadyExist{source.Name}
  261. }
  262. // Synchronization is only aviable with LDAP for now
  263. if !source.IsLDAP() {
  264. source.IsSyncEnabled = false
  265. }
  266. _, err = x.Insert(source)
  267. if err == nil && source.IsOAuth2() && source.IsActived {
  268. oAuth2Config := source.OAuth2()
  269. err = oauth2.RegisterProvider(source.Name, oAuth2Config.Provider, oAuth2Config.ClientID, oAuth2Config.ClientSecret, oAuth2Config.OpenIDConnectAutoDiscoveryURL, oAuth2Config.CustomURLMapping)
  270. err = wrapOpenIDConnectInitializeError(err, source.Name, oAuth2Config)
  271. if err != nil {
  272. // remove the LoginSource in case of errors while registering OAuth2 providers
  273. if _, err := x.Delete(source); err != nil {
  274. log.Error("CreateLoginSource: Error while wrapOpenIDConnectInitializeError: %v", err)
  275. }
  276. return err
  277. }
  278. }
  279. return err
  280. }
  281. // LoginSources returns a slice of all login sources found in DB.
  282. func LoginSources() ([]*LoginSource, error) {
  283. auths := make([]*LoginSource, 0, 6)
  284. return auths, x.Find(&auths)
  285. }
  286. // LoginSourcesByType returns all sources of the specified type
  287. func LoginSourcesByType(loginType LoginType) ([]*LoginSource, error) {
  288. sources := make([]*LoginSource, 0, 1)
  289. if err := x.Where("type = ?", loginType).Find(&sources); err != nil {
  290. return nil, err
  291. }
  292. return sources, nil
  293. }
  294. // ActiveLoginSources returns all active sources of the specified type
  295. func ActiveLoginSources(loginType LoginType) ([]*LoginSource, error) {
  296. sources := make([]*LoginSource, 0, 1)
  297. if err := x.Where("is_actived = ? and type = ?", true, loginType).Find(&sources); err != nil {
  298. return nil, err
  299. }
  300. return sources, nil
  301. }
  302. // IsSSPIEnabled returns true if there is at least one activated login
  303. // source of type LoginSSPI
  304. func IsSSPIEnabled() bool {
  305. if !HasEngine {
  306. return false
  307. }
  308. sources, err := ActiveLoginSources(LoginSSPI)
  309. if err != nil {
  310. log.Error("ActiveLoginSources: %v", err)
  311. return false
  312. }
  313. return len(sources) > 0
  314. }
  315. // GetLoginSourceByID returns login source by given ID.
  316. func GetLoginSourceByID(id int64) (*LoginSource, error) {
  317. source := new(LoginSource)
  318. has, err := x.ID(id).Get(source)
  319. if err != nil {
  320. return nil, err
  321. } else if !has {
  322. return nil, ErrLoginSourceNotExist{id}
  323. }
  324. return source, nil
  325. }
  326. // UpdateSource updates a LoginSource record in DB.
  327. func UpdateSource(source *LoginSource) error {
  328. var originalLoginSource *LoginSource
  329. if source.IsOAuth2() {
  330. // keep track of the original values so we can restore in case of errors while registering OAuth2 providers
  331. var err error
  332. if originalLoginSource, err = GetLoginSourceByID(source.ID); err != nil {
  333. return err
  334. }
  335. }
  336. _, err := x.ID(source.ID).AllCols().Update(source)
  337. if err == nil && source.IsOAuth2() && source.IsActived {
  338. oAuth2Config := source.OAuth2()
  339. err = oauth2.RegisterProvider(source.Name, oAuth2Config.Provider, oAuth2Config.ClientID, oAuth2Config.ClientSecret, oAuth2Config.OpenIDConnectAutoDiscoveryURL, oAuth2Config.CustomURLMapping)
  340. err = wrapOpenIDConnectInitializeError(err, source.Name, oAuth2Config)
  341. if err != nil {
  342. // restore original values since we cannot update the provider it self
  343. if _, err := x.ID(source.ID).AllCols().Update(originalLoginSource); err != nil {
  344. log.Error("UpdateSource: Error while wrapOpenIDConnectInitializeError: %v", err)
  345. }
  346. return err
  347. }
  348. }
  349. return err
  350. }
  351. // DeleteSource deletes a LoginSource record in DB.
  352. func DeleteSource(source *LoginSource) error {
  353. count, err := x.Count(&User{LoginSource: source.ID})
  354. if err != nil {
  355. return err
  356. } else if count > 0 {
  357. return ErrLoginSourceInUse{source.ID}
  358. }
  359. count, err = x.Count(&ExternalLoginUser{LoginSourceID: source.ID})
  360. if err != nil {
  361. return err
  362. } else if count > 0 {
  363. return ErrLoginSourceInUse{source.ID}
  364. }
  365. if source.IsOAuth2() {
  366. oauth2.RemoveProvider(source.Name)
  367. }
  368. _, err = x.ID(source.ID).Delete(new(LoginSource))
  369. return err
  370. }
  371. // CountLoginSources returns number of login sources.
  372. func CountLoginSources() int64 {
  373. count, _ := x.Count(new(LoginSource))
  374. return count
  375. }
  376. // .____ ________ _____ __________
  377. // | | \______ \ / _ \\______ \
  378. // | | | | \ / /_\ \| ___/
  379. // | |___ | ` \/ | \ |
  380. // |_______ \/_______ /\____|__ /____|
  381. // \/ \/ \/
  382. func composeFullName(firstname, surname, username string) string {
  383. switch {
  384. case len(firstname) == 0 && len(surname) == 0:
  385. return username
  386. case len(firstname) == 0:
  387. return surname
  388. case len(surname) == 0:
  389. return firstname
  390. default:
  391. return firstname + " " + surname
  392. }
  393. }
  394. // LoginViaLDAP queries if login/password is valid against the LDAP directory pool,
  395. // and create a local user if success when enabled.
  396. func LoginViaLDAP(user *User, login, password string, source *LoginSource) (*User, error) {
  397. sr := source.Cfg.(*LDAPConfig).SearchEntry(login, password, source.Type == LoginDLDAP)
  398. if sr == nil {
  399. // User not in LDAP, do nothing
  400. return nil, ErrUserNotExist{0, login, 0}
  401. }
  402. var isAttributeSSHPublicKeySet = len(strings.TrimSpace(source.LDAP().AttributeSSHPublicKey)) > 0
  403. // Update User admin flag if exist
  404. if isExist, err := IsUserExist(0, sr.Username); err != nil {
  405. return nil, err
  406. } else if isExist {
  407. if user == nil {
  408. user, err = GetUserByName(sr.Username)
  409. if err != nil {
  410. return nil, err
  411. }
  412. }
  413. if user != nil &&
  414. !user.ProhibitLogin && len(source.LDAP().AdminFilter) > 0 && user.IsAdmin != sr.IsAdmin {
  415. // Change existing admin flag only if AdminFilter option is set
  416. user.IsAdmin = sr.IsAdmin
  417. err = UpdateUserCols(user, "is_admin")
  418. if err != nil {
  419. return nil, err
  420. }
  421. }
  422. }
  423. if user != nil {
  424. if isAttributeSSHPublicKeySet && synchronizeLdapSSHPublicKeys(user, source, sr.SSHPublicKey) {
  425. return user, RewriteAllPublicKeys()
  426. }
  427. return user, nil
  428. }
  429. // Fallback.
  430. if len(sr.Username) == 0 {
  431. sr.Username = login
  432. }
  433. if len(sr.Mail) == 0 {
  434. sr.Mail = fmt.Sprintf("%s@localhost", sr.Username)
  435. }
  436. user = &User{
  437. LowerName: strings.ToLower(sr.Username),
  438. Name: sr.Username,
  439. FullName: composeFullName(sr.Name, sr.Surname, sr.Username),
  440. Email: sr.Mail,
  441. LoginType: source.Type,
  442. LoginSource: source.ID,
  443. LoginName: login,
  444. IsActive: true,
  445. IsAdmin: sr.IsAdmin,
  446. }
  447. err := CreateUser(user)
  448. if err == nil && isAttributeSSHPublicKeySet && addLdapSSHPublicKeys(user, source, sr.SSHPublicKey) {
  449. err = RewriteAllPublicKeys()
  450. }
  451. return user, err
  452. }
  453. // _________ __________________________
  454. // / _____/ / \__ ___/\______ \
  455. // \_____ \ / \ / \| | | ___/
  456. // / \/ Y \ | | |
  457. // /_______ /\____|__ /____| |____|
  458. // \/ \/
  459. type smtpLoginAuth struct {
  460. username, password string
  461. }
  462. func (auth *smtpLoginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
  463. return "LOGIN", []byte(auth.username), nil
  464. }
  465. func (auth *smtpLoginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
  466. if more {
  467. switch string(fromServer) {
  468. case "Username:":
  469. return []byte(auth.username), nil
  470. case "Password:":
  471. return []byte(auth.password), nil
  472. }
  473. }
  474. return nil, nil
  475. }
  476. // SMTP authentication type names.
  477. const (
  478. SMTPPlain = "PLAIN"
  479. SMTPLogin = "LOGIN"
  480. )
  481. // SMTPAuths contains available SMTP authentication type names.
  482. var SMTPAuths = []string{SMTPPlain, SMTPLogin}
  483. // SMTPAuth performs an SMTP authentication.
  484. func SMTPAuth(a smtp.Auth, cfg *SMTPConfig) error {
  485. c, err := smtp.Dial(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port))
  486. if err != nil {
  487. return err
  488. }
  489. defer c.Close()
  490. if err = c.Hello("gogs"); err != nil {
  491. return err
  492. }
  493. if cfg.TLS {
  494. if ok, _ := c.Extension("STARTTLS"); ok {
  495. if err = c.StartTLS(&tls.Config{
  496. InsecureSkipVerify: cfg.SkipVerify,
  497. ServerName: cfg.Host,
  498. }); err != nil {
  499. return err
  500. }
  501. } else {
  502. return errors.New("SMTP server unsupports TLS")
  503. }
  504. }
  505. if ok, _ := c.Extension("AUTH"); ok {
  506. return c.Auth(a)
  507. }
  508. return ErrUnsupportedLoginType
  509. }
  510. // LoginViaSMTP queries if login/password is valid against the SMTP,
  511. // and create a local user if success when enabled.
  512. func LoginViaSMTP(user *User, login, password string, sourceID int64, cfg *SMTPConfig) (*User, error) {
  513. // Verify allowed domains.
  514. if len(cfg.AllowedDomains) > 0 {
  515. idx := strings.Index(login, "@")
  516. if idx == -1 {
  517. return nil, ErrUserNotExist{0, login, 0}
  518. } else if !com.IsSliceContainsStr(strings.Split(cfg.AllowedDomains, ","), login[idx+1:]) {
  519. return nil, ErrUserNotExist{0, login, 0}
  520. }
  521. }
  522. var auth smtp.Auth
  523. if cfg.Auth == SMTPPlain {
  524. auth = smtp.PlainAuth("", login, password, cfg.Host)
  525. } else if cfg.Auth == SMTPLogin {
  526. auth = &smtpLoginAuth{login, password}
  527. } else {
  528. return nil, errors.New("Unsupported SMTP auth type")
  529. }
  530. if err := SMTPAuth(auth, cfg); err != nil {
  531. // Check standard error format first,
  532. // then fallback to worse case.
  533. tperr, ok := err.(*textproto.Error)
  534. if (ok && tperr.Code == 535) ||
  535. strings.Contains(err.Error(), "Username and Password not accepted") {
  536. return nil, ErrUserNotExist{0, login, 0}
  537. }
  538. return nil, err
  539. }
  540. if user != nil {
  541. return user, nil
  542. }
  543. username := login
  544. idx := strings.Index(login, "@")
  545. if idx > -1 {
  546. username = login[:idx]
  547. }
  548. user = &User{
  549. LowerName: strings.ToLower(username),
  550. Name: strings.ToLower(username),
  551. Email: login,
  552. Passwd: password,
  553. LoginType: LoginSMTP,
  554. LoginSource: sourceID,
  555. LoginName: login,
  556. IsActive: true,
  557. }
  558. return user, CreateUser(user)
  559. }
  560. // __________ _____ _____
  561. // \______ \/ _ \ / \
  562. // | ___/ /_\ \ / \ / \
  563. // | | / | \/ Y \
  564. // |____| \____|__ /\____|__ /
  565. // \/ \/
  566. // LoginViaPAM queries if login/password is valid against the PAM,
  567. // and create a local user if success when enabled.
  568. func LoginViaPAM(user *User, login, password string, sourceID int64, cfg *PAMConfig) (*User, error) {
  569. pamLogin, err := pam.Auth(cfg.ServiceName, login, password)
  570. if err != nil {
  571. if strings.Contains(err.Error(), "Authentication failure") {
  572. return nil, ErrUserNotExist{0, login, 0}
  573. }
  574. return nil, err
  575. }
  576. if user != nil {
  577. return user, nil
  578. }
  579. // Allow PAM sources with `@` in their name, like from Active Directory
  580. username := pamLogin
  581. idx := strings.Index(pamLogin, "@")
  582. if idx > -1 {
  583. username = pamLogin[:idx]
  584. }
  585. user = &User{
  586. LowerName: strings.ToLower(username),
  587. Name: username,
  588. Email: pamLogin,
  589. Passwd: password,
  590. LoginType: LoginPAM,
  591. LoginSource: sourceID,
  592. LoginName: login, // This is what the user typed in
  593. IsActive: true,
  594. }
  595. return user, CreateUser(user)
  596. }
  597. // ExternalUserLogin attempts a login using external source types.
  598. func ExternalUserLogin(user *User, login, password string, source *LoginSource) (*User, error) {
  599. if !source.IsActived {
  600. return nil, ErrLoginSourceNotActived
  601. }
  602. var err error
  603. switch source.Type {
  604. case LoginLDAP, LoginDLDAP:
  605. user, err = LoginViaLDAP(user, login, password, source)
  606. case LoginSMTP:
  607. user, err = LoginViaSMTP(user, login, password, source.ID, source.Cfg.(*SMTPConfig))
  608. case LoginPAM:
  609. user, err = LoginViaPAM(user, login, password, source.ID, source.Cfg.(*PAMConfig))
  610. default:
  611. return nil, ErrUnsupportedLoginType
  612. }
  613. if err != nil {
  614. return nil, err
  615. }
  616. // WARN: DON'T check user.IsActive, that will be checked on reqSign so that
  617. // user could be hint to resend confirm email.
  618. if user.ProhibitLogin {
  619. return nil, ErrUserProhibitLogin{user.ID, user.Name}
  620. }
  621. return user, nil
  622. }
  623. // UserSignIn validates user name and password.
  624. func UserSignIn(username, password string) (*User, error) {
  625. var user *User
  626. if strings.Contains(username, "@") {
  627. user = &User{Email: strings.ToLower(strings.TrimSpace(username))}
  628. // check same email
  629. cnt, err := x.Count(user)
  630. if err != nil {
  631. return nil, err
  632. }
  633. if cnt > 1 {
  634. return nil, ErrEmailAlreadyUsed{
  635. Email: user.Email,
  636. }
  637. }
  638. } else {
  639. trimmedUsername := strings.TrimSpace(username)
  640. if len(trimmedUsername) == 0 {
  641. return nil, ErrUserNotExist{0, username, 0}
  642. }
  643. user = &User{LowerName: strings.ToLower(trimmedUsername)}
  644. }
  645. hasUser, err := x.Get(user)
  646. if err != nil {
  647. return nil, err
  648. }
  649. if hasUser {
  650. switch user.LoginType {
  651. case LoginNoType, LoginPlain, LoginOAuth2:
  652. if user.IsPasswordSet() && user.ValidatePassword(password) {
  653. // Update password hash if server password hash algorithm have changed
  654. if user.PasswdHashAlgo != setting.PasswordHashAlgo {
  655. user.HashPassword(password)
  656. if err := UpdateUserCols(user, "passwd", "passwd_hash_algo"); err != nil {
  657. return nil, err
  658. }
  659. }
  660. // WARN: DON'T check user.IsActive, that will be checked on reqSign so that
  661. // user could be hint to resend confirm email.
  662. if user.ProhibitLogin {
  663. return nil, ErrUserProhibitLogin{user.ID, user.Name}
  664. }
  665. return user, nil
  666. }
  667. return nil, ErrUserNotExist{user.ID, user.Name, 0}
  668. default:
  669. var source LoginSource
  670. hasSource, err := x.ID(user.LoginSource).Get(&source)
  671. if err != nil {
  672. return nil, err
  673. } else if !hasSource {
  674. return nil, ErrLoginSourceNotExist{user.LoginSource}
  675. }
  676. return ExternalUserLogin(user, user.LoginName, password, &source)
  677. }
  678. }
  679. sources := make([]*LoginSource, 0, 5)
  680. if err = x.Where("is_actived = ?", true).Find(&sources); err != nil {
  681. return nil, err
  682. }
  683. for _, source := range sources {
  684. if source.IsOAuth2() || source.IsSSPI() {
  685. // don't try to authenticate against OAuth2 and SSPI sources here
  686. continue
  687. }
  688. authUser, err := ExternalUserLogin(nil, username, password, source)
  689. if err == nil {
  690. return authUser, nil
  691. }
  692. log.Warn("Failed to login '%s' via '%s': %v", username, source.Name, err)
  693. }
  694. return nil, ErrUserNotExist{user.ID, user.Name, 0}
  695. }