socks5_check_access_handle.go 1.5 KB

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