Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
projectdiscovery
GitHub Repository: projectdiscovery/nuclei
Path: blob/dev/pkg/js/libs/mysql/mysql.go
2070 views
1
package mysql
2
3
import (
4
"context"
5
"database/sql"
6
"fmt"
7
"io"
8
"log"
9
"net"
10
"time"
11
12
"github.com/go-sql-driver/mysql"
13
"github.com/praetorian-inc/fingerprintx/pkg/plugins"
14
mysqlplugin "github.com/praetorian-inc/fingerprintx/pkg/plugins/services/mysql"
15
"github.com/projectdiscovery/nuclei/v3/pkg/js/utils"
16
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/protocolstate"
17
)
18
19
type (
20
// MySQLClient is a client for MySQL database.
21
// Internally client uses go-sql-driver/mysql driver.
22
// @example
23
// ```javascript
24
// const mysql = require('nuclei/mysql');
25
// const client = new mysql.MySQLClient;
26
// ```
27
MySQLClient struct{}
28
)
29
30
// IsMySQL checks if the given host is running MySQL database.
31
// If the host is running MySQL database, it returns true.
32
// If the host is not running MySQL database, it returns false.
33
// @example
34
// ```javascript
35
// const mysql = require('nuclei/mysql');
36
// const isMySQL = mysql.IsMySQL('acme.com', 3306);
37
// ```
38
func (c *MySQLClient) IsMySQL(ctx context.Context, host string, port int) (bool, error) {
39
executionId := ctx.Value("executionId").(string)
40
// todo: why this is exposed? Service fingerprint should be automatic
41
return memoizedisMySQL(executionId, host, port)
42
}
43
44
// @memo
45
func isMySQL(executionId string, host string, port int) (bool, error) {
46
if !protocolstate.IsHostAllowed(executionId, host) {
47
// host is not valid according to network policy
48
return false, protocolstate.ErrHostDenied.Msgf(host)
49
}
50
dialer := protocolstate.GetDialersWithId(executionId)
51
if dialer == nil {
52
return false, fmt.Errorf("dialers not initialized for %s", executionId)
53
}
54
55
conn, err := dialer.Fastdialer.Dial(context.TODO(), "tcp", net.JoinHostPort(host, fmt.Sprintf("%d", port)))
56
if err != nil {
57
return false, err
58
}
59
defer func() {
60
_ = conn.Close()
61
}()
62
63
plugin := &mysqlplugin.MYSQLPlugin{}
64
service, err := plugin.Run(conn, 5*time.Second, plugins.Target{Host: host})
65
if err != nil {
66
return false, err
67
}
68
if service == nil {
69
return false, nil
70
}
71
return true, nil
72
}
73
74
// Connect connects to MySQL database using given credentials.
75
// If connection is successful, it returns true.
76
// If connection is unsuccessful, it returns false and error.
77
// The connection is closed after the function returns.
78
// @example
79
// ```javascript
80
// const mysql = require('nuclei/mysql');
81
// const client = new mysql.MySQLClient;
82
// const connected = client.Connect('acme.com', 3306, 'username', 'password');
83
// ```
84
func (c *MySQLClient) Connect(ctx context.Context, host string, port int, username, password string) (bool, error) {
85
executionId := ctx.Value("executionId").(string)
86
if !protocolstate.IsHostAllowed(executionId, host) {
87
// host is not valid according to network policy
88
return false, protocolstate.ErrHostDenied.Msgf(host)
89
}
90
91
// executing queries implies the remote mysql service
92
ok, err := c.IsMySQL(ctx, host, port)
93
if err != nil {
94
return false, err
95
}
96
if !ok {
97
return false, fmt.Errorf("not a mysql service")
98
}
99
100
dsn, err := BuildDSN(MySQLOptions{
101
Host: host,
102
Port: port,
103
DbName: "INFORMATION_SCHEMA",
104
Protocol: "tcp",
105
Username: username,
106
Password: password,
107
})
108
if err != nil {
109
return false, err
110
}
111
return connectWithDSN(dsn)
112
}
113
114
type (
115
// MySQLInfo contains information about MySQL server.
116
// this is returned when fingerprint is successful
117
MySQLInfo struct {
118
Host string `json:"host,omitempty"`
119
IP string `json:"ip"`
120
Port int `json:"port"`
121
Protocol string `json:"protocol"`
122
TLS bool `json:"tls"`
123
Transport string `json:"transport"`
124
Version string `json:"version,omitempty"`
125
Debug plugins.ServiceMySQL `json:"debug,omitempty"`
126
Raw string `json:"metadata"`
127
}
128
)
129
130
// returns MySQLInfo when fingerpint is successful
131
// @example
132
// ```javascript
133
// const mysql = require('nuclei/mysql');
134
// const info = mysql.FingerprintMySQL('acme.com', 3306);
135
// log(to_json(info));
136
// ```
137
func (c *MySQLClient) FingerprintMySQL(ctx context.Context, host string, port int) (MySQLInfo, error) {
138
executionId := ctx.Value("executionId").(string)
139
return memoizedfingerprintMySQL(executionId, host, port)
140
}
141
142
// @memo
143
func fingerprintMySQL(executionId string, host string, port int) (MySQLInfo, error) {
144
info := MySQLInfo{}
145
if !protocolstate.IsHostAllowed(executionId, host) {
146
// host is not valid according to network policy
147
return info, protocolstate.ErrHostDenied.Msgf(host)
148
}
149
dialer := protocolstate.GetDialersWithId(executionId)
150
if dialer == nil {
151
return MySQLInfo{}, fmt.Errorf("dialers not initialized for %s", executionId)
152
}
153
154
conn, err := dialer.Fastdialer.Dial(context.TODO(), "tcp", net.JoinHostPort(host, fmt.Sprintf("%d", port)))
155
if err != nil {
156
return info, err
157
}
158
defer func() {
159
_ = conn.Close()
160
}()
161
162
plugin := &mysqlplugin.MYSQLPlugin{}
163
service, err := plugin.Run(conn, 5*time.Second, plugins.Target{Host: host})
164
if err != nil {
165
return info, err
166
}
167
if service == nil {
168
return info, fmt.Errorf("something went wrong got null output")
169
}
170
// fill all fields
171
info.Host = service.Host
172
info.IP = service.IP
173
info.Port = service.Port
174
info.Protocol = service.Protocol
175
info.TLS = service.TLS
176
info.Transport = service.Transport
177
info.Version = service.Version
178
info.Debug = service.Metadata().(plugins.ServiceMySQL)
179
bin, _ := service.Raw.MarshalJSON()
180
info.Raw = string(bin)
181
return info, nil
182
}
183
184
// ConnectWithDSN connects to MySQL database using given DSN.
185
// we override mysql dialer with fastdialer so it respects network policy
186
// If connection is successful, it returns true.
187
// @example
188
// ```javascript
189
// const mysql = require('nuclei/mysql');
190
// const client = new mysql.MySQLClient;
191
// const connected = client.ConnectWithDSN('username:password@tcp(acme.com:3306)/');
192
// ```
193
func (c *MySQLClient) ConnectWithDSN(dsn string) (bool, error) {
194
return memoizedconnectWithDSN(dsn)
195
}
196
197
// ExecuteQueryWithOpts connects to Mysql database using given credentials
198
// and executes a query on the db.
199
// @example
200
// ```javascript
201
// const mysql = require('nuclei/mysql');
202
// const options = new mysql.MySQLOptions();
203
// options.Host = 'acme.com';
204
// options.Port = 3306;
205
// const result = mysql.ExecuteQueryWithOpts(options, 'SELECT * FROM users');
206
// log(to_json(result));
207
// ```
208
func (c *MySQLClient) ExecuteQueryWithOpts(ctx context.Context, opts MySQLOptions, query string) (*utils.SQLResult, error) {
209
executionId := ctx.Value("executionId").(string)
210
if !protocolstate.IsHostAllowed(executionId, opts.Host) {
211
// host is not valid according to network policy
212
return nil, protocolstate.ErrHostDenied.Msgf(opts.Host)
213
}
214
215
// executing queries implies the remote mysql service
216
ok, err := c.IsMySQL(ctx, opts.Host, opts.Port)
217
if err != nil {
218
return nil, err
219
}
220
if !ok {
221
return nil, fmt.Errorf("not a mysql service")
222
}
223
224
dsn, err := BuildDSN(opts)
225
if err != nil {
226
return nil, err
227
}
228
229
db, err := sql.Open("mysql", dsn)
230
if err != nil {
231
return nil, err
232
}
233
defer func() {
234
_ = db.Close()
235
}()
236
db.SetMaxOpenConns(1)
237
db.SetMaxIdleConns(0)
238
239
rows, err := db.Query(query)
240
if err != nil {
241
return nil, err
242
}
243
244
data, err := utils.UnmarshalSQLRows(rows)
245
if err != nil {
246
if len(data.Rows) > 0 {
247
// allow partial results
248
return data, nil
249
}
250
return nil, err
251
}
252
return data, nil
253
}
254
255
// ExecuteQuery connects to Mysql database using given credentials
256
// and executes a query on the db.
257
// @example
258
// ```javascript
259
// const mysql = require('nuclei/mysql');
260
// const result = mysql.ExecuteQuery('acme.com', 3306, 'username', 'password', 'SELECT * FROM users');
261
// log(to_json(result));
262
// ```
263
func (c *MySQLClient) ExecuteQuery(ctx context.Context, host string, port int, username, password, query string) (*utils.SQLResult, error) {
264
// executing queries implies the remote mysql service
265
ok, err := c.IsMySQL(ctx, host, port)
266
if err != nil {
267
return nil, err
268
}
269
if !ok {
270
return nil, fmt.Errorf("not a mysql service")
271
}
272
273
return c.ExecuteQueryWithOpts(ctx, MySQLOptions{
274
Host: host,
275
Port: port,
276
Protocol: "tcp",
277
Username: username,
278
Password: password,
279
}, query)
280
}
281
282
// ExecuteQuery connects to Mysql database using given credentials
283
// and executes a query on the db.
284
// @example
285
// ```javascript
286
// const mysql = require('nuclei/mysql');
287
// const result = mysql.ExecuteQueryOnDB('acme.com', 3306, 'username', 'password', 'dbname', 'SELECT * FROM users');
288
// log(to_json(result));
289
// ```
290
func (c *MySQLClient) ExecuteQueryOnDB(ctx context.Context, host string, port int, username, password, dbname, query string) (*utils.SQLResult, error) {
291
return c.ExecuteQueryWithOpts(ctx, MySQLOptions{
292
Host: host,
293
Port: port,
294
Protocol: "tcp",
295
Username: username,
296
Password: password,
297
DbName: dbname,
298
}, query)
299
}
300
301
func init() {
302
_ = mysql.SetLogger(log.New(io.Discard, "", 0))
303
}
304
305