trustar

package module
v0.0.0-...-2ef8f31 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 4, 2019 License: MIT Imports: 12 Imported by: 1

README

trustar-golang

Build Status GoDoc MIT License Go Report Card PRs Welcome

Golang SDK for the TruSTAR API

API Documentation

See https://docs.trustar.co/api/index.html for the official documentation to the TruSTAR API.

Example

Get reports from an enclave
package main

import (
	"net/url"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/davecgh/go-spew/spew"
	trustar "github.com/jakewarren/trustar-golang"
	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
)

func main() {
	log.Logger = zerolog.New(zerolog.ConsoleWriter{Out: os.Stderr}).With().Caller().Timestamp().Logger()
	
	// set the list of enclave IDs we want to pull from
	enclaveIDs := []string{"abc-123-def"}

	// initialize the client with our API auth information
	c, err := trustar.NewClient("TruSTAR API Key goes here", "TruSTAR API Secret goes here", trustar.APIBaseLive)
	if err != nil {
		log.Fatal().Err(err).Msg("error creating client")
	}

	// acquire the access token
	_, err = c.GetAccessToken()
	if err != nil {
		log.Fatal().Err(err).Msg("error while getting access token")
	}

	t := time.Now().Add(-24 * time.Hour)

	// build the request and send it
	query := url.Values{}
	query.Add("from", strconv.FormatInt(timeToMsEpoch(t), 10)) // request reports from the past 24 hours
	query.Add("enclaveIds", strings.Join(enclaveIDs, ","))
	reports, err := c.GetReports(query)

	// print out the reports we received
	spew.Dump(reports)
}

// convert time.Time to milliseconds epoch string
func timeToMsEpoch(t time.Time) int64 {
	return t.UnixNano() / int64(time.Millisecond)
}

Roadmap

Implemented endpoints can be found in TODO.md

Disclaimer

This project is currently in alpha status. Breaking changes are possible and the project has not been thoroughly tested.

Acknowledgements

The overall design of this client is based upon logpacker/PayPal-Go-SDK

License

MIT © 2019 Jake Warren

Documentation

Index

Constants

View Source
const (
	// APIBaseLive points to the live version of the API and the current stable version that's supported
	APIBaseLive = "https://api.trustar.co/api/1.3/"

	// RequestNewTokenBeforeExpiresIn is used by SendWithAuth and try to get new Token when it's about to expire
	RequestNewTokenBeforeExpiresIn = time.Duration(60) * time.Second
)

Variables

This section is empty.

Functions

func MsEpochToTime

func MsEpochToTime(msInt int64) (time.Time, error)

MsEpochToTime converts millisecond epoch int to time.Time

func TimeToMsEpoch

func TimeToMsEpoch(t time.Time) int64

TimeToMsEpoch converts time.Time to milliseconds epoch string

Types

type Client

type Client struct {
	sync.Mutex
	Client   *http.Client
	ClientID string
	Secret   string
	APIBase  string
	Log      io.Writer // If user set log file name all requests will be logged there
	Token    *TokenResponse
	// contains filtered or unexported fields
}

Client represents a TruSTAR REST API Client

func NewClient

func NewClient(clientID string, secret string, APIBase string) (*Client, error)

NewClient returns new Client struct APIBase is a base API URL

func (*Client) DeleteFromWhitelist

func (c *Client) DeleteFromWhitelist(v url.Values) error

DeleteFromWhitelist Delete an indicator from the user’s company whitelist.

Endpoint: DELETE /1.3/whitelist

func (*Client) DeleteReport

func (c *Client) DeleteReport(id string) error

DeleteReport Delete a report with the specified Trustar report ID.

Endpoint: DELETE /1.3/reports/{ID}

func (*Client) FindCorrelatedReports

func (c *Client) FindCorrelatedReports(v url.Values) (CorrelatedReportResponse, error)

FindCorrelatedReports Returns a paginated list of all reports that contain any of the provided indicator values.

