-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
261 lines (223 loc) · 6.06 KB
/
main.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
package main
import (
"database/sql"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"time"
"github.com/fatih/color"
_ "github.com/go-sql-driver/mysql"
)
// Define flags
var (
source = flag.String("s", "", "Source Host")
file = flag.String("f", "", "dump file")
only = flag.String("o", "", "Only dump the specified user")
help = flag.Bool("h", false, "Print help")
)
// define colors
var green = color.New(color.FgGreen).SprintFunc()
var red = color.New(color.FgRed).SprintFunc()
var yellow = color.New(color.FgYellow).SprintFunc()
//var blue = color.New(color.FgBlue).SprintFunc()
// parse flags
func init() {
flag.Parse()
}
// global variables
var (
db *sql.DB
err error
)
// read the ~/.my.cnf file to get the database credentials
func readMyCnf() {
file, err := ioutil.ReadFile(os.Getenv("HOME") + "/.my.cnf")
if err != nil {
handleError(err)
}
lines := strings.Split(string(file), "\n")
for _, line := range lines {
if strings.HasPrefix(line, "user") {
os.Setenv("MYSQL_USER", strings.TrimSpace(line[5:]))
}
if strings.HasPrefix(line, "password") {
os.Setenv("MYSQL_PASSWORD", strings.TrimSpace(line[9:]))
}
}
}
// connet to the source database and create a connection
func connectToDatabase() {
db, err = sql.Open("mysql", os.Getenv("MYSQL_USER")+":"+os.Getenv("MYSQL_PASSWORD")+"@tcp("+*source+":3306)/")
if err != nil {
handleError(err)
}
err = db.Ping()
if err != nil {
handleError(err)
}
log.Println(green("[+]"), "Connecting to database:", os.Getenv("MYSQL_USER")+":"+os.Getenv("MYSQL_PASSWORD")+"@tcp("+*source+":3306)/mysql")
}
// Create a function to dump the user accounts to a file
func dumpUserAccounts() {
// Get the user accounts from the source database
var rows *sql.Rows
var err error
if *only != "" {
rows, err = db.Query("SELECT CONCAT('SHOW CREATE USER ', quote(user), '@', quote(host), '; SHOW GRANTS FOR ', quote(user), '@', quote(host), ';') as user FROM mysql.user WHERE user = ?", *only)
} else {
rows, err = db.Query("SELECT CONCAT('SHOW CREATE USER ', quote(user), '@', quote(host), '; SHOW GRANTS FOR ', quote(user), '@', quote(host), ';') as user FROM mysql.user WHERE user NOT IN ('mysql.infoschema', 'mysql.session', 'mysql.sys')")
}
if err != nil {
handleError(err)
}
defer rows.Close()
var users []string
for rows.Next() {
var user string
err := rows.Scan(&user)
if err != nil {
handleError(err)
}
users = append(users, user)
}
if err := rows.Err(); err != nil {
handleError(err)
}
fileName := *file
// Check if file exists and has write permissions
fileInfo, err := os.Stat(fileName)
if os.IsNotExist(err) {
// File doesn't exist, try to create it
file, err := os.Create(fileName)
if err != nil {
handleError(err)
}
defer file.Close()
fileInfo, err = file.Stat()
if err != nil {
handleError(err)
}
} else if err != nil {
handleError(err)
}
// File exists and has write permissions, do something with it
if !fileInfo.Mode().IsRegular() {
handleError(fmt.Errorf("error: Not a regular file"))
} else if fileInfo.Mode().Perm()&os.FileMode(0200) == 0 {
handleError(fmt.Errorf("error: File is not writable"))
}
// Create the file and write the user accounts to it
file, err := os.Create(fileName)
if err != nil {
handleError(err)
}
defer file.Close()
// add this to the top of the file -> SET print_identified_with_as_hex = 1;
file.Seek(0, 0)
file.WriteString("SET print_identified_with_as_hex = 1;\n")
defer func() {
_, err := db.Exec("SET print_identified_with_as_hex = 0;")
if err != nil {
handleError(err)
}
}()
for _, user := range users {
if _, err = file.WriteString(user + "\n"); err != nil {
handleError(err)
}
}
if err = file.Sync(); err != nil {
handleError(err)
}
//fmt.Println(yellow("[+]"), "Wrote to file:", fileName)
}
// Create a function to read and apply the sql query from the file back to the source database
func runQuery() {
// Read SQL file
file, err := ioutil.ReadFile(*file)
if err != nil {
handleError(err)
}
// Split SQL file into statements
statements := strings.Split(string(file), ";")
// Execute each statement one by one
for _, statement := range statements {
if strings.TrimSpace(statement) == "" {
continue
}
rows, err := db.Query(statement)
if err != nil {
handleError(err)
}
defer rows.Close()
// Print out each row of results
columns, err := rows.Columns()
if err != nil {
handleError(err)
}
values := make([]interface{}, len(columns))
valuePtrs := make([]interface{}, len(columns))
for i := range columns {
valuePtrs[i] = &values[i]
}
for rows.Next() {
if err := rows.Scan(valuePtrs...); err != nil {
handleError(err)
}
for i, col := range values {
if col == nil {
fmt.Printf("-- %s: \n NULL;", columns[i]) // append semicolon to printed string
} else {
fmt.Printf("-- %s: \n %s;", columns[i], col) // append semicolon to printed string
}
}
fmt.Println()
}
}
}
// print the help message
func printHelp() {
fmt.Println("Usage: ./go-pass -s < source host> -f <dump file>")
fmt.Println("Options:")
fmt.Println("Usage: ./go-pass -s < source host> -f <dump file>" + yellow(" -o <user>"))
}
// handleError is a helper function to handle errors
func handleError(err error) {
log.Fatal(red("[!]"), err)
}
// main is the entry point of the application
func main() {
if *help {
printHelp()
os.Exit(0)
}
flag.Parse()
// read the ~/.my.cnf file to get the database credentials. check that the file exists
if _, err := os.Stat(os.Getenv("HOME") + "/.my.cnf"); os.IsNotExist(err) {
fmt.Println(red("[+]"), "Please create a ~/.my.cnf file with the database credentials.")
os.Exit(1)
}
readMyCnf()
connectToDatabase()
// make sure the source and target flags are set
if *source == "" || *file == "" {
printHelp()
os.Exit(1)
} else if *source == *file {
printHelp()
os.Exit(1)
} else {
if *file != "" {
fmt.Println(yellow("[+]"), "Dumping user accounts to file:", *file)
dumpUserAccounts()
defer db.Close()
// sleep for 5 seconds
time.Sleep(5 * time.Second)
runQuery()
defer db.Close()
}
}
}