This repository has been archived by the owner on Sep 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
nessie.go
1093 lines (960 loc) · 28.2 KB
/
nessie.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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package nessie implements a client for the Tenable Nessus 6 API.
package nessie
import (
"bytes"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
)
// Nessus exposes the resources offered via the Tenable Nessus RESTful API.
type Nessus interface {
SetVerbose(bool)
AuthCookie() string
Request(method string, resource string, js interface{}, wantStatus []int) (resp *http.Response, err error)
Login(username, password string) error
Logout() error
Session() (Session, error)
ServerProperties() (*ServerProperties, error)
ServerStatus() (*ServerStatus, error)
CreateUser(username, password, userType, permissions, name, email string) (*User, error)
ListUsers() ([]User, error)
DeleteUser(userID int) error
SetUserPassword(userID int, password string) error
EditUser(userID int, permissions, name, email string) (*User, error)
PluginFamilies() ([]PluginFamily, error)
FamilyDetails(ID int64) (*FamilyDetails, error)
PluginDetails(ID int64) (*PluginDetails, error)
AllPlugins() (chan PluginDetails, error)
Scanners() ([]Scanner, error)
Policies() ([]Policy, error)
CreatePolicy(policySettings CreatePolicyRequest) (CreatePolicyResp, error)
ConfigurePolicy(id int64, policySettings CreatePolicyRequest) error
DeletePolicy(id int64) error
Upload(filePath string) error
AgentGroups() ([]AgentGroup, error)
NewScan(editorTmplUUID, settingsName string, outputFolderID, policyID, scannerID int64, launch string, targets []string) (*Scan, error)
CreateScan(newScanRequest NewScanRequest) (*Scan, error)
Scans() (*ListScansResponse, error)
ScanTemplates() ([]Template, error)
PolicyTemplates() ([]Template, error)
StartScan(scanID int64) (string, error)
PauseScan(scanID int64) error
ResumeScan(scanID int64) error
StopScan(scanID int64) error
DeleteScan(scanID int64) error
ScanDetails(scanID int64) (*ScanDetailsResp, error)
ConfigureScan(scanID int64, scanSetting NewScanRequest) (*Scan, error)
Timezones() ([]TimeZone, error)
Folders() ([]Folder, error)
CreateFolder(name string) error
EditFolder(folderID int64, newName string) error
DeleteFolder(folderID int64) error
ExportScan(scanID int64, format string) (int64, error)
ExportFinished(scanID, exportID int64) (bool, error)
DownloadExport(scanID, exportID int64) ([]byte, error)
Permissions(objectType string, objectID int64) ([]Permission, error)
}
type nessusImpl struct {
// client is the HTTP client to use to issue requests to nessus.
client *http.Client
// authCookie is the login token returned by nessus upon successful login.
authCookie string
apiURL string
// verbose will log requests and responses amongst other helpful debugging things.
verbose bool
}
// NewNessus will return a new Nessus instance, if caCertPath is empty, the host certificate roots will be used to check for the validity of the nessus server API certificate.
func NewNessus(apiURL, caCertPath string) (Nessus, error) {
return newNessus(apiURL, caCertPath, false, false, nil)
}
// NewInsecureNessus will return a nessus instance which does not check for the api certificate validity, do not use in production environment.
func NewInsecureNessus(apiURL string) (Nessus, error) {
return newNessus(apiURL, "", true, false, nil)
}
// NewFingerprintedNessus will return a nessus instance which verifies the api server's certificate by its SHA256 fingerprint (on the RawSubjectPublicKeyInfo and base64 encoded) against a whitelist of good certFingerprints. Fingerprint verification will enable InsecureSkipVerify.
func NewFingerprintedNessus(apiURL string, certFingerprints []string) (Nessus, error) {
return newNessus(apiURL, "", true, true, certFingerprints)
}
func newNessus(apiURL, caCertPath string, ignoreSSLCertsErrors bool, verifyCertFingerprint bool, certFingerprints []string) (Nessus, error) {
var (
dialTLS func(network, addr string) (net.Conn, error)
roots *x509.CertPool
)
config := &tls.Config{
InsecureSkipVerify: ignoreSSLCertsErrors,
RootCAs: roots,
}
if len(caCertPath) != 0 {
roots = x509.NewCertPool()
rootPEM, err := ioutil.ReadFile(caCertPath)
if err != nil {
return nil, err
}
ok := roots.AppendCertsFromPEM(rootPEM)
if !ok {
return nil, fmt.Errorf("could not append certs from PEM %s", caCertPath)
}
} else if verifyCertFingerprint == true {
if len(certFingerprints) == 0 {
return nil, fmt.Errorf("fingerprint verification enabled, fingerprint must not be empty")
}
dialTLS = createDialTLSFuncToVerifyFingerprint(certFingerprints, config)
}
return &nessusImpl{
apiURL: apiURL,
client: &http.Client{
Transport: &http.Transport{
TLSClientConfig: config,
DialTLS: dialTLS,
},
},
}, nil
}
func sha256Fingerprint(data []byte) string {
h := sha256.New()
h.Write(data)
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
func createDialTLSFuncToVerifyFingerprint(certFingerprints []string, config *tls.Config) func(network, addr string) (net.Conn, error) {
return func(network, addr string) (net.Conn, error) {
conn, err := tls.Dial(network, addr, config)
if err != nil {
return nil, err
}
state := conn.ConnectionState()
// Only check the first cert in the chain. The TLS server must send its cert first (RFC5246), and this first cert is authenticated with a check for proof of private key possesion.
peerFingerprint := sha256Fingerprint(state.PeerCertificates[0].RawSubjectPublicKeyInfo)
for _, fingerprint := range certFingerprints {
if peerFingerprint == fingerprint {
return conn, nil
}
}
conn.Close()
return nil, fmt.Errorf("no server certificate with fingerprints %v was found", certFingerprints)
}
}
func (n *nessusImpl) SetVerbose(verbosity bool) {
n.verbose = verbosity
}
func (n *nessusImpl) AuthCookie() string {
return n.authCookie
}
// Request make a request to Nessus
func (n *nessusImpl) Request(method string, resource string, js interface{}, wantStatus []int) (resp *http.Response, err error) {
u, err := url.ParseRequestURI(n.apiURL)
if err != nil {
return nil, err
}
// Note: resource doesn't support '?' due to https://golang.org/pkg/net/url/#PathEscape
// In order to not break this API, we'll split the resource by '?' here
// when resource = "/agents?filter.0.filter=status&filter.0.quality=neq&filter.0.value=online"
// split resource to:
// 1. Path = "/agents"
// 2. RawQuery = "filter.0.filter=status&filter.0.quality=neq&filter.0.value=online"
if idx := strings.IndexByte(resource, '?'); -1 != idx {
u.Path = resource[:idx]
u.RawQuery = resource[idx+1:]
} else {
u.Path = resource
}
urlStr := fmt.Sprintf("%v", u)
jb, err := json.Marshal(js)
if err != nil {
return nil, err
}
req, err := http.NewRequest(method, urlStr, bytes.NewBufferString(string(jb)))
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
if n.authCookie != "" {
req.Header.Add("X-Cookie", fmt.Sprintf("token=%s", n.authCookie))
}
if n.verbose {
db, err := httputil.DumpRequest(req, true)
if err != nil {
return nil, err
}
log.Println("sending data:", string(db))
}
resp, err = n.client.Do(req)
if err != nil {
return nil, err
}
if n.verbose {
if body, err := httputil.DumpResponse(resp, true); err == nil {
log.Println(string(body))
}
}
var statusFound bool
for _, status := range wantStatus {
if resp.StatusCode == status {
statusFound = true
break
}
}
if !statusFound {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return nil, fmt.Errorf("Unexpected status code, got %d wanted %v (%s)", resp.StatusCode, wantStatus, body)
}
return resp, nil
}
// Login will log into nessus with the username and passwords given from the command line flags.
func (n *nessusImpl) Login(username, password string) error {
if n.verbose {
log.Printf("Login into %s\n", n.apiURL)
}
data := loginRequest{
Username: username,
Password: password,
}
resp, err := n.Request("POST", "/session", data, []int{http.StatusOK})
if err != nil {
return err
}
defer resp.Body.Close()
reply := &loginResp{}
if err = json.NewDecoder(resp.Body).Decode(&reply); err != nil {
return err
}
n.authCookie = reply.Token
return nil
}
// Logout will invalidate the current session token.
func (n *nessusImpl) Logout() error {
if n.authCookie == "" {
log.Println("Not logged in, nothing to do to logout...")
return nil
}
if n.verbose {
log.Println("Logout...")
}
if _, err := n.Request("DELETE", "/session", nil, []int{http.StatusOK}); err != nil {
return err
}
n.authCookie = ""
return nil
}
// Session will return the details for the current session.
func (n *nessusImpl) Session() (Session, error) {
if n.verbose {
log.Printf("Getting details for current session...")
}
resp, err := n.Request("GET", "/session", nil, []int{http.StatusOK})
if err != nil {
return Session{}, err
}
defer resp.Body.Close()
var reply Session
if err = json.NewDecoder(resp.Body).Decode(&reply); err != nil {
return Session{}, err
}
return reply, nil
}
// ServerProperties will return the current state of the nessus instance.
func (n *nessusImpl) ServerProperties() (*ServerProperties, error) {
if n.verbose {
log.Println("Server properties...")
}
resp, err := n.Request("GET", "/server/properties", nil, []int{http.StatusOK})
if err != nil {
return nil, err
}
defer resp.Body.Close()
reply := &ServerProperties{}
if err = json.NewDecoder(resp.Body).Decode(&reply); err != nil {
return nil, err
}
return reply, nil
}
// ServerStatus will return the current status of the nessus instance.
func (n *nessusImpl) ServerStatus() (*ServerStatus, error) {
if n.verbose {
log.Println("Server status...")
}
resp, err := n.Request("GET", "/server/status", nil, []int{http.StatusOK, http.StatusServiceUnavailable})
if err != nil {
return nil, err
}
defer resp.Body.Close()
reply := &ServerStatus{}
if err = json.NewDecoder(resp.Body).Decode(&reply); err != nil {
return nil, err
}
if resp.StatusCode == http.StatusServiceUnavailable {
reply.MustDestroySession = true
}
return reply, nil
}
const (
UserTypeLocal = "local"
UserTypeLDAP = "ldap"
Permissions0 = "0"
Permissions16 = "16"
Permissions32 = "32"
Permissions64 = "64"
Permissions128 = "128"
)
// CreateUser will register a new user with the nessus instance.
// Name and email can be empty.
func (n *nessusImpl) CreateUser(username, password, userType, permissions, name, email string) (*User, error) {
if n.verbose {
log.Println("Creating new user...")
}
data := createUserRequest{
Username: username,
Password: password,
Permissions: permissions,
Type: userType,
}
if name != "" {
data.Name = name
}
if email != "" {
data.Email = email
}
resp, err := n.Request("POST", "/users", data, []int{http.StatusOK})
if err != nil {
return nil, err
}
defer resp.Body.Close()
reply := &User{}
if err = json.NewDecoder(resp.Body).Decode(&reply); err != nil {
return nil, err
}
return reply, nil
}
// ListUsers will return the list of users on this nessus instance.
func (n *nessusImpl) ListUsers() ([]User, error) {
if n.verbose {
log.Println("Listing users...")
}
resp, err := n.Request("GET", "/users", nil, []int{http.StatusOK})
if err != nil {
return nil, err
}
defer resp.Body.Close()
reply := &listUsersResp{}
if err = json.NewDecoder(resp.Body).Decode(&reply); err != nil {
return nil, err
}
return reply.Users, nil
}
// DeleteUser will remove a user from this nessus instance.
func (n *nessusImpl) DeleteUser(userID int) error {
if n.verbose {
log.Println("Deleting user...")
}
_, err := n.Request("DELETE", fmt.Sprintf("/users/%d", userID), nil, []int{http.StatusOK})
return err
}
// SetUserPassword will change the password for the given user.
func (n *nessusImpl) SetUserPassword(userID int, password string) error {
if n.verbose {
log.Println("Changing password of user...")
}
data := setUserPasswordRequest{
Password: password,
}
_, err := n.Request("PUT", fmt.Sprintf("/users/%d/chpasswd", userID), data, []int{http.StatusOK})
return err
}
// EditUser will edit certain information about a user.
// Any non empty parameter will be set.
func (n *nessusImpl) EditUser(userID int, permissions, name, email string) (*User, error) {
if n.verbose {
log.Println("Editing user...")
}
data := editUserRequest{}
if permissions != "" {
data.Permissions = permissions
}
if name != "" {
data.Name = name
}
if email != "" {
data.Email = email
}
resp, err := n.Request("PUT", fmt.Sprintf("/users/%d", userID), data, []int{http.StatusOK})
if err != nil {
return nil, err
}
defer resp.Body.Close()
reply := &User{}
if err = json.NewDecoder(resp.Body).Decode(&reply); err != nil {
return nil, err
}
return reply, nil
}
func (n *nessusImpl) PluginFamilies() ([]PluginFamily, error) {
if n.verbose {
log.Println("Getting list of plugin families...")
}
resp, err := n.Request("GET", "/plugins/families", nil, []int{http.StatusOK})
if err != nil {
return nil, err
}
defer resp.Body.Close()
var reply PluginFamilies
if err = json.NewDecoder(resp.Body).Decode(&reply); err != nil {
return nil, err
}
return reply.Families, nil
}
func (n *nessusImpl) FamilyDetails(ID int64) (*FamilyDetails, error) {
if n.verbose {
log.Println("Getting details of family...")
}
resp, err := n.Request("GET", fmt.Sprintf("/plugins/families/%d", ID), nil, []int{http.StatusOK})
if err != nil {
return nil, err
}
defer resp.Body.Close()
reply := &FamilyDetails{}
if err = json.NewDecoder(resp.Body).Decode(&reply); err != nil {
return nil, err
}
return reply, nil
}
func (n *nessusImpl) PluginDetails(ID int64) (*PluginDetails, error) {
if n.verbose {
log.Println("Getting details plugin...")
}
resp, err := n.Request("GET", fmt.Sprintf("/plugins/plugin/%d", ID), nil, []int{http.StatusOK})
if err != nil {
return nil, err
}
defer resp.Body.Close()
reply := &PluginDetails{}
if err = json.NewDecoder(resp.Body).Decode(&reply); err != nil {
return nil, err
}
return reply, nil
}
func (n *nessusImpl) Scanners() ([]Scanner, error) {
if n.verbose {
log.Println("Getting scanners list...")
}
resp, err := n.Request("GET", "/scanners", nil, []int{http.StatusOK})
if err != nil {
return nil, err
}
defer resp.Body.Close()
var reply struct {
Scanners []Scanner `json:"scanners"`
}
if err = json.NewDecoder(resp.Body).Decode(&reply); err != nil {
return nil, err
}
return reply.Scanners, nil
}
// AllPlugin wil hammer nessus asking for details of every plugins available and feeding them in
// the returned channel.
// Getting all the plugins is slow (usually takes a few minutes on a decent machine).
func (n *nessusImpl) AllPlugins() (chan PluginDetails, error) {
plugChan := make(chan PluginDetails, 20)
families, err := n.PluginFamilies()
if err != nil {
return nil, err
}
idChan := make(chan int64, 20)
var wgf sync.WaitGroup
var wgp sync.WaitGroup
// Launch a goroutine per family to get all the plugins of those families.
for _, family := range families {
wgf.Add(1)
go func(famID int64) {
defer wgf.Done()
famDetails, err := n.FamilyDetails(famID)
if err != nil {
return
}
for _, plugin := range famDetails.Plugins {
wgp.Add(1)
idChan <- plugin.ID
}
}(family.ID)
}
// Launch our workers getting individual plugin details.
for i := 0; i < 10; i++ {
go func() {
for id := range idChan {
plugin, err := n.PluginDetails(id)
if err != nil {
wgp.Done()
continue
}
plugChan <- *plugin
wgp.Done()
}
}()
}
go func() {
wgf.Wait()
// Once we finished adding all the plugin IDs, we can close the channel.
close(idChan)
// Once all the plugins have been returned, we can close the plugin channel
// to let the receiver know.
wgp.Wait()
close(plugChan)
}()
return plugChan, nil
}
func (n *nessusImpl) Policies() ([]Policy, error) {
if n.verbose {
log.Println("Getting policies list...")
}
resp, err := n.Request("GET", "/policies", nil, []int{http.StatusOK})
if err != nil {
return nil, err
}
defer resp.Body.Close()
var reply listPoliciesResp
if err = json.NewDecoder(resp.Body).Decode(&reply); err != nil {
return nil, err
}
return reply.Policies, nil
}
const (
LaunchOnDemand = "ON_DEMAND"
LaunchDaily = "DAILY"
LaunchWeekly = "WEEKLY"
LaunchMonthly = "MONTHLY"
LaunchYearly = "YEARLY"
)
func (n *nessusImpl) NewScan(
editorTmplUUID string,
settingsName string,
outputFolderID int64,
policyID int64,
scannerID int64,
launch string,
targets []string) (*Scan, error) {
data := NewScanRequest{
UUID: editorTmplUUID,
Settings: ScanSettingsRequest{
Name: settingsName,
Description: "Some description",
FolderID: outputFolderID,
ScannerID: scannerID,
PolicyID: policyID,
Launch: launch,
TextTargets: strings.Join(targets, ", "),
},
}
return n.CreateScan(data)
}
func (n *nessusImpl) CreateScan(newScanRequest NewScanRequest) (*Scan, error) {
if n.verbose {
log.Println("Creating a new scan...")
}
resp, err := n.Request("POST", "/scans", newScanRequest, []int{http.StatusOK})
if err != nil {
return nil, err
}
defer resp.Body.Close()
reply := struct {
Scan Scan `json:"scan"`
}{}
if err = json.NewDecoder(resp.Body).Decode(&reply); err != nil {
return nil, err
}
return &reply.Scan, nil
}
func (n *nessusImpl) Scans() (*ListScansResponse, error) {
if n.verbose {
log.Println("Getting scans list...")
}
resp, err := n.Request("GET", "/scans", nil, []int{http.StatusOK})
if err != nil {
return nil, err
}
defer resp.Body.Close()
reply := &ListScansResponse{}
if err = json.NewDecoder(resp.Body).Decode(&reply); err != nil {
return nil, err
}
return reply, nil
}
func (n *nessusImpl) ScanTemplates() ([]Template, error) {
if n.verbose {
log.Println("Getting scans templates...")
}
resp, err := n.Request("GET", "/editor/scan/templates", nil, []int{http.StatusOK})
if err != nil {
return nil, err
}
defer resp.Body.Close()
reply := &listTemplatesResp{}
if err = json.NewDecoder(resp.Body).Decode(&reply); err != nil {
return nil, err
}
return reply.Templates, nil
}
func (n *nessusImpl) PolicyTemplates() ([]Template, error) {
if n.verbose {
log.Println("Getting policy templates...")
}
resp, err := n.Request("GET", "/editor/policy/templates", nil, []int{http.StatusOK})
if err != nil {
return nil, err
}
defer resp.Body.Close()
reply := &listTemplatesResp{}
if err = json.NewDecoder(resp.Body).Decode(&reply); err != nil {
return nil, err
}
return reply.Templates, nil
}
// StartScan starts the given scan and returns its UUID.
func (n *nessusImpl) StartScan(scanID int64) (string, error) {
if n.verbose {
log.Println("Starting scan...")
}
resp, err := n.Request("POST", fmt.Sprintf("/scans/%d/launch", scanID), nil, []int{http.StatusOK})
if err != nil {
return "", err
}
defer resp.Body.Close()
reply := &startScanResp{}
if err = json.NewDecoder(resp.Body).Decode(&reply); err != nil {
return "", err
}
return reply.UUID, nil
}
func (n *nessusImpl) PauseScan(scanID int64) error {
if n.verbose {
log.Println("Pausing scan...")
}
_, err := n.Request("POST", fmt.Sprintf("/scans/%d/pause", scanID), nil, []int{http.StatusOK})
return err
}
func (n *nessusImpl) ResumeScan(scanID int64) error {
if n.verbose {
log.Println("Resume scan...")
}
_, err := n.Request("POST", fmt.Sprintf("/scans/%d/resume", scanID), nil, []int{http.StatusOK})
return err
}
func (n *nessusImpl) StopScan(scanID int64) error {
if n.verbose {
log.Println("Stop scan...")
}
_, err := n.Request("POST", fmt.Sprintf("/scans/%d/stop", scanID), nil, []int{http.StatusOK})
return err
}
func (n *nessusImpl) DeleteScan(scanID int64) error {
if n.verbose {
log.Println("Deleting scan...")
}
_, err := n.Request("DELETE", fmt.Sprintf("/scans/%d", scanID), nil, []int{http.StatusOK})
return err
}
func (n *nessusImpl) ScanDetails(scanID int64) (*ScanDetailsResp, error) {
if n.verbose {
log.Println("Getting details about a scan...")
}
resp, err := n.Request("GET", fmt.Sprintf("/scans/%d", scanID), nil, []int{http.StatusOK})
if err != nil {
return nil, err
}
defer resp.Body.Close()
reply := &ScanDetailsResp{}
if err = json.NewDecoder(resp.Body).Decode(&reply); err != nil {
return nil, err
}
return reply, nil
}
func (n *nessusImpl) ConfigureScan(scanID int64, scanSetting NewScanRequest) (*Scan, error) {
if n.verbose {
log.Println("Configuring a scan...")
}
resp, err := n.Request("PUT", fmt.Sprintf("/scans/%d", scanID), scanSetting, []int{http.StatusOK})
if nil != err {
return nil, err
}
defer resp.Body.Close()
reply := &Scan{}
if err = json.NewDecoder(resp.Body).Decode(&reply); nil != err {
return nil, err
}
return reply, nil
}
func (n *nessusImpl) Timezones() ([]TimeZone, error) {
if n.verbose {
log.Println("Getting list of timezones...")
}
resp, err := n.Request("GET", "/scans/timezones", nil, []int{http.StatusOK})
if err != nil {
return nil, err
}
defer resp.Body.Close()
reply := &tzResp{}
if err = json.NewDecoder(resp.Body).Decode(&reply); err != nil {
return nil, err
}
return reply.Timezones, nil
}
func (n *nessusImpl) Folders() ([]Folder, error) {
if n.verbose {
log.Println("Getting list of folders...")
}
resp, err := n.Request("GET", "/folders", nil, []int{http.StatusOK})
if err != nil {
return nil, err
}
defer resp.Body.Close()
reply := &listFoldersResp{}
if err = json.NewDecoder(resp.Body).Decode(&reply); err != nil {
return nil, err
}
return reply.Folders, nil
}
func (n *nessusImpl) CreateFolder(name string) error {
if n.verbose {
log.Println("Creating folders...")
}
req := createFolderRequest{Name: name}
_, err := n.Request("POST", "/folders", req, []int{http.StatusOK})
return err
}
func (n *nessusImpl) EditFolder(folderID int64, newName string) error {
if n.verbose {
log.Println("Editing folders...")
}
req := editFolderRequest{Name: newName}
_, err := n.Request("PUT", fmt.Sprintf("/folders/%d", folderID), req, []int{http.StatusOK})
return err
}
func (n *nessusImpl) DeleteFolder(folderID int64) error {
if n.verbose {
log.Println("Deleting folders...")
}
_, err := n.Request("DELETE", fmt.Sprintf("/folders/%d", folderID), nil, []int{http.StatusOK})
return err
}
const (
ExportNessus = "nessus"
ExportPDF = "pdf"
ExportHTML = "html"
ExportCSV = "csv"
ExportDB = "db"
)
// ExportScan exports a scan to a File resource.
// Call ExportStatus to get the status of the export and call Download() to download the actual file.
func (n *nessusImpl) ExportScan(scanID int64, format string) (int64, error) {
if n.verbose {
log.Println("Exporting scan...")
}
req := exportScanRequest{Format: format}
resp, err := n.Request("POST", fmt.Sprintf("/scans/%d/export", scanID), req, []int{http.StatusOK})
if err != nil {
return 0, err
}
defer resp.Body.Close()
reply := &exportScanResp{}
if err = json.NewDecoder(resp.Body).Decode(&reply); err != nil {
return 0, err
}
return reply.File, nil
}
// ExportFinished returns whether the given scan export file has finished being prepared.
func (n *nessusImpl) ExportFinished(scanID, exportID int64) (bool, error) {
if n.verbose {
log.Println("Getting export status...")
}
resp, err := n.Request("GET", fmt.Sprintf("/scans/%d/export/%d/status", scanID, exportID), nil, []int{http.StatusOK})
if err != nil {
return false, err
}
defer resp.Body.Close()
reply := &exportStatusResp{}
if err = json.NewDecoder(resp.Body).Decode(&reply); err != nil {
return false, err
}
return reply.Status == "ready", nil
}
// DownloadExport will download the given export from nessus.
func (n *nessusImpl) DownloadExport(scanID, exportID int64) ([]byte, error) {
if n.verbose {
log.Println("Downloading export file...")
}
resp, err := n.Request("GET", fmt.Sprintf("/scans/%d/export/%d/download", scanID, exportID), nil, []int{http.StatusOK})
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil {
return nil, err
}
return body, err
}
// TODO: Currently returns a 404... not exposed yet?
func (n *nessusImpl) ListGroups() ([]Group, error) {
if n.verbose {
log.Println("Listing groups...")
}
resp, err := n.Request("GET", "/groups", nil, []int{http.StatusOK})
if err != nil {
return nil, err
}
defer resp.Body.Close()
reply := &listGroupsResp{}
if err = json.NewDecoder(resp.Body).Decode(&reply); err != nil {
return nil, err
}
return reply.Groups, nil
}
// TODO: Currently returns a 404... not exposed yet?
func (n *nessusImpl) CreateGroup(name string) (Group, error) {
if n.verbose {
log.Println("Creating a group...")
}
req := createGroupRequest{
Name: name,
}
resp, err := n.Request("POST", "/groups", req, []int{http.StatusOK})
if err != nil {
return Group{}, err
}
defer resp.Body.Close()
var reply Group
if err = json.NewDecoder(resp.Body).Decode(&reply); err != nil {
return Group{}, err
}
return reply, nil
}
func (n *nessusImpl) Permissions(objectType string, objectID int64) ([]Permission, error) {
if n.verbose {
log.Println("Creating a group...")
}
resp, err := n.Request("GET", fmt.Sprintf("/permissions/%s/%d", objectType, objectID), nil, []int{http.StatusOK})
if err != nil {
return nil, err
}
defer resp.Body.Close()
var reply []Permission
if err = json.NewDecoder(resp.Body).Decode(&reply); err != nil {
return nil, err
}
return reply, nil
}
// CreatePolicy Create a policy.
func (n *nessusImpl) CreatePolicy(createPolicyRequest CreatePolicyRequest) (CreatePolicyResp, error) {
if n.verbose {
log.Println("Creating a policy...")
}
resp, err := n.Request("POST", "/policies", createPolicyRequest, []int{http.StatusOK})
if err != nil {
return CreatePolicyResp{}, err
}
defer resp.Body.Close()
var reply CreatePolicyResp
if err = json.NewDecoder(resp.Body).Decode(&reply); err != nil {
return CreatePolicyResp{}, err
}
return reply, nil
}
// ConfigurePolicy Changes the parameters of a policy.
func (n *nessusImpl) ConfigurePolicy(policyID int64, createPolicyRequest CreatePolicyRequest) error {
if n.verbose {
log.Println("Configuring a policy...")
}
_, err := n.Request("PUT", fmt.Sprintf("/policies/%d", policyID), createPolicyRequest, []int{http.StatusOK})