login.go 13 KB

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