-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathautosign.go
108 lines (75 loc) · 1.85 KB
/
autosign.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package autosign
import (
"bytes"
"crypto/sha1"
"encoding/hex"
"errors"
"io/ioutil"
"log"
"os"
"path/filepath"
)
const (
signature = "autosignature"
)
func checkError(e error) {
if e != nil {
log.Fatal(e)
os.Exit(0)
}
}
func Init(salt ...[]byte) (outHash string, outCreated bool) {
outHash = ""
outCreated = false
var err error = nil
var needSign bool = true
var sign_found []byte
var byte_sign []byte = []byte(signature)
var size_sign int = 40 + len(byte_sign)
var executable string
executable, err = os.Executable()
checkError(err)
file, err := ioutil.ReadFile(executable)
checkError(err)
if bytes.Equal(byte_sign, file[len(file)-size_sign:][:len(byte_sign)]) {
needSign = false
sign_found = file[len(file)-(size_sign-len(byte_sign)):]
}
hash := sha1.New()
if needSign == true {
_, err = hash.Write(file)
} else {
_, err = hash.Write(file[:len(file)-(size_sign)])
}
checkError(err)
if len(salt) > 0 {
_, err = hash.Write(salt[0])
checkError(err)
}
hashInBytes := hash.Sum(nil)[:]
shaFile := make([]byte, 40)
hex.Encode(shaFile, hashInBytes)
if needSign == true {
var directory string
var filename string
var executable_signed string
directory, filename = filepath.Split(executable)
filename = filename[0:len(filename)-len(filepath.Ext(filename))] + "_" + string(shaFile[:]) + filepath.Ext(filename)
executable_signed = directory + filename
var _, err = os.Stat(executable_signed)
if os.IsNotExist(err) {
data, err := ioutil.ReadFile(executable)
checkError(err)
err = ioutil.WriteFile(executable_signed, append(data, append(byte_sign, shaFile...)...), 0644)
checkError(err)
}
outCreated = true
} else {
if !bytes.Equal(shaFile, sign_found) {
checkError(errors.New("File corrupted!"))
}
outCreated = false
}
outHash = string(shaFile[:])
return outHash, outCreated
}