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 23KB

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