Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
projectdiscovery
GitHub Repository: projectdiscovery/nuclei
Path: blob/dev/pkg/protocols/whois/whois.go
2070 views
1
package whois
2
3
import (
4
"net/url"
5
"strings"
6
"time"
7
8
jsoniter "github.com/json-iterator/go"
9
"github.com/pkg/errors"
10
"github.com/projectdiscovery/rdap"
11
12
"github.com/projectdiscovery/gologger"
13
"github.com/projectdiscovery/nuclei/v3/pkg/operators"
14
"github.com/projectdiscovery/nuclei/v3/pkg/operators/extractors"
15
"github.com/projectdiscovery/nuclei/v3/pkg/operators/matchers"
16
"github.com/projectdiscovery/nuclei/v3/pkg/output"
17
"github.com/projectdiscovery/nuclei/v3/pkg/protocols"
18
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/contextargs"
19
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/generators"
20
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/helpers/eventcreator"
21
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/helpers/responsehighlighter"
22
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/replacer"
23
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/utils/vardump"
24
protocolutils "github.com/projectdiscovery/nuclei/v3/pkg/protocols/utils"
25
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/whois/rdapclientpool"
26
templateTypes "github.com/projectdiscovery/nuclei/v3/pkg/templates/types"
27
28
"github.com/projectdiscovery/nuclei/v3/pkg/types"
29
)
30
31
// Request is a request for the WHOIS protocol
32
type Request struct {
33
// Operators for the current request go here.
34
operators.Operators `yaml:",inline,omitempty" json:",inline,omitempty"`
35
CompiledOperators *operators.Operators `yaml:"-" json:"-"`
36
37
// ID is the optional id of the request
38
ID string `yaml:"id,omitempty" json:"id,omitempty" jsonschema:"title=id of the request,description=ID of the network request"`
39
40
// description: |
41
// Query contains query for the request
42
Query string `yaml:"query,omitempty" json:"query,omitempty" jsonschema:"title=query for the WHOIS request,description=Query contains query for the request"`
43
44
// description: |
45
// Optional WHOIS server URL.
46
//
47
// If present, specifies the WHOIS server to execute the Request on.
48
// Otherwise, nil enables bootstrapping
49
Server string `yaml:"server,omitempty" json:"server,omitempty" jsonschema:"title=server url to execute the WHOIS request on,description=Server contains the server url to execute the WHOIS request on"`
50
// cache any variables that may be needed for operation.
51
client *rdap.Client
52
options *protocols.ExecutorOptions
53
parsedServerURL *url.URL
54
}
55
56
// Compile compiles the request generators preparing any requests possible.
57
func (request *Request) Compile(options *protocols.ExecutorOptions) error {
58
var err error
59
if request.Server != "" {
60
request.parsedServerURL, err = url.Parse(request.Server)
61
if err != nil {
62
return errors.Wrap(err, "failed to parse server URL")
63
}
64
}
65
66
request.options = options
67
request.client, _ = rdapclientpool.Get(options.Options, nil)
68
69
if len(request.Matchers) > 0 || len(request.Extractors) > 0 {
70
compiled := &request.Operators
71
compiled.ExcludeMatchers = options.ExcludeMatchers
72
compiled.TemplateID = options.TemplateID
73
if err := compiled.Compile(); err != nil {
74
return errors.Wrap(err, "could not compile operators")
75
}
76
request.CompiledOperators = compiled
77
}
78
return nil
79
}
80
81
// Requests returns the total number of requests the rule will perform
82
func (request *Request) Requests() int {
83
return 1
84
}
85
86
// GetID returns the ID for the request if any.
87
func (request *Request) GetID() string {
88
return ""
89
}
90
91
// ExecuteWithResults executes the protocol requests and returns results instead of writing them.
92
func (request *Request) ExecuteWithResults(input *contextargs.Context, dynamicValues, previous output.InternalEvent, callback protocols.OutputEventCallback) error {
93
// generate variables
94
defaultVars := protocolutils.GenerateVariables(input.MetaInput.Input, false, nil)
95
optionVars := generators.BuildPayloadFromOptions(request.options.Options)
96
// add templatectx variables to varMap
97
vars := request.options.Variables.Evaluate(generators.MergeMaps(defaultVars, optionVars, dynamicValues, request.options.GetTemplateCtx(input.MetaInput).GetAll()))
98
99
variables := generators.MergeMaps(vars, defaultVars, optionVars, dynamicValues, request.options.Constants)
100
101
if vardump.EnableVarDump {
102
gologger.Debug().Msgf("Whois Protocol request variables: %s\n", vardump.DumpVariables(variables))
103
}
104
105
// and replace placeholders
106
query := replacer.Replace(request.Query, variables)
107
// build an rdap request
108
rdapReq := rdap.NewAutoRequest(query)
109
rdapReq.Server = request.parsedServerURL
110
res, err := request.client.Do(rdapReq)
111
if err != nil {
112
return errors.Wrap(err, "could not make whois request")
113
}
114
gologger.Verbose().Msgf("Sent WHOIS request to %s", query)
115
if request.options.Options.Debug || request.options.Options.DebugRequests {
116
gologger.Debug().Msgf("[%s] Dumped WHOIS request for %s", request.options.TemplateID, query)
117
}
118
119
data := make(map[string]interface{})
120
var response interface{}
121
switch rdapReq.Type {
122
case rdap.DomainRequest:
123
// convert the rdap response to a whois style response (for domain request type only)
124
whoisResp := res.ToWhoisStyleResponse()
125
for k, v := range whoisResp.Data {
126
data[strings.ToLower(k)] = strings.Join(v, ",")
127
}
128
response = whoisResp
129
default:
130
response = res.Object
131
}
132
jsonData, _ := jsoniter.Marshal(response)
133
jsonDataString := string(jsonData)
134
135
data["type"] = request.Type().String()
136
data["host"] = query
137
data["response"] = jsonDataString
138
139
// add response fields to template context and merge templatectx variables to output event
140
request.options.AddTemplateVars(input.MetaInput, request.Type(), request.ID, data)
141
data = generators.MergeMaps(data, request.options.GetTemplateCtx(input.MetaInput).GetAll())
142
143
event := eventcreator.CreateEvent(request, data, request.options.Options.Debug || request.options.Options.DebugResponse)
144
if request.options.Options.Debug || request.options.Options.DebugResponse {
145
gologger.Debug().Msgf("[%s] Dumped WHOIS response for %s", request.options.TemplateID, query)
146
gologger.Print().Msgf("%s", responsehighlighter.Highlight(event.OperatorsResult, jsonDataString, request.options.Options.NoColor, false))
147
}
148
149
callback(event)
150
return nil
151
}
152
153
// Match performs matching operation for a matcher on model and returns:
154
// true and a list of matched snippets if the matcher type is supports it
155
// otherwise false and an empty string slice
156
func (request *Request) Match(data map[string]interface{}, matcher *matchers.Matcher) (bool, []string) {
157
return protocols.MakeDefaultMatchFunc(data, matcher)
158
}
159
160
// Extract performs extracting operation for an extractor on model and returns true or false.
161
func (request *Request) Extract(data map[string]interface{}, matcher *extractors.Extractor) map[string]struct{} {
162
return protocols.MakeDefaultExtractFunc(data, matcher)
163
}
164
165
// MakeResultEvent creates a result event from internal wrapped event
166
func (request *Request) MakeResultEvent(wrapped *output.InternalWrappedEvent) []*output.ResultEvent {
167
return protocols.MakeDefaultResultEvent(request, wrapped)
168
}
169
170
// GetCompiledOperators returns a list of the compiled operators
171
func (request *Request) GetCompiledOperators() []*operators.Operators {
172
return []*operators.Operators{request.CompiledOperators}
173
}
174
175
func (request *Request) MakeResultEventItem(wrapped *output.InternalWrappedEvent) *output.ResultEvent {
176
data := &output.ResultEvent{
177
TemplateID: types.ToString(request.options.TemplateID),
178
TemplatePath: types.ToString(request.options.TemplatePath),
179
Info: request.options.TemplateInfo,
180
TemplateVerifier: request.options.TemplateVerifier,
181
Type: types.ToString(wrapped.InternalEvent["type"]),
182
Host: types.ToString(wrapped.InternalEvent["host"]),
183
Metadata: wrapped.OperatorsResult.PayloadValues,
184
ExtractedResults: wrapped.OperatorsResult.OutputExtracts,
185
Timestamp: time.Now(),
186
MatcherStatus: true,
187
Request: types.ToString(wrapped.InternalEvent["request"]),
188
Response: types.ToString(wrapped.InternalEvent["response"]),
189
TemplateEncoded: request.options.EncodeTemplate(),
190
Error: types.ToString(wrapped.InternalEvent["error"]),
191
}
192
return data
193
}
194
195
// Type returns the type of the protocol request
196
func (request *Request) Type() templateTypes.ProtocolType {
197
return templateTypes.WHOISProtocol
198
}
199
200
// UpdateOptions replaces this request's options with a new copy
201
func (r *Request) UpdateOptions(opts *protocols.ExecutorOptions) {
202
r.options.ApplyNewEngineOptions(opts)
203
}
204
205