Endpoint: GET /1.3/reports/correlated

func (*Client) FindRelatedIndicators

func (c *Client) FindRelatedIndicators(v url.Values) (RelatedIndicatorsResponse, error)

FindRelatedIndicators Search all TruSTAR incident reports for provided indicators and return all correlated indicators from search results. Two indicators are considered “correlated” if they can be found in a common report.

Endpoint: GET /1.3/indicators/related

func (*Client) GetAccessToken

func (c *Client) GetAccessToken() (*TokenResponse, error)

GetAccessToken returns struct of TokenResponse No need to call SetAccessToken to apply new access token for current Client Endpoint: POST /v1/oauth2/token

func (*Client) GetEnclaves

func (c *Client) GetEnclaves() ([]Enclave, error)

GetEnclaves Returns the list of all enclaves that the user has access to, as well as whether they can read, create, and update reports in that enclave.

Endpoint: GET /1.3/enclaves

func (*Client) GetIndicatorMetadata

func (c *Client) GetIndicatorMetadata(indicators []Indicator) (IndicatorMetadataResponse, error)

GetIndicatorMetadata Provide metadata associated with an indicator

Endpoint: POST /1.3/indicators/metadata

func (*Client) GetReportDetails

func (c *Client) GetReportDetails(id string) (ReportDetails, error)

GetReportDetails Gets the details for a report for the specified Trustar report id

Endpoint: GET /1.3/reports/{ID}

func (*Client) GetReportIndicators

func (c *Client) GetReportIndicators(id string, v url.Values) (ReportIndicatorsResponse, error)

GetReportIndicators Returns a paginated list of all indicators contained in a specified report.

Endpoint: GET /1.3/reports/{id}/indicators

func (*Client) GetReports

func (c *Client) GetReports(v url.Values) (ReportResponse, error)

GetReports Returns a page of incident reports matching the specified filters. All parameters are optional: if nothing is specified, the latest 25 reports accessible by the user will be returned.

Endpoint: GET /1.3/reports

func (*Client) GetTrendingIndicators

func (c *Client) GetTrendingIndicators(v url.Values) (TrendingIndicators, error)

GetTrendingIndicators Returns the 10 indicators that have recently appeared in the most community reports.

Endpoint: GET /1.3/indicators/community-trending

func (*Client) GetWhitelist

func (c *Client) GetWhitelist(v url.Values) (WhitelistIndicatorsResponse, error)

GetWhitelist Get a paginated list of the indicators that have been whitelisted by the user’s company.

Endpoint: GET /1.3/whitelist

func (*Client) Ping

func (c *Client) Ping() (string, error)

Ping is a standard ping endpoint, used to help users easily establish that the API can be reached. Reference: https://docs.trustar.co/api/v13/ping.html

Endpoint: GET /1.3/ping

func (*Client) RequestQuotas

func (c *Client) RequestQuotas() (RequestQuotas, error)

RequestQuotas returns the current status of the company’s request quotas. A request quota is a maximum number of requests that a company can send to the API during a given time window. Reference: https://docs.trustar.co/api/v13/request_quotas.html

Endpoint: GET /1.3/request-quotas

func (*Client) SearchIndicators

func (c *Client) SearchIndicators(v url.Values) (SearchIndicatorReponse, error)

SearchIndicators Searches for all indicators that contain the given search term. Also allows filtering by date, enclave, and tags.

Endpoint: GET /1.3/indicators/search

func (*Client) SearchReports

func (c *Client) SearchReports(v url.Values) (ReportResponse, error)

SearchReports Searches for all reports that contain the given search term.

Endpoint: GET /1.3/reports/search

func (*Client) Send

func (c *Client) Send(req *http.Request, v interface{}) error

Send makes a request to the API, the response body will be unmarshaled into v, or if v is an io.Writer, the response will be written to it without decoding

func (*Client) SendWithAuth

func (c *Client) SendWithAuth(req *http.Request, v interface{}) error

