-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.go
408 lines (336 loc) · 12.4 KB
/
lib.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/gob"
"encoding/pem"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"os"
"os/exec"
"strings"
)
// Windows Only (duh)
// Function to run PowerShell command
func ExecPowerShell(script string) (string, error) {
cmd := exec.Command("powershell", "-Command", script)
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
return out.String(), err
}
// Save our config struct to an encrypted binary file
func DumpStructToFile(data any, filename string, key []byte) error {
// Encode the data using gob
var buffer bytes.Buffer
encoder := gob.NewEncoder(&buffer)
err := encoder.Encode(data)
if err != nil {
return err
}
// Create the AES cipher
block, err := aes.NewCipher(key)
if err != nil {
return err
}
// Generate a new IV
iv := make([]byte, aes.BlockSize)
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return err
}
// Pad the data to ensure it is a multiple of the block size
originalData := buffer.Bytes()
padding := aes.BlockSize - len(originalData)%aes.BlockSize
paddedData := append(originalData, bytes.Repeat([]byte{byte(padding)}, padding)...)
// Encrypt the data
encryptedData := make([]byte, aes.BlockSize+len(paddedData))
copy(encryptedData[:aes.BlockSize], iv)
stream := cipher.NewCBCEncrypter(block, iv)
stream.CryptBlocks(encryptedData[aes.BlockSize:], paddedData)
// Open the file to write
os.Mkdir("/etc/project-one", 0755)
file, err := os.Create(filename)
if err != nil {
return err
}
println("creating file")
defer file.Close()
// Write the encrypted data to file
_, err = file.Write(encryptedData)
return err
}
func SendToTermbin(text string) string {
// Connect to termbin.com on port 9999
conn, err := net.Dial("tcp", "termbin.com:9999")
handle(err)
defer conn.Close()
// Write data to the connection
_, err = conn.Write([]byte(text + "\n"))
handle(err)
// Read the response (URL) from termbin
buffer := make([]byte, 1024)
n, err := conn.Read(buffer)
handle(err)
url := string(buffer[:n])
code := strings.Split(url, "termbin.com/")[1]
// Return the response (URL)
return code
}
// Load our config to the "MasterConfig" struct from an encrypted binary file
func LoadStructFromFile(data any, filename string, key []byte) error {
// Open the file
file, err := os.Open(filename)
if err != nil {
return err
}
defer file.Close()
// Read the encrypted data from file
encryptedData, err := ioutil.ReadAll(file)
if err != nil {
return err
}
// Create the AES cipher
block, err := aes.NewCipher(key)
if err != nil {
return err
}
// Check for data length
if len(encryptedData) < aes.BlockSize {
return errors.New("ciphertext too short")
}
// IV is at the beginning of the file
iv := encryptedData[:aes.BlockSize]
encryptedData = encryptedData[aes.BlockSize:]
// Decrypt the data
stream := cipher.NewCBCDecrypter(block, iv)
stream.CryptBlocks(encryptedData, encryptedData)
// Remove padding
paddingLen := int(encryptedData[len(encryptedData)-1])
if paddingLen > aes.BlockSize || paddingLen == 0 {
return errors.New("invalid padding size")
}
decryptedData := encryptedData[:len(encryptedData)-paddingLen]
// Decode the gob
decoder := gob.NewDecoder(bytes.NewReader(decryptedData))
err = decoder.Decode(data)
return err
}
// Allows us to save the RSA public key in a somewhat human-readable format
func ExportRsaPublicKeyAsPemStr(pubkey *rsa.PublicKey) string {
pubAsn1, _ := x509.MarshalPKIXPublicKey(pubkey)
pubBytes := pem.EncodeToMemory(&pem.Block{
Type: "RSA PUBLIC KEY",
Bytes: pubAsn1,
})
return string(pubBytes)
}
// Broadcasts a message to all users via (Linux) (who says we can't have some fun back with the red team?)
func LinuxBroadcast(message string) error {
cmd := exec.Command("wall", "-n")
stdinPipe, err := cmd.StdinPipe()
if err != nil {
return err
}
go func() {
defer stdinPipe.Close()
stdinPipe.Write([]byte(message))
}()
return cmd.Run()
}
// Broadcasts a message to all users (Windows) (who says we can't have some fun back with the red team?)
func WindowsBroadcast(message string) error {
cleanedMessage := strings.ReplaceAll(message, "\n", "`n")
_, err := ExecPowerShell("msg * /server:$env:COMPUTERNAME \"" + cleanedMessage + "\"")
handle(err)
return nil
}
// Basic error handler to satisfy the linter
func handle(e error) {
if e != nil {
fmt.Println(Red + "PANIC: Something internal went wrong, this text should never be visible!!!")
fmt.Println(Reset, e)
os.Exit(-1)
}
}
/****************************************************
#####################################################
WINDOWS FIRST TIME SETUP STUFF
#####################################################
****************************************************/
// Create and store out windows config file
func WindowsFirstTimeSetup() {
var err error
var resp *http.Response
PrivateKey, _ := rsa.GenerateKey(rand.Reader, 2048) // returns pointer
ghUrl := "0"
ghUrl_confirm := "1"
// Basic input validation for the GitHub URL
for ghUrl != ghUrl_confirm {
fmt.Print("Enter the URL of the GitHub to search for backups: ")
fmt.Scanln(&ghUrl)
fmt.Print("Re-type GitHub URL: ")
fmt.Scanln(&ghUrl_confirm)
if ghUrl != ghUrl_confirm {
fmt.Println("URLs do not match, please try again.")
}
}
// Ensure the URL is in the correct format
ghUrl = "https://" + strings.TrimPrefix(strings.TrimPrefix(ghUrl, "http://"), "https://")
fmt.Println("Contacting repository...")
// Attempt to make a GET request to the repository
resp, err = http.Get(ghUrl)
_ = resp.Body.Close()
handle(err) // universal internal error handling (this should realistically never trigger)
if resp.StatusCode != 200 {
// if the repository returned 404, it's unreachable (either private or non-existent)
fmt.Println("Failed to read repository:")
fmt.Println("Status Code", resp.StatusCode)
os.Exit(-1)
}
// Validate the repository doesn't already contain an "ACTIVATE" file
// this is useful in case we need to redeploy our failsafe,
// we can generate a brand-new config file and RSA key
fmt.Println("Validating repository...")
// Format the github repo url into the direct download link to the ACTIVATE file
temp := strings.Split(ghUrl, "github.com/")
temp = strings.Split(temp[1], "/")
ghUrl = "https://raw.githubusercontent.com/" + temp[0] + "/" + temp[1] + "/main/ACTIVATE"
resp, err = http.Get(ghUrl) // attempt to download the ACTIVATE file
defer resp.Body.Close()
handle(err)
// Make sure the ACTIVATE file doesn't exist
if resp.StatusCode != 404 {
fmt.Println("Misconfigured Repository.")
fmt.Println("Make sure there is no file called 'ACTIVATE' (", resp.StatusCode, ")")
os.Exit(-1)
}
MasterConfig.RepoUrl = ghUrl
MasterConfig.Protector = *PrivateKey // dereference the pointer (low level memory manipulation crap)
fmt.Println("Generating config file...")
err = DumpStructToFile(MasterConfig, WindowsConfigLocation, MasterKey)
if err != nil {
_, err = ExecPowerShell("md " + strings.TrimSuffix(WindowsConfigLocation, "\\config.protected"))
handle(err)
err = DumpStructToFile(MasterConfig, WindowsConfigLocation, MasterKey)
}
handle(err)
fmt.Println("Config file generated successfully.")
fmt.Println("Copying executable to C:\\Windows\\System32\\one.exe...")
// Copy the binary to /usr/local/bin so it can be run as a service
exePath, err := os.Executable()
handle(err)
ExecPowerShell("copy \"" + exePath + "\" C:\\Windows\\System32\\one.exe")
fmt.Println("Creating Windows Defender Exclusion rule...")
// Tell windows defender our binary can be trusted.
_, err = ExecPowerShell("Add-MpPreference -ExclusionPath " + exePath)
handle(err)
fmt.Println("Scheduling startup task...")
// Enable the failsafe task to run at startup
_, err = ExecPowerShell(`schtasks /create /tn "` + taskname + `" /tr "C:\Windows\System32\one.exe" /sc onstart /ru "SYSTEM" /F`)
handle(err)
fmt.Println("Exporting public key...")
// Export the RSA public key as a PEM string (readable format)
PEMObj := ExportRsaPublicKeyAsPemStr(&PrivateKey.PublicKey)
os.Stdout.WriteString(Green + PEMObj + Reset)
os.WriteFile("PEM_STRING.txt", []byte(PEMObj), 0644)
recoveryCode := SendToTermbin(PEMObj)
fmt.Println("This is your recovery code:\n")
fmt.Println(Green + recoveryCode + Reset)
fmt.Println("\nStore it somewhere safe, as you will need it to activate the failsafe.")
fmt.Println(Red + "Recovery codes are DEVICE SPECIFIC\nDo not use this code to reset another device! You will corrupt it!" + Reset)
fmt.Println("Done.")
fmt.Println("Use Start-ScheduledTask -TaskName \"project-one\"\n or shutdown /r /f /t 0 to finalize install.")
os.Exit(0)
}
/****************************************************
#####################################################
LINUX FIRST TIME SETUP STUFF
#####################################################
****************************************************/
// Create and store out linux config file
func LinuxFirstTimeSetup() {
var err error
var resp *http.Response
PrivateKey, _ := rsa.GenerateKey(rand.Reader, 2048) // returns pointer
ghUrl := "0"
ghUrl_confirm := "1"
// Basic input validation for the GitHub URL
for ghUrl != ghUrl_confirm {
fmt.Print("Enter the URL of the GitHub to search for backups: ")
fmt.Scanln(&ghUrl)
fmt.Print("Re-type GitHub URL: ")
fmt.Scanln(&ghUrl_confirm)
if ghUrl != ghUrl_confirm {
fmt.Println(Red + "URLs do not match, please try again." + Reset)
}
}
// Ensure the URL is in the correct format
ghUrl = "https://" + strings.TrimPrefix(strings.TrimPrefix(ghUrl, "http://"), "https://")
fmt.Println("Contacting repository...")
// Attempt to make a GET request to the repository
resp, err = http.Get(ghUrl)
_ = resp.Body.Close()
handle(err) // universal internal error handling (this should realistically never trigger)
if resp.StatusCode != 200 {
// if the repository returned 404, it's unreachable (either private or non-existent)
fmt.Println(Red, "Failed to read repository:", Reset)
fmt.Println(Red, "Status Code", resp.StatusCode, Reset)
os.Exit(-1)
}
// Validate the repository doesn't already contain an "ACTIVATE" file
// this is useful in case we need to redeploy our failsafe,
// we can generate a brand-new config file and RSA key
fmt.Println("Validating repository...")
// Format the github repo url into the direct download link to the ACTIVATE file
temp := strings.Split(ghUrl, "github.com/")
temp = strings.Split(temp[1], "/")
ghUrl = "https://raw.githubusercontent.com/" + temp[0] + "/" + temp[1] + "/main/ACTIVATE"
resp, err = http.Get(ghUrl) // attempt to download the ACTIVATE file
defer resp.Body.Close()
handle(err)
if resp.StatusCode != 404 {
fmt.Println(Red, "Misconfigured Repository.", Reset)
fmt.Println(Red, "Make sure there is no file called 'ACTIVATE'", resp.StatusCode, Reset)
os.Exit(-1)
}
MasterConfig.RepoUrl = ghUrl
MasterConfig.Protector = *PrivateKey // dereference the pointer (low level memory manipulation crap)
fmt.Println("Generating config file...")
err = DumpStructToFile(MasterConfig, LinuxConfigLocation, MasterKey)
handle(err)
fmt.Println("Config file generated successfully.")
fmt.Println("Adding process to systemd...")
// Create the systemd service file
// This is necessary to ensure the failsafe keeps listening even if we reboot the system.
err = os.WriteFile("/etc/systemd/system/"+taskname+".service", []byte(systemd_service), 0644)
handle(err)
fmt.Println("Copying binary to /usr/local/bin...")
// Copy the binary to /usr/local/bin so it can be run as a service
thisPath, _ := os.Executable()
exec.Command("cp", thisPath, "/usr/local/bin/one").Run()
exec.Command("chmod", "+x", "/usr/local/bin/one").Run()
fmt.Println("Enabling process...")
// Enable the failsafe service to run at boot
cmd := exec.Command("systemctl", "enable", "one.service")
err = cmd.Run()
handle(err)
fmt.Println("Exporting public key...")
// Export the RSA public key as a PEM string (readable format)
PEMObj := ExportRsaPublicKeyAsPemStr(&PrivateKey.PublicKey)
recoveryCode := SendToTermbin(PEMObj)
fmt.Println("This is your recovery code:\n")
fmt.Println(Green + recoveryCode + Reset)
fmt.Println("\nStore it somewhere safe, as you will need it to activate the failsafe.")
fmt.Println(Red + "Recovery codes are DEVICE SPECIFIC\nDo not use this code to reset another device! You will corrupt it!" + Reset)
fmt.Println("Done.")
fmt.Println("Use " + White + "sudo systemctl start one.service" + Reset + " or reboot to finalize install.")
os.Exit(0)
}