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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. "strings"
  12. "time"
  13. "github.com/go-xorm/core"
  14. "github.com/go-xorm/xorm"
  15. "github.com/gogits/gogs/modules/auth/ldap"
  16. "github.com/gogits/gogs/modules/auth/pam"
  17. "github.com/gogits/gogs/modules/log"
  18. )
  19. type LoginType int
  20. // Note: new type must be added at the end of list to maintain compatibility.
  21. const (
  22. NOTYPE LoginType = iota
  23. PLAIN
  24. LDAP
  25. SMTP
  26. PAM
  27. DLDAP
  28. )
  29. var (
  30. ErrAuthenticationAlreadyExist = errors.New("Authentication already exist")
  31. ErrAuthenticationNotExist = errors.New("Authentication does not exist")
  32. ErrAuthenticationUserUsed = errors.New("Authentication has been used by some users")
  33. )
  34. var LoginTypes = map[LoginType]string{
  35. LDAP: "LDAP (via BindDN)",
  36. DLDAP: "LDAP (simple auth)",
  37. SMTP: "SMTP",
  38. PAM: "PAM",
  39. }
  40. // Ensure structs implemented interface.
  41. var (
  42. _ core.Conversion = &LDAPConfig{}
  43. _ core.Conversion = &SMTPConfig{}
  44. _ core.Conversion = &PAMConfig{}
  45. )
  46. type LDAPConfig struct {
  47. ldap.Ldapsource
  48. }
  49. func (cfg *LDAPConfig) FromDB(bs []byte) error {
  50. return json.Unmarshal(bs, &cfg.Ldapsource)
  51. }
  52. func (cfg *LDAPConfig) ToDB() ([]byte, error) {
  53. return json.Marshal(cfg.Ldapsource)
  54. }
  55. type SMTPConfig struct {
  56. Auth string
  57. Host string
  58. Port int
  59. TLS bool
  60. SkipVerify bool
  61. }
  62. func (cfg *SMTPConfig) FromDB(bs []byte) error {
  63. return json.Unmarshal(bs, cfg)
  64. }
  65. func (cfg *SMTPConfig) ToDB() ([]byte, error) {
  66. return json.Marshal(cfg)
  67. }
  68. type PAMConfig struct {
  69. ServiceName string // pam service (e.g. system-auth)
  70. }
  71. func (cfg *PAMConfig) FromDB(bs []byte) error {
  72. return json.Unmarshal(bs, &cfg)
  73. }
  74. func (cfg *PAMConfig) ToDB() ([]byte, error) {
  75. return json.Marshal(cfg)
  76. }
  77. type LoginSource struct {
  78. ID int64 `xorm:"pk autoincr"`
  79. Type LoginType
  80. Name string `xorm:"UNIQUE"`
  81. IsActived bool `xorm:"NOT NULL DEFAULT false"`
  82. Cfg core.Conversion `xorm:"TEXT"`
  83. AllowAutoRegister bool `xorm:"NOT NULL DEFAULT false"`
  84. Created time.Time `xorm:"CREATED"`
  85. Updated time.Time `xorm:"UPDATED"`
  86. }
  87. func (source *LoginSource) BeforeSet(colName string, val xorm.Cell) {
  88. switch colName {
  89. case "type":
  90. switch LoginType((*val).(int64)) {
  91. case LDAP, DLDAP:
  92. source.Cfg = new(LDAPConfig)
  93. case SMTP:
  94. source.Cfg = new(SMTPConfig)
  95. case PAM:
  96. source.Cfg = new(PAMConfig)
  97. }
  98. }
  99. }
  100. func (source *LoginSource) TypeString() string {
  101. return LoginTypes[source.Type]
  102. }
  103. func (source *LoginSource) LDAP() *LDAPConfig {
  104. return source.Cfg.(*LDAPConfig)
  105. }
  106. func (source *LoginSource) SMTP() *SMTPConfig {
  107. return source.Cfg.(*SMTPConfig)
  108. }
  109. func (source *LoginSource) PAM() *PAMConfig {
  110. return source.Cfg.(*PAMConfig)
  111. }
  112. // CountLoginSources returns number of login sources.
  113. func CountLoginSources() int64 {
  114. count, _ := x.Count(new(LoginSource))
  115. return count
  116. }
  117. func CreateSource(source *LoginSource) error {
  118. _, err := x.Insert(source)
  119. return err
  120. }
  121. func GetAuths() ([]*LoginSource, error) {
  122. auths := make([]*LoginSource, 0, 5)
  123. return auths, x.Find(&auths)
  124. }
  125. func GetLoginSourceByID(id int64) (*LoginSource, error) {
  126. source := new(LoginSource)
  127. has, err := x.Id(id).Get(source)
  128. if err != nil {
  129. return nil, err
  130. } else if !has {
  131. return nil, ErrAuthenticationNotExist
  132. }
  133. return source, nil
  134. }
  135. func UpdateSource(source *LoginSource) error {
  136. _, err := x.Id(source.ID).AllCols().Update(source)
  137. return err
  138. }
  139. func DelLoginSource(source *LoginSource) error {
  140. cnt, err := x.Count(&User{LoginSource: source.ID})
  141. if err != nil {
  142. return err
  143. }
  144. if cnt > 0 {
  145. return ErrAuthenticationUserUsed
  146. }
  147. _, err = x.Id(source.ID).Delete(&LoginSource{})
  148. return err
  149. }
  150. // UserSignIn validates user name and password.
  151. func UserSignIn(uname, passwd string) (*User, error) {
  152. var u *User
  153. if strings.Contains(uname, "@") {
  154. u = &User{Email: uname}
  155. } else {
  156. u = &User{LowerName: strings.ToLower(uname)}
  157. }
  158. userExists, err := x.Get(u)
  159. if err != nil {
  160. return nil, err
  161. }
  162. if userExists {
  163. switch u.LoginType {
  164. case NOTYPE:
  165. fallthrough
  166. case PLAIN:
  167. if u.ValidatePassword(passwd) {
  168. return u, nil
  169. }
  170. return nil, ErrUserNotExist{u.Id, u.Name}
  171. default:
  172. var source LoginSource
  173. hasSource, err := x.Id(u.LoginSource).Get(&source)
  174. if err != nil {
  175. return nil, err
  176. } else if !hasSource {
  177. return nil, ErrLoginSourceNotExist
  178. }
  179. return ExternalUserLogin(u, u.LoginName, passwd, &source, false)
  180. }
  181. }
  182. var sources []LoginSource
  183. if err = x.UseBool().Find(&sources, &LoginSource{IsActived: true, AllowAutoRegister: true}); err != nil {
  184. return nil, err
  185. }
  186. for _, source := range sources {
  187. u, err := ExternalUserLogin(nil, uname, passwd, &source, true)
  188. if err == nil {
  189. return u, nil
  190. }
  191. log.Warn("Failed to login '%s' via '%s': %v", uname, source.Name, err)
  192. }
  193. return nil, ErrUserNotExist{u.Id, u.Name}
  194. }
  195. func ExternalUserLogin(u *User, name, passwd string, source *LoginSource, autoRegister bool) (*User, error) {
  196. if !source.IsActived {
  197. return nil, ErrLoginSourceNotActived
  198. }
  199. switch source.Type {
  200. case LDAP, DLDAP:
  201. return LoginUserLdapSource(u, name, passwd, source, autoRegister)
  202. case SMTP:
  203. return LoginUserSMTPSource(u, name, passwd, source.ID, source.Cfg.(*SMTPConfig), autoRegister)
  204. case PAM:
  205. return LoginUserPAMSource(u, name, passwd, source.ID, source.Cfg.(*PAMConfig), autoRegister)
  206. }
  207. return nil, ErrUnsupportedLoginType
  208. }
  209. // Query if name/passwd can login against the LDAP directory pool
  210. // Create a local user if success
  211. // Return the same LoginUserPlain semantic
  212. // FIXME: https://github.com/gogits/gogs/issues/672
  213. func LoginUserLdapSource(u *User, name, passwd string, source *LoginSource, autoRegister bool) (*User, error) {
  214. cfg := source.Cfg.(*LDAPConfig)
  215. directBind := (source.Type == DLDAP)
  216. fn, sn, mail, admin, logged := cfg.Ldapsource.SearchEntry(name, passwd, directBind)
  217. if !logged {
  218. // User not in LDAP, do nothing
  219. return nil, ErrUserNotExist{0, name}
  220. }
  221. if !autoRegister {
  222. return u, nil
  223. }
  224. // Fallback.
  225. if len(mail) == 0 {
  226. mail = fmt.Sprintf("%s@localhost", name)
  227. }
  228. u = &User{
  229. LowerName: strings.ToLower(name),
  230. Name: name,
  231. FullName: fn + " " + sn,
  232. LoginType: source.Type,
  233. LoginSource: source.ID,
  234. LoginName: name,
  235. Passwd: passwd,
  236. Email: mail,
  237. IsAdmin: admin,
  238. IsActive: true,
  239. }
  240. return u, CreateUser(u)
  241. }
  242. type loginAuth struct {
  243. username, password string
  244. }
  245. func LoginAuth(username, password string) smtp.Auth {
  246. return &loginAuth{username, password}
  247. }
  248. func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
  249. return "LOGIN", []byte(a.username), nil
  250. }
  251. func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
  252. if more {
  253. switch string(fromServer) {
  254. case "Username:":
  255. return []byte(a.username), nil
  256. case "Password:":
  257. return []byte(a.password), nil
  258. }
  259. }
  260. return nil, nil
  261. }
  262. const (
  263. SMTP_PLAIN = "PLAIN"
  264. SMTP_LOGIN = "LOGIN"
  265. )
  266. var (
  267. SMTPAuths = []string{SMTP_PLAIN, SMTP_LOGIN}
  268. )
  269. func SMTPAuth(a smtp.Auth, cfg *SMTPConfig) error {
  270. c, err := smtp.Dial(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port))
  271. if err != nil {
  272. return err
  273. }
  274. defer c.Close()
  275. if err = c.Hello("gogs"); err != nil {
  276. return err
  277. }
  278. if cfg.TLS {
  279. if ok, _ := c.Extension("STARTTLS"); ok {
  280. if err = c.StartTLS(&tls.Config{
  281. InsecureSkipVerify: cfg.SkipVerify,
  282. ServerName: cfg.Host,
  283. }); err != nil {
  284. return err
  285. }
  286. } else {
  287. return errors.New("SMTP server unsupports TLS")
  288. }
  289. }
  290. if ok, _ := c.Extension("AUTH"); ok {
  291. if err = c.Auth(a); err != nil {
  292. return err
  293. }
  294. return nil
  295. }
  296. return ErrUnsupportedLoginType
  297. }
  298. // Query if name/passwd can login against the LDAP directory pool
  299. // Create a local user if success
  300. // Return the same LoginUserPlain semantic
  301. func LoginUserSMTPSource(u *User, name, passwd string, sourceId int64, cfg *SMTPConfig, autoRegister bool) (*User, error) {
  302. var auth smtp.Auth
  303. if cfg.Auth == SMTP_PLAIN {
  304. auth = smtp.PlainAuth("", name, passwd, cfg.Host)
  305. } else if cfg.Auth == SMTP_LOGIN {
  306. auth = LoginAuth(name, passwd)
  307. } else {
  308. return nil, errors.New("Unsupported SMTP auth type")
  309. }
  310. if err := SMTPAuth(auth, cfg); err != nil {
  311. if strings.Contains(err.Error(), "Username and Password not accepted") {
  312. return nil, ErrUserNotExist{u.Id, u.Name}
  313. }
  314. return nil, err
  315. }
  316. if !autoRegister {
  317. return u, nil
  318. }
  319. var loginName = name
  320. idx := strings.Index(name, "@")
  321. if idx > -1 {
  322. loginName = name[:idx]
  323. }
  324. // fake a local user creation
  325. u = &User{
  326. LowerName: strings.ToLower(loginName),
  327. Name: strings.ToLower(loginName),
  328. LoginType: SMTP,
  329. LoginSource: sourceId,
  330. LoginName: name,
  331. IsActive: true,
  332. Passwd: passwd,
  333. Email: name,
  334. }
  335. err := CreateUser(u)
  336. return u, err
  337. }
  338. // Query if name/passwd can login against PAM
  339. // Create a local user if success
  340. // Return the same LoginUserPlain semantic
  341. func LoginUserPAMSource(u *User, name, passwd string, sourceId int64, cfg *PAMConfig, autoRegister bool) (*User, error) {
  342. if err := pam.PAMAuth(cfg.ServiceName, name, passwd); err != nil {
  343. if strings.Contains(err.Error(), "Authentication failure") {
  344. return nil, ErrUserNotExist{u.Id, u.Name}
  345. }
  346. return nil, err
  347. }
  348. if !autoRegister {
  349. return u, nil
  350. }
  351. // fake a local user creation
  352. u = &User{
  353. LowerName: strings.ToLower(name),
  354. Name: strings.ToLower(name),
  355. LoginType: PAM,
  356. LoginSource: sourceId,
  357. LoginName: name,
  358. IsActive: true,
  359. Passwd: passwd,
  360. Email: name,
  361. }
  362. err := CreateUser(u)
  363. return u, err
  364. }