-
Notifications
You must be signed in to change notification settings - Fork 94
/
topology.js
513 lines (433 loc) · 13.1 KB
/
topology.js
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
/* Greenbone Security Assistant
*
* Authors:
* Björn Ricks <bjoern.ricks@greenbone.net>
* Steffen Waterkamp <steffen.waterkamp@greenbone.net>
*
* Copyright:
* Copyright (C) 2018 Greenbone Networks GmbH
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import React from 'react';
import glamorous from 'glamorous';
import {
forceSimulation,
forceLink,
forceManyBody,
forceCenter,
forceX,
forceY,
} from 'd3-force';
import {color} from 'd3-color';
import {scaleLinear} from 'd3-scale';
import _ from 'gmp/locale';
import {is_defined} from 'gmp/utils/identity';
import PropTypes from '../../utils/proptypes';
import Theme from '../../utils/theme';
import {
getSeverityLevelsOld as getSeverityLevels,
FALSE_POSITIVE_VALUE,
HIGH_VALUE,
} from '../../utils/severity';
import {setRef} from '../../utils/render';
import Group from './group';
import {Layout} from '../layout/layout';
const MAX_HOSTS = 1000;
const SCANNER_RADIUS = 8;
const HOST_RADIUS = 5;
const Svg = glamorous.svg({
'& text': {
userSelect: 'none',
},
}, ({dragging = false}) => ({
cursor: dragging ? 'grabbing' : 'grab',
}));
const Circle = glamorous.circle({
cursor: 'pointer',
});
const severityColorsGradientScale = type => {
const severity_levels = getSeverityLevels(type);
return scaleLinear()
.domain([
FALSE_POSITIVE_VALUE,
severity_levels.max_log,
severity_levels.min_low,
(severity_levels.min_low + severity_levels.max_low) / 2,
severity_levels.max_low,
severity_levels.min_medium,
(severity_levels.min_medium + severity_levels.max_medium) / 2,
severity_levels.max_medium,
severity_levels.min_high,
(severity_levels.min_high + HIGH_VALUE) / 2,
HIGH_VALUE,
])
.range([
'grey', // False Positive
'silver', // Log
'#b1cee9', // minimum Low
'#87CEEB', // middle Low
'#a5e59d', // maximum Low
'#ffde00', // minimum Medium
'#FFA500', // middle Medium
'#f57b00', // maximum Medium
'#eb5200', // minimum High
'#D80000', // middle High
'#ff0000', // maximum High
]);
};
const SCROLL_STEP = 0.1;
const MAX_SCALE = 2;
const MIN_SCALE = 0.1;
const TEXT_SCALE_THRESHOLD = 1;
const DEFAULT_STROKE_WIDTH = 1;
const SCANNER_STROKE_WIDTH = 2;
class HostsTopologyChart extends React.Component {
constructor(...args) {
super(...args);
this.state = {
hosts: [],
links: [],
scale: 1.0,
translateX: 0,
translateY: 0,
dragging: false,
};
this.colorScale = severityColorsGradientScale(this.props.severityClass);
this.hostFillColor = this.hostFillColor.bind(this);
this.hostStrokeColor = this.hostStrokeColor.bind(this);
this.handleMouseWheel = this.handleMouseWheel.bind(this);
this.handleMouseDown = this.handleMouseDown.bind(this);
this.handleMousUp = this.handleMousUp.bind(this);
this.handleMousMove = this.handleMousMove.bind(this);
}
componentDidMount() {
this.updateData(this.props.data);
}
componentWillUnmount() {
if (is_defined(this.simulation)) {
this.simulation.stop();
this.simulation.on('tick', null);
this.simulation.on('end', null);
}
}
hostFillColor(host) {
return is_defined(host.uuid) ? this.colorScale(host.severity) : Theme.white;
}
hostStrokeColor(host) {
if (host.isScanner) {
return Theme.green;
}
if (is_defined(host.uuid)) {
return color(this.colorScale(host.severity)).darker();
}
return Theme.lightGray;
};
/**
* Zoom chart at pixel coordinates to the scale factor
*
* @param {Number} px X coordinate relative to the svg element
* @param {Number} py Y coordinate relative to the svg element
* @param {Number} scale New scale factor to set
*/
zoom(px, py, scale) {
const {x, y} = this.toChartCoords(px, py);
// calculate new pixel coords and afterwards diff to previous coords
const diffX = (x * scale) - px;
const diffY = (y * scale) - py;
this.setState({
scale,
translateX: -diffX,
translateY: -diffY,
});
}
/**
* Zoom chart at pixel coordinates one step in until MAX_SCALE is reached
*
* @param {Number} px X coordinate relative to the svg element
* @param {Number} py Y coordinate relative to the svg element
*/
zoomIn(px, py) {
let {scale} = this.state;
if (scale === MAX_SCALE) {
// avoid setting state and rerendering
return;
}
scale = scale + SCROLL_STEP;
if (scale > MAX_SCALE) {
// limit min scale
scale = MAX_SCALE;
}
this.zoom(px, py, scale);
}
/**
* Zoom chart at pixel coordinates one step out until MIN_SCALE is reached
*
* @param {Number} px X coordinate relative to the svg element
* @param {Number} py Y coordinate relative to the svg element
*/
zoomOut(px, py) {
let {scale} = this.state;
if (scale === MIN_SCALE) {
// avoid setting state and rerendering
return;
}
scale = scale - SCROLL_STEP;
if (scale < MIN_SCALE) {
// limit scale
scale = MIN_SCALE;
}
this.zoom(px, py, scale);
}
/**
* Convert pixel coordinates into chart coordinates
*
* @param {Number} x Relative X position to the svg element
* @param {Number} y Relative Y position to the svg element
*
* @returns {Object} Chart coordinates as {x,y}
*/
toChartCoords(x, y) {
const {scale, translateX, translateY} = this.state;
// transform pixel coords into chart coords
return {
x: (x - translateX) / scale,
y: (y - translateY) / scale,
};
}
/**
* Get relative mouse positions to the svg element
*
* @param {MouseEvent} event The MouseEvent
*
* @returns {Object} Relative position of the mouse as {x,y}
*/
getMousePosition(event) {
const {clientX, clientY} = event;
const {left, top} = this.svg.getBoundingClientRect();
return {
x: clientX - left,
y: clientY - top,
};
}
handleMouseWheel(event) {
const {x, y} = this.getMousePosition(event);
event.preventDefault();
// event.deltaY returns nagative values for mouse wheel up and positive values for mouse wheel down
const isZoomOut = Math.sign(event.deltaY) === 1;
isZoomOut ? this.zoomOut(x, y) : this.zoomIn(x, y);
}
handleMouseDown(event) {
this.coords = {
x: event.pageX,
y: event.pageY,
};
this.setState({dragging: true});
}
handleMousUp(event) {
if (is_defined(this.draggingHost)) {
this.simulation.alphaTarget(0);
this.draggingHost.fx = undefined;
this.draggingHost.fy = undefined;
this.draggingHost = undefined;
}
this.coords = {};
this.setState({dragging: false});
}
handleMousMove(event) {
if (is_defined(this.draggingHost)) {
// we are dragging a host circle
const {x: mx, y: my} = this.getMousePosition(event);
const {x, y} = this.toChartCoords(mx, my);
this.draggingHost.fx = x;
this.draggingHost.fy = y;
return;
}
if (!this.state.dragging) {
// we aren't dragging anything
return;
}
event.preventDefault();
const xDiff = this.coords.x - event.pageX;
const yDiff = this.coords.y - event.pageY;
this.coords.x = event.pageX;
this.coords.y = event.pageY;
this.setState(state => ({
translateX: state.translateX - xDiff,
translateY: state.translateY - yDiff,
}));
}
handleHostDragStart(event, host) {
event.stopPropagation();
this.simulation.alphaTarget(0.3).restart();
host.fx = host.x;
host.fy = host.y;
this.draggingHost = host;
}
updateData(data = {}) {
const {width, height} = this.props;
let {hosts = [], links = []} = data;
this.setState({hostsCount: hosts.length});
if (hosts.length === 0) {
this.setState({hosts: [], links: []});
return;
}
if (hosts.length > MAX_HOSTS) {
const removeHosts = hosts.slice(MAX_HOSTS, hosts.length - 1);
// remove all links using these hosts
const linksSet = new Set(links);
for (const host of removeHosts) {
for (const link of host.links) {
linksSet.delete(link);
}
}
links = [...linksSet];
hosts = hosts.slice(0, MAX_HOSTS);
}
const linkForce = forceLink(links)
.id(l => l.id)
.strength(0.2);
const gravityXForce = forceX().strength(0.03);
const gravityYForce = forceY().strength(0.03);
this.simulation = forceSimulation(hosts)
.force('link', linkForce)
.force('charge', forceManyBody().strength(-20))
.force('center', forceCenter(width / 2, height / 2))
.force('gravityX', gravityXForce)
.force('gravityY', gravityYForce)
.alphaMin(0.1)
.alphaDecay(0.02276278) // alphaMin and alphaDecay result in ~100 ticks
.on('tick', () => {
this.setState({hosts, links});
});
}
render() {
const {width, height, svgRef} = this.props;
const {
hosts = [],
links = [],
scale,
translateX,
translateY,
dragging,
hostsCount,
} = this.state;
return (
<Layout flex="column">
{hostsCount > MAX_HOSTS &&
<Layout align={['center', 'center']}>
<p>{_('The current number of {{hostsCount}} hosts exceeds the ' +
'maximum of {{maxHosts}}. Please apply a more specific ' +
'filter.', {hostsCount, maxHosts: MAX_HOSTS})}</p>
</Layout>
}
<Svg
dragging={dragging}
width={width}
height={height}
onWheel={this.handleMouseWheel}
onMouseDown={this.handleMouseDown}
onMouseUp={this.handleMousUp}
onMouseMove={this.handleMousMove}
innerRef={setRef(ref => this.svg = ref, svgRef)}
>
<Group
left={translateX}
top={translateY}
scale={scale}
>
{links.map(link => {
return (
<line
key={link.index}
stroke={Theme.green}
x1={link.source.x}
y1={link.source.y}
x2={link.target.x}
y2={link.target.y}
/>
);
})}
{hosts.map(host => {
const radius = host.isScanner ? SCANNER_RADIUS : HOST_RADIUS;
return (
<React.Fragment
key={host.id}
>
{scale > TEXT_SCALE_THRESHOLD &&
<text
fontWeight="normal"
textAnchor="middle"
dominantBaseline="hanging"
fontSize="6px"
fill={is_defined(host.uuid) ?
Theme.black : Theme.lightGray}
x={host.x}
y={host.y + 1 + radius}
>
{host.name}
</text>
}
<Circle
r={radius}
fill={this.hostFillColor(host)}
stroke={this.hostStrokeColor(host)}
strokeWidth={host.isScanner ?
SCANNER_STROKE_WIDTH : DEFAULT_STROKE_WIDTH}
cx={host.x}
cy={host.y}
onMouseDown={event => this.handleHostDragStart(event, host)}
/>
</React.Fragment>
);
})}
</Group>
</Svg>
</Layout>
);
}
}
const LinkType = PropTypes.shape({
// d3 is mutating the original link object. Therefore allow object for source and target
// actually the target and source objects are of HostType ...
source: PropTypes.oneOfType([
PropTypes.string,
PropTypes.object,
]).isRequired,
target: PropTypes.oneOfType([
PropTypes.string,
PropTypes.object,
]).isRequired,
});
const HostType = PropTypes.shape({
id: PropTypes.string.isRequired,
uuid: PropTypes.id,
severity: PropTypes.number,
name: PropTypes.string,
isScanner: PropTypes.bool,
links: PropTypes.arrayOf(LinkType).isRequired,
});
HostsTopologyChart.propTypes = {
data: PropTypes.shape({
hosts: PropTypes.arrayOf(HostType),
links: PropTypes.arrayOf(LinkType),
}).isRequired,
height: PropTypes.number.isRequired,
severityClass: PropTypes.severityClass,
svgRef: PropTypes.ref,
width: PropTypes.number.isRequired,
};
export default HostsTopologyChart;
// vim: set ts=2 sw=2 tw=80: