/
sastclient.go
223 lines (181 loc) · 6.99 KB
/
sastclient.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
package CxSASTClientGo
import (
"bytes"
"fmt"
"io"
//"io/ioutil"
"net/http"
"strings"
"time"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"golang.org/x/oauth2"
)
func (c SASTClient) createRequest(method, url string, body io.Reader, header *http.Header, cookies []*http.Cookie) (*http.Request, error) {
request, err := http.NewRequest(method, url, body)
if err != nil {
return &http.Request{}, err
}
for name, headers := range *header {
for _, h := range headers {
request.Header.Add(name, h)
}
}
for _, cookie := range cookies {
request.AddCookie(cookie)
}
if request.Header.Get("User-Agent") == "" {
request.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:105.0) Gecko/20100101 Firefox/105.0")
}
if request.Header.Get("Content-Type") == "" {
request.Header.Set("Content-Type", "application/json")
}
return request, nil
}
func (c SASTClient) sendRequestInternal(client *http.Client, method, url string, body io.Reader, header http.Header) ([]byte, error) {
var bodyBytes []byte
c.logger.Tracef("Sending request to URL %v", url)
if body != nil {
closer := io.NopCloser(body)
bodyBytes, _ = io.ReadAll(closer)
defer closer.Close()
}
request, err := c.createRequest(method, url, bytes.NewReader(bodyBytes), &header, nil)
if err != nil {
c.logger.Errorf("Unable to create request: %s", err)
return []byte{}, err
}
response, err := client.Do(request)
if err != nil {
c.logger.Errorf("HTTP request failed with error: %s", err)
var resBody []byte
if response != nil && response.Body != nil {
resBody, _ = io.ReadAll(response.Body)
}
c.recordRequestDetailsInErrorCase(bodyBytes, resBody)
return resBody, err
}
if response.StatusCode >= 400 {
var resBody []byte
if response != nil && response.Body != nil {
resBody, _ = io.ReadAll(response.Body)
}
c.recordRequestDetailsInErrorCase(bodyBytes, resBody)
//c.logger.Errorf("HTTP response indicates error: %v", response.Status)
return resBody, errors.New("HTTP Response: " + response.Status)
}
defer response.Body.Close()
resBody, err := io.ReadAll(response.Body)
if err != nil {
if err.Error() == "remote error: tls: user canceled" {
c.logger.Warnf("HTTP request encountered error: %s", err)
} else {
c.logger.Errorf("Error reading response body: %s", err)
}
c.logger.Tracef("Parsed: %v", string(resBody))
}
return resBody, nil
}
func (c SASTClient) sendRequest(method, url string, body io.Reader, header http.Header) ([]byte, error) {
sasturl := fmt.Sprintf("%v/cxrestapi%v", c.baseUrl, url)
return c.sendRequestInternal(c.restClient, method, sasturl, body, header)
}
func (c SASTClient) sendSOAPRequest(method string, body string) ([]byte, error) {
if c.soapClient == nil {
return []byte{}, errors.New("No SOAP client initialized")
}
sasturl := fmt.Sprintf("%v/CxWebInterface/Portal/CxWebService.asmx", c.baseUrl)
header := http.Header{}
SOAPEnvOpen := "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body>"
SOAPEnvClose := "</soap:Body></soap:Envelope>"
header.Set("Content-Type", "text/xml; charset=utf-8")
header.Set("SOAPAction", fmt.Sprintf("%v/%v", "http://Checkmarx.com", method))
//header.Set("Authorization", "Bearer "+c.soapToken)
soap_msg := fmt.Sprintf("%v<%v xmlns=\"http://Checkmarx.com\">%v</%v>%v", SOAPEnvOpen, method, body, method, SOAPEnvClose)
return c.sendRequestInternal(c.soapClient, http.MethodPost, sasturl, strings.NewReader(soap_msg), header)
}
func (c SASTClient) recordRequestDetailsInErrorCase(requestBody []byte, responseBody []byte) {
if len(requestBody) != 0 {
c.logger.Tracef("Request body: %s", string(requestBody))
}
if len(responseBody) != 0 {
c.logger.Tracef("Response body: %s", string(responseBody))
}
}
// convenience function
func (c SASTClient) getV(api string, version string) ([]byte, error) {
header := http.Header{}
header.Add("Accept", "application/json;version="+version)
return c.sendRequest(http.MethodGet, api, nil, header)
}
func (c SASTClient) get(api string) ([]byte, error) {
return c.getV(api, "1.0")
}
func (c SASTClient) ClientsValid() (bool, bool) {
rest_valid := false
soap_valid := false
if c.restClient != nil {
token, err := c.restClient.Transport.(*oauth2.Transport).Source.Token()
if err != nil {
rest_valid = false
} else {
rest_valid = token.Valid()
}
}
if c.soapClient != nil {
token, err := c.soapClient.Transport.(*oauth2.Transport).Source.Token()
if err != nil {
soap_valid = false
} else {
soap_valid = token.Valid()
}
}
return rest_valid, soap_valid
}
func (s *Scan) String() string {
return fmt.Sprintf("Scan ID: %d, Project ID: %d, Status: %v, Time: %v", s.ScanID, s.Project.ID, s.Status, s.FinishTime.Format(time.RFC3339))
}
func (c SASTClient) String() string {
return c.baseUrl // + " with token: " + ShortenGUID(c.authToken)
}
func ShortenGUID(guid string) string {
return fmt.Sprintf("%v..%v", guid[:2], guid[len(guid)-2:])
}
// If you want to provide your own authenticated HTTP Client (prepared through OAuth2 library) you can use this instead.
// this is useful if you are using SAST authentication on a third-party website with authorization_code style oauth
// oauth authorization_code helper function are implemented in sastpassclient.go
func New(client *http.Client, soap_client *http.Client, base_url string, logger *logrus.Logger) (*SASTClient, error) {
cli := &SASTClient{client, soap_client, base_url, logger, nil}
user, err := cli.GetCurrentUser()
if err != nil {
logger.Errorf("Error while fetching current user information: %s", err)
return nil, err
}
cli.CurrentUser = &user
// cli.RefreshCache()
return cli, nil
}
// NewTokenClient will authenticate with SAST using the standard OIDC clients included in the platform
func NewTokenClient(client *http.Client, base_url string, username string, password string, logger *logrus.Logger) (*SASTClient, error) {
// implemented in sastpassclient.go
rest_client := OauthCredentialClient(client, base_url, "resource_owner_client", "014DF517-39D1-4453-B7B3-9930C563627C", username, password, []string{"sast_rest_api", "access_control_api"})
if rest_client == nil {
return nil, errors.New("Unable to initialize CxREST API client")
}
soap_client := OauthCredentialClient(client, base_url, "resource_owner_sast_client", "014DF517-39D1-4453-B7B3-9930C563627C", username, password, []string{"sast_api", "offline_access"})
if soap_client == nil {
return nil, errors.New("Unable to initialize CxSOAP API client")
}
cli, err := New(rest_client, soap_client, base_url, logger)
if err != nil {
return nil, fmt.Errorf("unable to create client: %s", err)
}
return cli, nil
}
func (c SASTClient) depwarn(old, new string) {
if new == "" {
c.logger.Warnf("Cx1SASTClientGo deprecation notice: %v will be deprecated", old)
} else {
c.logger.Warnf("Cx1SASTClientGo deprecation notice: %v will be deprecated and replaced by %v", old, new)
}
}