SendWithAuth makes a request to the API and apply OAuth2 header automatically. If the access token soon to be expired or already expired, it will try to get a new one before making the main request client.Token will be updated when changed

func (*Client) SendWithBasicAuth

func (c *Client) SendWithBasicAuth(req *http.Request, v interface{}) error

SendWithBasicAuth makes a request to the API using clientID:secret basic auth

func (*Client) SetAccessToken

func (c *Client) SetAccessToken(token string)

SetAccessToken sets saved token to current client

func (*Client) SetHTTPClient

func (c *Client) SetHTTPClient(client *http.Client)

SetHTTPClient sets *http.Client to current client

func (*Client) SetLog

func (c *Client) SetLog(log io.Writer)

SetLog will set/change the output destination. If log file is set paypalsdk will log all requests and responses to this Writer

func (*Client) SubmitIndicators

func (c *Client) SubmitIndicators(indicators IndicatorSubmission) error

SubmitIndicators Submit Indicators

Endpoint: POST /1.3/indicators

func (*Client) SubmitReport

func (c *Client) SubmitReport(report ReportSubmission) (string, error)

SubmitReport Submit a new incident report, and receive the ID it has been assigned in TruSTAR’s system.

Endpoint: POST /1.3/reports

func (*Client) UpdateReport

func (c *Client) UpdateReport(id string, report ReportSubmission) error

UpdateReport Update the report with the specified Trustar report ID.

Endpoint: PUT /1.3/reports/{ID}

func (*Client) Version

func (c *Client) Version() (string, error)

Version returns the current stable version Reference: https://docs.trustar.co/api/v13/version.html

Endpoint: GET /api/version

func (*Client) WhitelistIndicators

func (c *Client) WhitelistIndicators(indicators []string) error

WhitelistIndicators Whitelist a list of indicator values for the user’s company.

Endpoint: POST /1.3/whitelist

type CorrelatedReportResponse

type CorrelatedReportResponse struct {
	Empty      bool            `json:"empty"`
	HasNext    bool            `json:"hasNext"`
	Items      []ReportDetails `json:"items"`
	PageNumber int64           `json:"pageNumber"`
	PageSize   int64           `json:"pageSize"`
}

CorrelatedReportResponse is the reponse object from the Find Correlated Reports endpoint

type Enclave

type Enclave struct {
	Create bool   `json:"create"`
	ID     string `json:"id"`
	Name   string `json:"name"`
	Read   bool   `json:"read"`
	Type   string `json:"type"`
	Update bool   `json:"update"`
}

Enclave represents enclave data

type ErrorResponse

type ErrorResponse struct {
	Response *http.Response
}

ErrorResponse holds the response if an error occurs

func (*ErrorResponse) Error

func (r *ErrorResponse) Error() string

Error method implementation for ErrorResponse struct

type Indicator

type Indicator struct {
	GUID          string `json:"guid,omitempty"`
	IndicatorType string `json:"indicatorType,omitempty"` // the type of indicator (IP, URL, EMAIL_ADDRESS, etc.)
	PriorityLevel string `json:"priorityLevel,omitempty"` // LOW, MEDIUM, or HIGH. NOT_FOUND if no score has been computed for this indicator.
	Value         string `json:"value"`                   // the indicator’s value
	Weight        int    `json:"weight"`                  // Possible values are 0 and 1. A value of 0 indicates that, although the term fits the technical requirements to be considered an indicator, our machine learning model has determined that it is likely not an indicator of compromise when considered in the context of a specific report.
	Reason        string `json:"reason"`                  // the reason the indicator has a weight of 0 (not present if weight is 1)
	Whitelisted   string `json:"whitelisted"`             // whether the indicator has been whitelisted by the requesting company
}

Indicator hold the indicator metadata search queries

type IndicatorContent

