login_source.go 14 KB

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