Skip to content

Commit

Permalink
Merge pull request #365 from jumpserver/dev
Browse files Browse the repository at this point in the history
v4.3.0
  • Loading branch information
BaiJiangJie authored Oct 17, 2024
2 parents 3acc785 + 84a5e30 commit 9aef15b
Show file tree
Hide file tree
Showing 24 changed files with 191 additions and 62 deletions.
3 changes: 1 addition & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,5 @@ ui/pnpm-debug.log*
*.njsproj
*.sln
*.sw?
ui/yarn.lock
build
package-lock.json
build/
6 changes: 4 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,10 @@ RUN --mount=type=cache,target=/var/cache/apt,sharing=locked,id=lion \
&& ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
&& apt-get update \
&& apt-get install -y --no-install-recommends ${DEPENDENCIES} \
&& apt-get clean \
&& sed -i "s@# export @export @g" ~/.bashrc \
&& sed -i "s@# alias @alias @g" ~/.bashrc
&& sed -i "s@# alias @alias @g" ~/.bashrc \
&& mkdir -p /lib32 /libx32

WORKDIR /opt/lion

Expand All @@ -67,4 +69,4 @@ EXPOSE 8081

STOPSIGNAL SIGQUIT

CMD [ "supervisord", "-c", "/etc/supervisor/supervisord.conf" ]
CMD [ "supervisord", "-c", "/etc/supervisor/supervisord.conf" ]
45 changes: 44 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ func main() {
eng := registerRouter(jmsService, &tunnelService)
go runHeartTask(jmsService, tunnelService.Cache)
go runCleanDriverDisk(tunnelService.Cache)
go runTokenCheck(jmsService, tunnelService.Cache)
addr := net.JoinHostPort(config.GlobalConfig.BindHost, config.GlobalConfig.HTTPPort)
fmt.Printf("Lion Version %s, more see https://www.jumpserver.org\n", Version)
logger.Infof("listen on: %s", addr)
Expand Down Expand Up @@ -212,6 +213,48 @@ func runCleanDriverDisk(tunnelCache *tunnel.GuaTunnelCacheManager) {
}
}

func runTokenCheck(jmsService *service.JMService, tunnelCache *tunnel.GuaTunnelCacheManager) {
for {
time.Sleep(5 * time.Minute)
connections := tunnelCache.GetActiveConnections()
tokens := make(map[string]model.TokenCheckStatus, len(connections))
for _, s := range connections {
tokenId := s.Sess.AuthInfo.Id
ret, ok := tokens[tokenId]
if ok {
handleTokenCheck(s, &ret)
continue
}
ret, err := jmsService.CheckTokenStatus(tokenId)
if err != nil && ret.Code == "" {
logger.Errorf("Check token status failed: %s", err)
continue
}
tokens[tokenId] = ret
handleTokenCheck(s, &ret)
}
}
}

func handleTokenCheck(session *tunnel.Connection, tokenStatus *model.TokenCheckStatus) {
var task model.TerminalTask
switch tokenStatus.Code {
case model.CodePermOk:
task = model.TerminalTask{
Name: model.TaskPermValid,
Args: tokenStatus.Detail,
}
default:
task = model.TerminalTask{
Name: model.TaskPermExpired,
Args: tokenStatus.Detail,
}
}
if err := session.HandleTask(&task); err != nil {
logger.Errorf("Handle token check task failed: %s", err)
}
}

