go - 检查 golang 中的二进制完整性

标签 go

我尝试为我的应用程序创建完整性保护,这是我的实际代码:

package main 

import (
    "os"
    "io"
    "crypto/sha256"
    "fmt"
)


var OriginalSign string


func checkSUM() string {
    hasher := sha256.New()
    f, err := os.Open(os.Args[0])
    if err != nil {
        os.Exit(0)
    }

    defer f.Close()
    if _, err = io.Copy(hasher, f); err != nil {
        os.Exit(0)
    }

    return fmt.Sprintf("%x", hasher.Sum(nil))
}


func main() {
    signature := checkSUM()

    fmt.Println(OriginalSign)
    fmt.Println(signature)

    if signature != OriginalSign {
        fmt.Println("binary is compromised")
    }
}

我用这个命令编译:

C:\Users\admin\go\src\localhost\lic>go build -ldflags="-s -w -X main.OriginalSig
n=8636cdeef255e52c6fd3f391fd7d75fbaf7c6e830e0e7ac66a645093c7efcbc7" -o checksum.
exe checksum.go

C:\Users\admin\go\src\localhost\lic>checksum.exe
8636cdeef255e52c6fd3f391fd7d75fbaf7c6e830e0e7ac66a645093c7efcbc7
d29440d3467f6176a6af0dcb61ea696cb318db3a6f1680b5b8f7890e165d8d7e
binary is compromised

我怎样才能在 go 中正确地做到这一点?我需要知道最终二进制文件的签名并检查是否被破坏。

最佳答案

我看不到如何挂接到程序中的工具 buildid,但它可以(某种程度上)检测二进制文件的更改

buildid 似乎确实存储了二进制文件的“contentid”,这是原始问题的本质

这是一个显示此内容的 bash 脚本(抱歉,我不使用 MS Windows)

#

# delete any old binaries
rm -f t

# do an initial build
go build t.go

# show it works
./t

# get the original buildid
ORIG=$(go tool buildid t)

# now tamper with it!
perl -p -i -e 's/testing/porkpie/' t

# run again, show the tamper
./t

# now regenerate the buildid
go tool buildid -w t

# get the buildid after the regeneration
LATER=$(go tool buildid t)

# show the original and the post-tampering buildid - they are different
echo "$ORIG"
echo "$LATER"

这里是什么都不做的 t.go

package main

import (
    "fmt"
)

func main() {
    fmt.Println("testing 123")
}

这是输出

testing 123
porkpie 123
koB1H61TwQSHTQGiI4PP/-o93sSzqt1ltMhBJn4pR/2wvL4J9vF4vGUGjdbsyd/y-0uRBmxfJdrbAfsE1lr
koB1H61TwQSHTQGiI4PP/-o93sSzqt1ltMhBJn4pR/2wvL4J9vF4vGUGjdbsyd/UeLetY1pBF54B_4Y8-Nj

因此 go tool buildid 可以将哈希存储在二进制文件中并(某种程度上)检测篡改。但是我不知道如何从普通程序中的普通调用中获取 contentid

关于go - 检查 golang 中的二进制完整性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50996194/

相关文章:

go - 在 Go 中命名我的代码

windows - 在 Go 中创建 Windows 快捷方式 (.lnk)

go - 通过将键与字符串数组进行比较来从 map 中检索

XML 解析返回带有换行符的字符串

go - "bad quoted string"在生成

go - 如何从 slice 中删除项目的重复项?

go - 需要一个示例,了解赋值运算符的Go语法如何使用通过EBNF指定的语法规则

go - 为什么 go vet report uint(0) 对于 63 的移位来说可能太小了?

go - 重定向到 Go 中的页面问题

Go:rpc 请求返回空