type IndicatorContent struct {
	Value     string         `json:"value"`
	FirstSeen int64          `json:"firstSeen,omitempty"`
	LastSeen  int64          `json:"lastSeen,omitempty"`
	Sightings int64          `json:"sightings,omitempty"`
	Source    string         `json:"source,omitempty"`
	Notes     string         `json:"notes,omitempty"`
	Tags      []IndicatorTag `json:"tags,omitempty"`
}

IndicatorContent details an indicator object when submitting a new indicator

type IndicatorMetadataResponse

type IndicatorMetadataResponse []struct {
	EnclaveIds    []string       `json:"enclaveIds"`    // the enclaves (of those the user has access to) that the indicator has appeared in a report or indicator submission to
	FirstSeen     int64          `json:"firstSeen"`     // the time (in milliseconds since epoch) that the indicator first appeared in a report or indicator submission to any enclaves the user has access to
	GUID          string         `json:"guid"`          // unique id of the indicator
	IndicatorType string         `json:"indicatorType"` // the type of indicator (IP, URL, EMAIL_ADDRESS, etc.)
	LastSeen      int64          `json:"lastSeen"`      // the time (in milliseconds since epoch) that the indicator last appeared in a report or indicator submission to any enclaves the user has access to
	NoteCount     int64          `json:"noteCount"`     // the number of notes associated with this indicators
	Notes         []string       `json:"notes"`         // the notes associated with the indicator
	PriorityLevel string         `json:"priorityLevel"` // LOW, MEDIUM, or HIGH. NOT_FOUND if no score has been computed for this indicator.
	Sightings     int64          `json:"sightings"`     // the number of times the indicator has appeared in a report or indicator submission to any enclaves the user has access to
	Tags          []IndicatorTag `json:"tags"`          // the set of Tag objects that the indicator has been tagged with
	Value         string         `json:"value"`         // indicator value
}

IndicatorMetadataResponse is a metadata object containing the metadata for the requested indicator(s).

type IndicatorSubmission

type IndicatorSubmission struct {
	EnclaveIDS []string           `json:"enclaveIds"`
	Content    []IndicatorContent `json:"content"`
	Tags       []IndicatorTag     `json:"tags,omitempty"`
}

IndicatorSubmission records the information needed to submit a new indicator to TruSTAR

type IndicatorTag

type IndicatorTag struct {
	Guid      string `json:"guid"`      // the ID of the tag
	Name      string `json:"name"`      // the name of the tag (i.e. the actual string value of the tag)
	EnclaveID string `json:"enclaveId"` // the ID of the enclave of the tag
}

IndicatorTag contains the tag information

type RelatedIndicatorsResponse

type RelatedIndicatorsResponse struct {
	Empty      bool        `json:"empty"`
	HasNext    bool        `json:"hasNext"`
	Items      []Indicator `json:"items"`
	PageNumber int64       `json:"pageNumber"`
	PageSize   int64       `json:"pageSize"`
}

RelatedIndicatorsResponse is the response object from Find Related Indicators endpoint

type ReportDetails

type ReportDetails struct {
	Created          int64    `json:"created"`          // the time of creation, in milliseconds since epoch
	DistributionType string   `json:"distributionType"` // ENCLAVE or COMMUNITY - if COMMUNITY, the report is open to the community. This field is deprecated, but is retained for backwards compatibility. The Community has been transitioned to an enclave, so all reports have a distributionType of ENCLAVE.
	EnclaveIds       []string `json:"enclaveIds"`       // the list of IDs of the enclaves that the report has been submitted to
	ExternalID       string   `json:"externalId"`       // the external ID of the report (any string, user-defined)
	ID               string   `json:"id"`               // the internal ID of the report (a GUID)
	ReportBody       string   `json:"reportBody"`       // the body of the report
	Sector           Sector   `json:"sector"`           // the company's sector
	TimeBegan        int64    `json:"timeBegan"`        // the user-defined time when the incident began, in milliseconds since epoch
	Title            string   `json:"title"`            // the report title
	Updated          int64    `json:"updated"`          // the time of the last update, in milliseconds since epoch
}

ReportDetails contains the details for a specific report

