-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathasset.go
114 lines (102 loc) · 2.5 KB
/
asset.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
package main
import (
"encoding/csv"
"os"
"sync"
"time"
)
// An Asset represents an observation of one endpoint seen in network traffic.
//
// Each field is annotated with its JSON field name.
type Asset struct {
IPv4Address string `json:"ipv4_address"`
IPv6Address string `json:"ipv6_address"`
ListensOnPort string `json:"open_port_tcp"`
ConnectsToPort string `json:"connect_port_tcp"`
MACAddress string `json:"mac_address"`
Identifier string `json:"identifier"`
Provenance string `json:"provenance"`
LastSeen time.Time `json:"last_seen"`
ClientID string `json:"client_id"`
}
// AssetCSVWriter contains the state needed to write to a CSV file
type AssetCSVWriter struct {
sync.Mutex
filename string
filehandle *os.File
csvWriter *csv.Writer
}
// NewAssetCSVWriter creates (or overwrites) a file and writes a CSV header.
//
// If filename is "-", write to standard output instead of a file.
func NewAssetCSVWriter(filename string) (*AssetCSVWriter, error) {
// For testing
if filename == "" {
return nil, nil
}
w := new(AssetCSVWriter)
w.filename = filename
if w.filename == "-" {
w.filehandle = os.Stdout
} else {
file, err := os.OpenFile(w.filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return nil, err
}
w.filehandle = file
}
w.csvWriter = csv.NewWriter(w.filehandle)
// Write CSV header
header := []string{
"ipv4_address",
"ipv6_address",
"open_port_tcp",
"connect_port_tcp",
"mac_address",
"identifier",
"provenance",
"last_seen",
"client_id",
}
if err := w.csvWriter.Write(header); err != nil {
return nil, err
}
// Flush buffer to file
w.csvWriter.Flush()
if err := w.csvWriter.Error(); err != nil {
return nil, err
}
return w, nil
}
// Enabled returns true if the writer is enabled
func (w *AssetCSVWriter) Enabled() bool {
return w.filename != ""
}
// Close closes the CSV writer's underlyingfilehandle.
func (w *AssetCSVWriter) Close() {
w.Lock()
defer w.Unlock()
w.filehandle.Close()
}
// Append appends one Asset to a file in CSV format.
func (w *AssetCSVWriter) Append(asset *Asset) error {
w.Lock()
defer w.Unlock()
// Write CSV row
row := []string{
asset.IPv4Address,
asset.IPv6Address,
asset.ConnectsToPort,
asset.MACAddress,
asset.Identifier,
asset.Provenance,
asset.LastSeen.String(),
asset.ClientID,
}
if err := w.csvWriter.Write(row); err != nil {
return err
}
// Flush buffer to file
w.csvWriter.Flush()
return w.csvWriter.Error() // may be nil
}