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

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