socks5_check_access_handle.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package socks5
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "github.com/cnlh/nps/core"
  7. "net"
  8. )
  9. type CheckAccess struct {
  10. core.NpsPlugin
  11. configUsername string
  12. configPassword string
  13. }
  14. func (check *CheckAccess) GetConfigName() *core.NpsConfigs {
  15. c := core.NewNpsConfigs("socks5_simple_access_check", "need check the permission simply", core.CONFIG_LEVEL_PLUGIN)
  16. c.Add("socks5_simple_access_username", "simple auth username", core.CONFIG_LEVEL_PLUGIN)
  17. c.Add("socks5_simple_access_password", "simple auth password", core.CONFIG_LEVEL_PLUGIN)
  18. return c
  19. }
  20. func (check *CheckAccess) Run(ctx context.Context) (context.Context, error) {
  21. clientConn := check.GetClientConn(ctx)
  22. check.configUsername = check.Configs["socks5_simple_access_username"]
  23. check.configPassword = check.Configs["socks5_simple_access_password"]
  24. if check.Configs["socks5_simple_access_check"] == "true" {
  25. connUsername := ctx.Value("socks_client_username").(string)
  26. connPassword := ctx.Value("socks_client_password").(string)
  27. return ctx, check.checkAuth(clientConn, connUsername, connPassword)
  28. }
  29. return ctx, nil
  30. }
  31. func (check *CheckAccess) checkAuth(clientConn net.Conn, connUserName, connPassword string) error {
  32. if check.configUsername == connUserName && check.configPassword == connPassword {
  33. _, err := clientConn.Write([]byte{userAuthVersion, authSuccess})
  34. return err
  35. } else {
  36. _, err := clientConn.Write([]byte{userAuthVersion, authFailure})
  37. if err != nil {
  38. return err
  39. }
  40. return errors.New("auth check error,username or password does not match")
  41. }
  42. }