func registerRouter(jmsService *service.JMService, tunnelService *tunnel.GuacamoleTunnelServer) *gin.Engine {
if config.GlobalConfig.LogLevel != "DEBUG" {
gin.SetMode(gin.ReleaseMode)
Expand All @@ -232,7 +275,7 @@ func registerRouter(jmsService *service.JMService, tunnelService *tunnel.Guacamo
lionGroup.GET("/health/", func(ctx *gin.Context) {
status := make(map[string]interface{})
status["timestamp"] = time.Now().UTC()
status["uptime"] = time.Now().Sub(now).Minutes()
status["uptime"] = time.Since(now).Minutes()
ctx.JSON(http.StatusOK, status)
})
}
Expand Down
4 changes: 3 additions & 1 deletion pkg/common/random.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ import (

const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

var localRandom = rand.New(rand.NewSource(time.Now().UnixNano()))

func RandomStr(length int) string {
rand.Seed(time.Now().UnixNano())
localRandom.Seed(time.Now().UnixNano())
b := make([]byte, length)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
Expand Down
3 changes: 1 addition & 2 deletions pkg/jms-sdk-go/httplib/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/url"
Expand Down Expand Up @@ -180,7 +179,7 @@ func (c *Client) Do(method, reqUrl string, data, res interface{}, params ...map[
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return resp, err
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/jms-sdk-go/model/asset.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ type Protocols []Protocol

func (p Protocols) GetProtocolPort(protocol string) int {
for i := range p {
if strings.ToLower(p[i].Name) == strings.ToLower(protocol) {
if strings.EqualFold(p[i].Name, protocol) {
return p[i].Port
}
}
Expand Down
5 changes: 5 additions & 0 deletions pkg/jms-sdk-go/model/terminal.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ const (

TaskLockSession = "lock_session"
TaskUnlockSession = "unlock_session"

// TaskPermExpired TaskPermValid 非 api 数据,仅用于内部处理

TaskPermExpired = "perm_expired"
TaskPermValid = "perm_valid"
)

type TaskKwargs struct {
Expand Down
14 changes: 14 additions & 0 deletions pkg/jms-sdk-go/model/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,17 @@ type ConnectOptions struct {
Resolution string `json:"resolution"`
BackspaceAsCtrlH bool `json:"backspaceAsCtrlH"`
}

// token 授权和过期状态

type TokenCheckStatus struct {
Detail string `json:"detail"`
Code string `json:"code"`
Expired bool `json:"expired"`
}

const (
CodePermOk = "perm_ok"
CodePermAccountInvalid = "perm_account_invalid"
CodePermExpired = "perm_expired"
)
2 changes: 1 addition & 1 deletion pkg/jms-sdk-go/service/jms.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ func (s *JMService) GetWsClient() (*websocket.Conn, error) {
if err != nil {
return nil, err
}
scheme := "ws"
var scheme string
switch u.Scheme {
case "http":
scheme = "ws"
Expand Down
6 changes: 6 additions & 0 deletions pkg/jms-sdk-go/service/jms_token.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,9 @@ func (s *JMService) GetConnectTokenVirtualAppOption(tokenId string) (resp model.
_, err = s.authClient.Post(SuperConnectTokenVirtualAppOptionURL, data, &resp)
return
}

func (s *JMService) CheckTokenStatus(tokenId string) (res model.TokenCheckStatus, err error) {
reqURL := fmt.Sprintf(SuperConnectTokenCheckURL, tokenId)
_, err = s.authClient.Get(reqURL, &res)
return
}
1 change: 0 additions & 1 deletion pkg/jms-sdk-go/service/panda/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ func NewClient(baseUrl string, key model.AccessKey, insecure bool) *Client {

type Client struct {
BaseURL string
sign httplib.AuthSign
client *httplib.Client
}

Expand Down
26 changes: 0 additions & 26 deletions pkg/jms-sdk-go/service/panda/client_test.go

This file was deleted.

2 changes: 2 additions & 0 deletions pkg/jms-sdk-go/service/url.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ const (
SuperConnectAppletHostAccountReleaseURL = "/api/v1/authentication/super-connection-token/applet-account/release/"

SuperConnectTokenVirtualAppOptionURL = "/api/v1/authentication/super-connection-token/virtual-app-option/"

SuperConnectTokenCheckURL = "/api/v1/authentication/super-connection-token/%s/check/"
)

const (
Expand Down
19 changes: 8 additions & 11 deletions pkg/jms-sdk-go/service/videoworker/video_worker.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,7 @@ func NewClient(baseUrl string, key model.AccessKey, Insecure bool) *Client {

type Client struct {
BaseURL string
sign httplib.AuthSign
client *httplib.Client

cacheToken map[string]interface{}
}

func (s *Client) CreateReplayTask(sessionId string, file string, meta ReplayMeta) (model.Task, error) {
Expand Down Expand Up @@ -86,21 +83,21 @@ func StructToMapString(m interface{}) map[string]string {
if tagValue := fi.Tag.Get(tagName); tagValue != "" {
interValue := v.Field(i).Interface()
fieldValue := ""
switch interValue.(type) {
switch interValue1 := interValue.(type) {
case string:
fieldValue = interValue.(string)
fieldValue = interValue1
case int:
fieldValue = strconv.Itoa(interValue.(int))
fieldValue = strconv.Itoa(interValue1)
case int32:
fieldValue = strconv.FormatInt(int64(interValue.(int32)), 10)
fieldValue = strconv.FormatInt(int64(interValue1), 10)
case int64:
fieldValue = strconv.FormatInt(interValue.(int64), 10)
fieldValue = strconv.FormatInt(interValue1, 10)
case float64:
fieldValue = strconv.FormatFloat(interValue.(float64), 'f', -1, 64)
fieldValue = strconv.FormatFloat(interValue1, 'f', -1, 64)
case bool:
fieldValue = strconv.FormatBool(interValue.(bool))
fieldValue = strconv.FormatBool(interValue1)
default:
fieldValue = fmt.Sprintf("%v", interValue)
fieldValue = fmt.Sprintf("%v", interValue1)
}
// 如果值为空或者为0则不传递
if fieldValue == "" || fieldValue == "0" {
Expand Down
4 changes: 2 additions & 2 deletions pkg/session/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,8 @@ func (p *Parser) ParseStream(userInChan chan *Message) {
unicode := strconv.FormatInt(int64(keyCode), 16)
bs, _ := hex.DecodeString(unicode[3:])
for i, bl, br, r := 0, len(bs), bytes.NewReader(bs), uint16(0); i < bl; i += 2 {
binary.Read(br, binary.BigEndian, &r)
to += string(r)
_ = binary.Read(br, binary.BigEndian, &r)
to += string(rune(r))
}
b = append(b, []byte(to)...)
} else {
Expand Down
2 changes: 1 addition & 1 deletion pkg/session/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ func (s *Server) Create(ctx *gin.Context, opts ...TunnelOption) (sess TunnelSess
for _, setter := range opts {
setter(opt)
}
targetType := TypeRDP
var targetType string
sessionProtocol := opt.Protocol
switch opt.authInfo.ConnectMethod.Type {
case connectApplet, connectVirtualAPP:
Expand Down
4 changes: 2 additions & 2 deletions pkg/storage/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,13 +193,13 @@ func ParseEndpointRegion(s string) string {
}
endpoint, err := url.Parse(s)
if err != nil {
return ""
return s
}
endpoints := strings.Split(endpoint.Hostname(), ".")
if len(endpoints) >= 3 {
return endpoints[len(endpoints)-3]
}
return ""
return endpoints[0]
}

func ParseAWSURLRegion(s string) string {
Expand Down
5 changes: 5 additions & 0 deletions pkg/tunnel/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ type GuaTunnelCache interface {
GetSessionEventChan(sid string) *EventChan
BroadcastSessionEvent(sid string, event *Event)
RecycleSessionEventChannel(sid string, eventChan *EventChan)

GetActiveConnections() []*Connection
}

type SessionEvent interface {
Expand Down Expand Up @@ -117,4 +119,7 @@ const (
ShareRemoveUser = "share_remove_user"
ShareSessionPause = "share_session_pause"
ShareSessionResume = "share_session_resume"

PermExpiredEvent = "perm_expired"
PermValidEvent = "perm_valid"
)
10 changes: 10 additions & 0 deletions pkg/tunnel/cache_local.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,3 +121,13 @@ func (g *GuaTunnelLocalCache) RecycleSessionEventChannel(sid string, eventChan *
}
}
}

func (g *GuaTunnelLocalCache) GetActiveConnections() []*Connection {
g.Lock()
defer g.Unlock()
ret := make([]*Connection, 0, len(g.Tunnels))
for i := range g.Tunnels {
ret = append(ret, g.Tunnels[i])
}
return ret
}
3 changes: 0 additions & 3 deletions pkg/tunnel/cache_remote.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,9 +148,6 @@ type GuaTunnelRedisCache struct {

redisProxyExitChan chan string
redisConExitChan chan string

roomLock sync.Mutex
remoteRooms map[string]*Room
}

func (r *GuaTunnelRedisCache) BroadcastSessionEvent(sid string, event *Event) {
Expand Down
Loading

0 comments on commit 9aef15b

Please sign in to comment.