Completed
Pull Request — master (#769)
by kota
07:28
created

wordpress/wordpress.go   C

Size/Duplication

Total Lines 250
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
cc 56
eloc 160
dl 0
loc 250
rs 5.5199
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
F wordpress.FillWordPress 0 105 31
A wordpress.match 0 10 3
B wordpress.httpRequest 0 23 7
A wordpress.convertToVinfos 0 15 5
C wordpress.extractToVulnInfos 0 41 10
1
/* Vuls - Vulnerability Scanner
2
Copyright (C) 2016  Future Corporation , Japan.
3
4
This program is free software: you can redistribute it and/or modify
5
it under the terms of the GNU General Public License as published by
6
the Free Software Foundation, either version 3 of the License, or
7
(at your option) any later version.
8
9
This program is distributed in the hope that it will be useful,
10
but WITHOUT ANY WARRANTY; without even the implied warranty of
11
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
GNU General Public License for more details.
13
14
You should have received a copy of the GNU General Public License
15
along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
*/
17
18
package wordpress
19
20
import (
21
	"encoding/json"
22
	"fmt"
23
	"io/ioutil"
24
	"net/http"
25
	"strings"
26
27
	"github.com/future-architect/vuls/models"
28
	"github.com/future-architect/vuls/util"
29
	version "github.com/hashicorp/go-version"
30
	"github.com/pkg/errors"
31
)
32
33
//WpCveInfos is for wpvulndb's json
34
type WpCveInfos struct {
35
	ReleaseDate  string `json:"release_date"`
36
	ChangelogURL string `json:"changelog_url"`
37
	// Status        string `json:"status"`
38
	LatestVersion string `json:"latest_version"`
39
	LastUpdated   string `json:"last_updated"`
40
	// Popular         bool        `json:"popular"`
41
	Vulnerabilities []WpCveInfo `json:"vulnerabilities"`
42
	Error           string      `json:"error"`
43
}
44
45
//WpCveInfo is for wpvulndb's json
46
type WpCveInfo struct {
47
	ID        int    `json:"id"`
48
	Title     string `json:"title"`
49
	CreatedAt string `json:"created_at"`
50
	UpdatedAt string `json:"updated_at"`
51
	// PublishedDate string     `json:"published_date"`
52
	VulnType   string     `json:"vuln_type"`
53
	References References `json:"references"`
54
	FixedIn    string     `json:"fixed_in"`
55
}
56
57
//References is for wpvulndb's json
58
type References struct {
59
	URL     []string `json:"url"`
60
	Cve     []string `json:"cve"`
61
	Secunia []string `json:"secunia"`
62
}
63
64
// FillWordPress access to wpvulndb and fetch scurity alerts and then set to the given ScanResult.
65
// https://wpvulndb.com/
66
func FillWordPress(r *models.ScanResult, token string) (int, error) {
67
	// Core
68
	ver := strings.Replace(r.WordPressPackages.CoreVersion(), ".", "", -1)
69
	if ver == "" {
70
		return 0, fmt.Errorf("Failed to get WordPress core version")
71
	}
72
	url := fmt.Sprintf("https://wpvulndb.com/api/v3/wordpresses/%s", ver)
73
	body, err := httpRequest(url, token)
74
	if err != nil {
75
		return 0, err
76
	}
77
	wpVinfos, err := convertToVinfos(models.WPCore, string(body))
78
	if err != nil {
79
		return 0, err
80
	}
81
82
	//TODO add a flag ignore inactive plugin or themes such as -wp-ignore-inactive flag to cmd line option or config.toml
83
84
	// Themes
85
	for _, p := range r.WordPressPackages.Themes() {
86
		url := fmt.Sprintf("https://wpvulndb.com/api/v3/themes/%s", p.Name)
87
		body, err := httpRequest(url, token)
88
		if err != nil {
89
			return 0, err
90
		}
91
		if body == "" {
92
			continue
93
		}
94
95
		templateVinfos, err := convertToVinfos(p.Name, string(body))
96
		if err != nil {
97
			return 0, err
98
		}
99
100
		for _, v := range templateVinfos {
101
			for _, fixstat := range v.WpPackageFixStats {
102
				pkg, ok := r.WordPressPackages.Find(fixstat.Name)
103
				if !ok {
104
					continue
105
				}
106
				ok, err := match(pkg.Version, fixstat.FixedIn)
107
				if err != nil {
108
					return 0, errors.Wrap(err, "Not a semantic versioning")
109
				}
110
				if ok {
111
					wpVinfos = append(wpVinfos, v)
112
					util.Log.Infof("[match] %s installed: %s, fixedIn: %s", pkg.Name, pkg.Version, fixstat.FixedIn)
113
				} else {
114
					//TODO Debugf
115
					util.Log.Infof("[miss] %s installed: %s, fixedIn: %s", pkg.Name, pkg.Version, fixstat.FixedIn)
116
				}
117
			}
118
		}
119
	}
120
121
	// Plugins
122
	for _, p := range r.WordPressPackages.Plugins() {
123
		url := fmt.Sprintf("https://wpvulndb.com/api/v3/plugins/%s", p.Name)
124
		body, err := httpRequest(url, token)
125
		if err != nil {
126
			return 0, err
127
		}
128
		if body == "" {
129
			continue
130
		}
131
132
		pluginVinfos, err := convertToVinfos(p.Name, string(body))
133
		if err != nil {
134
			return 0, err
135
		}
136
137
		for _, v := range pluginVinfos {
138
			for _, fixstat := range v.WpPackageFixStats {
139
				pkg, ok := r.WordPressPackages.Find(fixstat.Name)
140
				if !ok {
141
					continue
142
				}
143
				ok, err := match(pkg.Version, fixstat.FixedIn)
144
				if err != nil {
145
					return 0, errors.Wrap(err, "Not a semantic versioning")
146
				}
147
				if ok {
148
					wpVinfos = append(wpVinfos, v)
149
					//TODO Debugf
150
					util.Log.Infof("[match] %s installed: %s, fixedIn: %s", pkg.Name, pkg.Version, fixstat.FixedIn)
151
				} else {
152
					//TODO Debugf
153
					util.Log.Infof("[miss] %s installed: %s, fixedIn: %s", pkg.Name, pkg.Version, fixstat.FixedIn)
154
				}
155
			}
156
		}
157
	}
158
159
	for _, wpVinfo := range wpVinfos {
160
		if vinfo, ok := r.ScannedCves[wpVinfo.CveID]; ok {
161
			vinfo.CveContents[models.WPVulnDB] = wpVinfo.CveContents[models.WPVulnDB]
162
			vinfo.VulnType = wpVinfo.VulnType
163
			vinfo.Confidences = append(vinfo.Confidences, wpVinfo.Confidences...)
164
			vinfo.WpPackageFixStats = append(vinfo.WpPackageFixStats, wpVinfo.WpPackageFixStats...)
165
			r.ScannedCves[wpVinfo.CveID] = vinfo
166
		} else {
167
			r.ScannedCves[wpVinfo.CveID] = wpVinfo
168
		}
169
	}
170
	return len(wpVinfos), nil
171
}
172
173
func match(installedVer, fixedIn string) (bool, error) {
174
	v1, err := version.NewVersion(installedVer)
175
	if err != nil {
176
		return false, err
177
	}
178
	v2, err := version.NewVersion(fixedIn)
179
	if err != nil {
180
		return false, err
181
	}
182
	return v1.LessThan(v2), nil
183
}
184
185
func convertToVinfos(pkgName, body string) (vinfos []models.VulnInfo, err error) {
186
	if body == "" {
187
		return
188
	}
189
	// "pkgName" : CVE Detailed data
190
	pkgnameCves := map[string]WpCveInfos{}
191
	if err = json.Unmarshal([]byte(body), &pkgnameCves); err != nil {
192
		return nil, errors.Wrap(err, fmt.Sprintf("Failed to unmarshal: %s", body))
193
	}
194
195
	for _, v := range pkgnameCves {
196
		vs := extractToVulnInfos(pkgName, v.Vulnerabilities)
197
		vinfos = append(vinfos, vs...)
198
	}
199
	return vinfos, nil
200
}
201
202
func extractToVulnInfos(pkgName string, cves []WpCveInfo) (vinfos []models.VulnInfo) {
203
	for _, vulnerability := range cves {
204
		var cveIDs []string
205
206
		if len(vulnerability.References.Cve) == 0 {
207
			cveIDs = append(cveIDs, fmt.Sprintf("WPVDBID-%d", vulnerability.ID))
208
		}
209
		for _, cveNumber := range vulnerability.References.Cve {
210
			cveIDs = append(cveIDs, "CVE-"+cveNumber)
211
		}
212
213
		var refs []models.Reference
214
		for _, url := range vulnerability.References.URL {
215
			refs = append(refs, models.Reference{
216
				Link: url,
217
			})
218
		}
219
220
		for _, cveID := range cveIDs {
221
			vinfos = append(vinfos, models.VulnInfo{
222
				CveID: cveID,
223
				CveContents: models.NewCveContents(
224
					models.CveContent{
225
						Type:       models.WPVulnDB,
226
						CveID:      cveID,
227
						Title:      vulnerability.Title,
228
						References: refs,
229
					},
230
				),
231
				VulnType: vulnerability.VulnType,
232
				Confidences: []models.Confidence{
233
					models.WPVulnDBMatch,
234
				},
235
				WpPackageFixStats: []models.WpPackageFixStatus{{
236
					Name:    pkgName,
237
					FixedIn: vulnerability.FixedIn,
238
				}},
239
			})
240
		}
241
	}
242
	return
243
}
244
245
func httpRequest(url, token string) (string, error) {
246
	util.Log.Debugf("%s", url)
247
	req, err := http.NewRequest("GET", url, nil)
248
	if err != nil {
249
		return "", err
250
	}
251
	req.Header.Set("Authorization", fmt.Sprintf("Token token=%s", token))
252
	resp, err := new(http.Client).Do(req)
253
	if err != nil {
254
		return "", err
255
	}
256
	body, err := ioutil.ReadAll(resp.Body)
257
	if err != nil {
258
		return "", err
259
	}
260
	defer resp.Body.Close()
261
	if resp.StatusCode != 200 && resp.StatusCode != 404 {
262
		return "", fmt.Errorf("status: %s", resp.Status)
263
	} else if resp.StatusCode == 404 {
264
		// This package is not in WPVulnDB
265
		return "", nil
266
	}
267
	return string(body), nil
268
}
269