type ReportIndicatorsResponse

type ReportIndicatorsResponse struct {
	Empty      bool        `json:"empty"`
	HasNext    bool        `json:"hasNext"`
	Items      []Indicator `json:"items"`
	PageNumber int64       `json:"pageNumber"`
	PageSize   int64       `json:"pageSize"`
}

ReportIndicatorsResponse is the response object from Get Indicators for Report endpoint

type ReportResponse

type ReportResponse struct {
	Empty      bool            `json:"empty,omitempty"`
	HasNext    bool            `json:"hasNext"`
	Reports    []ReportDetails `json:"items"`
	PageNumber int64           `json:"pageNumber"`
	PageSize   int64           `json:"pageSize"`
}

ReportResponse represents the list of reports matching the user's query

type ReportSubmission

type ReportSubmission struct {
	DistributionType   string   `json:"distributionType"`             // [required] COMMUNITY (will disregard any enclaveIds) or ENCLAVE (must include enclaveIds)
	EnclaveIds         []string `json:"enclaveIds"`                   // Non-empty array of TruSTAR-generated enclave ids (available on Station under settings or through the GET /enclaves endpoint). Use the enclave ID, NOT the enclave name.
	ExternalTrackingID string   `json:"externalTrackingId,omitempty"` // External tracking ID provided by user. Must be unique across all reports for a given company.
	ExternalURL        string   `json:"externalUrl,omitempty"`        // URL for the external report that this originated from, if one exists. Limit 500 alphanumeric characters.
	ReportBody         string   `json:"reportBody"`                   // [required] Text content of report
	TimeBegan          string   `json:"timeBegan,omitempty"`          // SO-8601 formatted incident time with timezone, e.g. 2016-09-22T11:38:35+00:00
	Title              string   `json:"title"`                        // [required] Title of the report
}

ReportSubmission is used for submitting a new report

type RequestQuotas

type RequestQuotas []struct {
	GUID          string `json:"guid"`
	LastResetTime int64  `json:"lastResetTime"`
	MaxRequests   int64  `json:"maxRequests"`
	NextResetTime int64  `json:"nextResetTime"`
	TimeWindow    int64  `json:"timeWindow"`
	UsedRequests  int64  `json:"usedRequests"`
}

RequestQuotas represents the current status of the company’s request quotas.

type SearchIndicatorReponse

type SearchIndicatorReponse struct {
	Empty         bool        `json:"empty"`
	HasNext       bool        `json:"hasNext"`
	Items         []Indicator `json:"items"`
	PageNumber    int64       `json:"pageNumber"`
	PageSize      int64       `json:"pageSize"`
	TotalElements int64       `json:"totalElements"`
	TotalPages    int64       `json:"totalPages"`
}

SearchIndicatorReponse contains the search results when searching indicators

type Sector

type Sector struct {
	ID    int64  `json:"id"`    // the ID of the company’s sector
	Label string `json:"label"` // the name of the company’s sector
	Name  string `json:"name"`  // the label of the company’s sector
}

Sector records sector information for reports and indicators

type TokenResponse

type TokenResponse struct {
	Token     string         `json:"access_token"`
	Scope     string         `json:"scope"`
	TokenType string         `json:"token_type"`
	ExpiresIn expirationTime `json:"expires_in"`
}

TokenResponse is for API response for the /oauth2/token endpoint

type TrendingIndicators

type TrendingIndicators []struct {
	CorrelationCount int64 `json:"correlationCount"`
	Indicator
}

TrendingIndicators holds a list of Indicator objects that are trending in the community

type WhitelistIndicatorsResponse

type WhitelistIndicatorsResponse struct {
	Empty      bool        `json:"empty"`
	HasNext    bool        `json:"hasNext"`
	Items      []Indicator `json:"items"`
	PageNumber int64       `json:"pageNumber"`
	PageSize   int64       `json:"pageSize"`
}

WhitelistIndicatorsResponse represents the indicators that have been whitelisted by the user's company

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL