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

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