Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
projectdiscovery
GitHub Repository: projectdiscovery/nuclei
Path: blob/dev/pkg/js/libs/mysql/mysql.go
2852 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(executionId, 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 fingerprint 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(ctx context.Context, dsn string) (bool, error) {
194
executionId := ctx.Value("executionId").(string)
195
return memoizedconnectWithDSN(executionId, dsn)
196
}
197
198
// ExecuteQueryWithOpts connects to Mysql database using given credentials
199
// and executes a query on the db.
200
// @example
201
// ```javascript
202
// const mysql = require('nuclei/mysql');
203
// const options = new mysql.MySQLOptions();
204
// options.Host = 'acme.com';
205
// options.Port = 3306;
206
// const result = mysql.ExecuteQueryWithOpts(options, 'SELECT * FROM users');
207
// log(to_json(result));
208
// ```
209
func (c *MySQLClient) ExecuteQueryWithOpts(ctx context.Context, opts MySQLOptions, query string) (*utils.SQLResult, error) {
210
executionId := ctx.Value("executionId").(string)
211
if !protocolstate.IsHostAllowed(executionId, opts.Host) {
212
// host is not valid according to network policy
213
return nil, protocolstate.ErrHostDenied.Msgf(opts.Host)
214
}
215
216
// executing queries implies the remote mysql service
217
ok, err := c.IsMySQL(ctx, opts.Host, opts.Port)
218
if err != nil {
219
return nil, err
220
}
221
if !ok {
222
return nil, fmt.Errorf("not a mysql service")
223
}
224
225
dsn, err := BuildDSN(opts)
226
if err != nil {
227
return nil, err
228
}
229
230
db, err := sql.Open("mysql", dsn)
231
if err != nil {
232
return nil, err
233
}
234
defer func() {
235
_ = db.Close()
236
}()
237
db.SetMaxOpenConns(1)
238
db.SetMaxIdleConns(0)
239
240
rows, err := db.Query(query)
241
if err != nil {
242
return nil, err
243
}
244
245
data, err := utils.UnmarshalSQLRows(rows)
246
if err != nil {
247
if len(data.Rows) > 0 {
248
// allow partial results
249
return data, nil
250
}
251
return nil, err
252
}
253
return data, nil
254
}
255
256
// ExecuteQuery connects to Mysql database using given credentials
257
// and executes a query on the db.
258
// @example
259
// ```javascript
260
// const mysql = require('nuclei/mysql');
261
// const result = mysql.ExecuteQuery('acme.com', 3306, 'username', 'password', 'SELECT * FROM users');
262
// log(to_json(result));
263
// ```
264
func (c *MySQLClient) ExecuteQuery(ctx context.Context, host string, port int, username, password, query string) (*utils.SQLResult, error) {
265
// executing queries implies the remote mysql service
266
ok, err := c.IsMySQL(ctx, host, port)
267
if err != nil {
268
return nil, err
269
}
270
if !ok {
271
return nil, fmt.Errorf("not a mysql service")
272
}
273
274
return c.ExecuteQueryWithOpts(ctx, MySQLOptions{
275
Host: host,
276
Port: port,
277
Protocol: "tcp",
278
Username: username,
279
Password: password,
280
}, query)
281
}
282
283
// ExecuteQuery connects to Mysql database using given credentials
284
// and executes a query on the db.
285
// @example
286
// ```javascript
287
// const mysql = require('nuclei/mysql');
288
// const result = mysql.ExecuteQueryOnDB('acme.com', 3306, 'username', 'password', 'dbname', 'SELECT * FROM users');
289
// log(to_json(result));
290
// ```
291
func (c *MySQLClient) ExecuteQueryOnDB(ctx context.Context, host string, port int, username, password, dbname, query string) (*utils.SQLResult, error) {
292
return c.ExecuteQueryWithOpts(ctx, MySQLOptions{
293
Host: host,
294
Port: port,
295
Protocol: "tcp",
296
Username: username,
297
Password: password,
298
DbName: dbname,
299
}, query)
300
}
301
302
func init() {
303
_ = mysql.SetLogger(log.New(io.Discard, "", 0))
304
}
305
306