app.js 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  1. document.documentElement.classList.replace('no-js','js');
  2. /* ===================== ОБЩИЕ УТИЛИТЫ ===================== */
  3. const $ = (s, r = document) => r.querySelector(s);
  4. const $$ = (s, r = document) => [...r.querySelectorAll(s)];
  5. const esc = s => String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
  6. const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
  7. const reduceMotion = !!(window.matchMedia && matchMedia('(prefers-reduced-motion: reduce)').matches);
  8. /* Звук: Web Audio, включается кнопкой в шапке */
  9. let soundOn = false, actx = null;
  10. function beep(freq = 660, dur = .09, type = 'sine', vol = .05) {
  11. if (!soundOn) return;
  12. try {
  13. actx = actx || new (window.AudioContext || window.webkitAudioContext)();
  14. const o = actx.createOscillator(), g = actx.createGain();
  15. o.type = type; o.frequency.value = freq;
  16. g.gain.setValueAtTime(vol, actx.currentTime);
  17. g.gain.exponentialRampToValueAtTime(0.0001, actx.currentTime + dur);
  18. o.connect(g).connect(actx.destination);
  19. o.start(); o.stop(actx.currentTime + dur);
  20. } catch (e) { /* звук не обязателен */ }
  21. }
  22. /* Единый цикл анимации: компоненты подключаются и отключаются, без утечек */
  23. const loops = new Map();
  24. let lastTs = performance.now();
  25. function frame(ts) {
  26. const dt = Math.min((ts - lastTs) / 1000, .05);
  27. lastTs = ts;
  28. loops.forEach(fn => fn(dt));
  29. requestAnimationFrame(frame);
  30. }
  31. requestAnimationFrame(frame);
  32. const addLoop = (name, fn) => loops.set(name, fn);
  33. const removeLoop = name => loops.delete(name);
  34. /* Холст с учётом плотности пикселей и размеров */
  35. function setupCanvas(canvas) {
  36. const c = { canvas, ctx: canvas.getContext('2d'), w: 0, h: 0 };
  37. c.resize = () => {
  38. const r = canvas.getBoundingClientRect();
  39. const dpr = Math.min(window.devicePixelRatio || 1, 2);
  40. canvas.width = Math.max(1, Math.round(r.width * dpr));
  41. canvas.height = Math.max(1, Math.round(r.height * dpr));
  42. c.ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  43. c.w = r.width; c.h = r.height;
  44. };
  45. c.resize();
  46. if ('ResizeObserver' in window) new ResizeObserver(c.resize).observe(canvas);
  47. else window.addEventListener('resize', c.resize);
  48. return c;
  49. }
  50. /* Математика: функция ошибок и хвост нормального распределения */
  51. function erfc(x) {
  52. const z = Math.abs(x), t = 1 / (1 + .5 * z);
  53. const r = t * Math.exp(-z * z - 1.26551223 + t * (1.00002368 + t * (.37409196 + t * (.09678418 +
  54. t * (-.18628806 + t * (.27886807 + t * (-1.13520398 + t * (1.48851587 + t * (-.82215223 + t * .17087277)))))))));
  55. return x >= 0 ? r : 2 - r;
  56. }
  57. const Q = x => .5 * erfc(x / Math.SQRT2);
  58. const gauss = () => { let u = 0; while (u === 0) u = Math.random(); return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * Math.random()); };
  59. /* ===================== ШАПКА, ПРОГРЕСС, ПОЯВЛЕНИЕ ===================== */
  60. const clockEl = $('#clock');
  61. const tickClock = () => { clockEl.textContent = new Date().toLocaleTimeString('ru-RU', { hour12: false }); };
  62. tickClock(); setInterval(tickClock, 1000);
  63. const nav = $('#nav'), burger = $('#burger');
  64. burger.addEventListener('click', () => {
  65. const open = nav.classList.toggle('open');
  66. burger.setAttribute('aria-expanded', String(open));
  67. });
  68. $$('#nav a').forEach(a => a.addEventListener('click', () => {
  69. nav.classList.remove('open');
  70. burger.setAttribute('aria-expanded', 'false');
  71. }));
  72. const progressEl = $('#progress');
  73. const onScroll = () => {
  74. const max = document.documentElement.scrollHeight - innerHeight;
  75. progressEl.style.transform = `scaleX(${max > 0 ? scrollY / max : 0})`;
  76. };
  77. addEventListener('scroll', onScroll, { passive: true });
  78. onScroll();
  79. const revealIO = new IntersectionObserver(entries => entries.forEach(e => {
  80. if (e.isIntersecting) { e.target.classList.add('in'); revealIO.unobserve(e.target); }
  81. }), { threshold: .12 });
  82. $$('.reveal').forEach(el => revealIO.observe(el));
  83. const activeIO = new IntersectionObserver(entries => entries.forEach(e => {
  84. if (!e.isIntersecting) return;
  85. $$('#nav a').forEach(a => a.classList.toggle('active', a.getAttribute('href') === '#' + e.target.id));
  86. }), { rootMargin: '-45% 0px -50% 0px' });
  87. $$('main section[id]').forEach(s => activeIO.observe(s));
  88. const soundBtn = $('#soundBtn');
  89. soundBtn.addEventListener('click', () => {
  90. soundOn = !soundOn;
  91. soundBtn.setAttribute('aria-pressed', String(soundOn));
  92. soundBtn.textContent = soundOn ? 'ЗВУК: ВКЛ' : 'ЗВУК: ВЫКЛ';
  93. if (soundOn) beep(660, .12, 'sine', .05);
  94. });
  95. /* ===================== HERO: ОСЦИЛЛОГРАФ ===================== */
  96. const heroC = setupCanvas($('#wave'));
  97. let heroPhase = 0;
  98. function drawHero(dt) {
  99. const { ctx, w, h } = heroC;
  100. if (!w) return;
  101. heroPhase += dt * 2;
  102. ctx.clearRect(0, 0, w, h);
  103. ctx.strokeStyle = 'rgba(101,227,255,.12)'; ctx.lineWidth = 1;
  104. ctx.beginPath(); ctx.moveTo(0, h / 2); ctx.lineTo(w, h / 2); ctx.stroke();
  105. for (let line = 0; line < 3; line++) {
  106. ctx.beginPath();
  107. for (let x = 0; x <= w; x += 2) {
  108. const k = x / w;
  109. let y = h * .5 + Math.sin(k * 16 + heroPhase + line * .5) * h * .12 + Math.sin(k * 5 - heroPhase * 1.4) * h * .07;
  110. if (line === 1) y += (Math.random() - .5) * h * .035;
  111. x === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
  112. }
  113. ctx.lineWidth = line === 1 ? 1.6 : .8;
  114. ctx.strokeStyle = line === 1 ? 'rgba(101,227,255,.9)' : 'rgba(101,227,255,.18)';
  115. ctx.shadowColor = '#65e3ff';
  116. ctx.shadowBlur = line === 1 ? 10 : 0;
  117. ctx.stroke();
  118. }
  119. ctx.shadowBlur = 0;
  120. }
  121. const heroBtn = $('#heroPlay');
  122. function setHero(on) {
  123. if (on) addLoop('hero', drawHero); else removeLoop('hero');
  124. heroBtn.setAttribute('aria-pressed', String(on));
  125. heroBtn.textContent = on ? 'Ⅱ Пауза осциллографа' : '▶ Запустить осциллограф';
  126. }
  127. heroBtn.addEventListener('click', () => setHero(heroBtn.getAttribute('aria-pressed') !== 'true'));
  128. setHero(!reduceMotion);
  129. if (reduceMotion) drawHero(0);
  130. setInterval(() => { $('#dbVal').textContent = (40 + Math.random() * 5).toFixed(1) + ' dB'; }, 700);
  131. /* ===================== 01. КАНАЛЫ: ОТДЕЛЬНАЯ СЦЕНА ДЛЯ КАЖДОГО КАНАЛА ===================== */
  132. const CH = {
  133. visual: {
  134. code: 'CHANNEL 01 / VISUAL', title: 'Визуальный канал',
  135. desc: 'Информация может быть получена простым наблюдением: через экран монитора, бумажные документы, доски или открытые окна.',
  136. mech: 'Наблюдение за отображаемой или напечатанной информацией без доступа к самой системе.',
  137. prot: 'Экранные фильтры, монитор развёрнут от прохода, блокировка экрана, режим «чистого стола».',
  138. ex: 'Распечатка с паролем лежала на столе в открытом офисе, и её прочитал посетитель.'
  139. },
  140. acoustic: {
  141. code: 'CHANNEL 02 / ACOUSTIC', title: 'Акустический канал',
  142. desc: 'Речевые сведения становятся доступны за пределами помещения через воздух и строительные конструкции (вибрацию).',
  143. mech: 'Звуковые волны распространяются через воздух, стены, окна, трубы и вентиляцию.',
  144. prot: 'Звукоизоляция переговорных, виброизоляция, маскирующий шум, правила обсуждения конфиденциальных вопросов.',
  145. ex: 'Переговоры в соседнем кабинете слышны через тонкую стену и вентиляционный короб.'
  146. },
  147. electromagnetic: {
  148. code: 'CHANNEL 03 / EM', title: 'Электромагнитный канал',
  149. desc: 'Работающая техника создаёт побочные электромагнитные излучения и наводки (ПЭМИН). При определённых условиях они могут нести информацию, которую обрабатывает устройство.',
  150. mech: 'Побочные излучения и наводки на линиях связи и питания технических средств.',
  151. prot: 'Экранирование помещений и оборудования, фильтрация линий, зашумление, размещение техники по нормам ТЗИ.',
  152. ex: 'Экранирование и фильтры на линиях питания — одна из основных мер, которые проверяют при аттестации.'
  153. },
  154. network: {
  155. code: 'CHANNEL 04 / NETWORK', title: 'Сетевой канал',
  156. desc: 'Данные могут покинуть организацию по сети при нарушении разграничения доступа, ошибках настройки или заражении устройства.',
  157. mech: 'Передача данных по коммуникационным каналам, несанкционированное подключение, неправомерный доступ.',
  158. prot: 'Сегментация сети, разграничение прав, шифрование трафика, журналирование, мониторинг соединений, обновления.',
  159. ex: 'Файл с персональными данными отправлен на внешний адрес после заражения рабочей станции.'
  160. },
  161. physical: {
  162. code: 'CHANNEL 05 / PHYSICAL', title: 'Физический канал',
  163. desc: 'Утечка может происходить через потерю флешек и дисков, несанкционированное копирование или вынос документов.',
  164. mech: 'Физическое перемещение носителя или доступ к устройству вне установленного контроля.',
  165. prot: 'Учёт носителей, пропускной режим, защищённое хранение, безопасное уничтожение, контроль портов и периферии.',
  166. ex: 'Незашифрованная флешка с базой клиентов потеряна в такси.'
  167. }
  168. };
  169. const modal = $('#modal');
  170. const sceneC = setupCanvas($('#chScene'));
  171. const S = { ch: null, prot: false, t: 0, dt: 0, acc: 0, seen: {}, log: [], cap: 0, blocked: 0, status: null, last: '' };
  172. const PAL = { cyan: '#65e3ff', green: '#5ce5b2', amber: '#ffc76b', red: '#ff657e', dim: '#5d6e83', text: '#e7edf6' };
  173. const GLYPHS = '#%&$@x7Qz9<>/';
  174. function say(ctx, s, x, y, color, sz = 10, align = 'left', bold = false) {
  175. ctx.fillStyle = color;
  176. ctx.font = `${bold ? '700 ' : ''}${sz}px "Space Mono", ui-monospace, Consolas, monospace`;
  177. ctx.textAlign = align; ctx.textBaseline = 'middle';
  178. ctx.fillText(s, x, y);
  179. }
  180. const smooth = x => x * x * (3 - 2 * x);
  181. const rnd = (a, b) => a + Math.random() * (b - a);
  182. const scramble = n => Array.from({ length: n }, () => GLYPHS[Math.floor(Math.random() * GLYPHS.length)]).join('');
  183. const stamp = t => '10:' + String(Math.floor(t) % 60).padStart(2, '0');
  184. function box(ctx, x, y, w, h, stroke, fill) {
  185. if (fill) { ctx.fillStyle = fill; ctx.fillRect(x, y, w, h); }
  186. ctx.strokeStyle = stroke; ctx.lineWidth = 1.2; ctx.strokeRect(x, y, w, h);
  187. }
  188. function figure(ctx, x, y, col) {
  189. ctx.strokeStyle = col; ctx.lineWidth = 1.6;
  190. ctx.beginPath(); ctx.arc(x, y - 22, 5, 0, Math.PI * 2); ctx.stroke();
  191. ctx.beginPath();
  192. ctx.moveTo(x, y - 16); ctx.lineTo(x, y - 6);
  193. ctx.moveTo(x, y - 6); ctx.lineTo(x - 4, y);
  194. ctx.moveTo(x, y - 6); ctx.lineTo(x + 4, y);
  195. ctx.moveTo(x, y - 13); ctx.lineTo(x + 6, y - 9);
  196. ctx.stroke();
  197. }
  198. function gridBg(ctx, w, h) {
  199. ctx.strokeStyle = 'rgba(101,227,255,.05)'; ctx.lineWidth = 1; ctx.beginPath();
  200. for (let x = 0; x < w; x += 24) { ctx.moveTo(x, 0); ctx.lineTo(x, h); }
  201. for (let y = 0; y < h; y += 24) { ctx.moveTo(0, y); ctx.lineTo(w, y); }
  202. ctx.stroke();
  203. }
  204. /* --- 1. ВИЗУАЛЬНЫЙ: конус видимости и фильтр конфиденциальности --- */
  205. function sceneVisual(ctx, w, h, t, prot, S) {
  206. const R = Math.min(w * .3, h * .42), mx = w * .3, my = h * .5, mw = w * .2, mh = h * .5;
  207. const fx = mx + mw / 2;
  208. const half = prot ? .42 : 1.25; // полуугол видимости экрана, рад
  209. const phi = Math.sin(t * .45) * 1.15; // угол наблюдателя, рад
  210. const readable = Math.abs(phi) < half;
  211. ctx.beginPath(); ctx.moveTo(fx, my);
  212. ctx.lineTo(fx + R * 1.1 * Math.cos(-half), my + R * 1.1 * Math.sin(-half));
  213. ctx.lineTo(fx + R * 1.1 * Math.cos(half), my + R * 1.1 * Math.sin(half));
  214. ctx.closePath();
  215. ctx.fillStyle = prot ? 'rgba(92,229,178,.07)' : 'rgba(255,101,126,.09)';
  216. ctx.fill();
  217. box(ctx, mx - mw / 2, my - mh / 2, mw, mh, 'rgba(101,227,255,.5)', '#0b1624');
  218. ctx.fillStyle = '#1a2a3e'; ctx.fillRect(mx - 3, my + mh / 2, 6, 10);
  219. ['ДОГОВОР № 77/26', 'СУММА 1 200 000', 'PIN: 4821', 'СЕКРЕТНО'].forEach((s, i) => {
  220. const y = my - mh / 2 + 16 + i * 14, x = mx - mw / 2 + 7;
  221. if (readable) say(ctx, s, x, y, PAL.green, 8.5);
  222. else { ctx.fillStyle = '#2a3a4d'; ctx.fillRect(x, y - 3, s.length * 5.2, 6); }
  223. });
  224. if (prot) {
  225. ctx.fillStyle = 'rgba(255,199,107,.75)'; ctx.fillRect(fx + 3, my - mh / 2, 3, mh);
  226. say(ctx, 'фильтр', fx + 9, my - mh / 2 + 6, PAL.amber, 8);
  227. }
  228. const ox = mx + R * Math.cos(phi), oy = my + R * Math.sin(phi);
  229. ctx.setLineDash([3, 4]); ctx.strokeStyle = readable ? PAL.red : PAL.dim;
  230. ctx.beginPath(); ctx.moveTo(ox, oy); ctx.lineTo(fx, my); ctx.stroke(); ctx.setLineDash([]);
  231. ctx.fillStyle = '#1b2a40'; ctx.strokeStyle = readable ? PAL.red : PAL.cyan; ctx.lineWidth = 1.5;
  232. ctx.beginPath(); ctx.arc(ox, oy, 8, 0, Math.PI * 2); ctx.fill(); ctx.stroke();
  233. say(ctx, 'наблюдатель', ox, oy + 17, PAL.dim, 8, 'center');
  234. const deg = Math.round(Math.abs(phi) * 180 / Math.PI);
  235. say(ctx, `угол ${deg}° · видимость до ${Math.round(half * 180 / Math.PI)}°`, 8, h - 10, PAL.dim, 8.5);
  236. S.status = readable
  237. ? { text: `Наблюдатель под углом ${deg}° читает экран: данные раскрыты`, tone: 'bad' }
  238. : { text: `Под углом ${deg}° экран не читается: фильтр работает`, tone: 'ok' };
  239. }
  240. /* --- 2. АКУСТИЧЕСКИЙ: волны, стена, маскирующий шум и разборчивость речи --- */
  241. function sceneAcoustic(ctx, w, h, t, prot, S) {
  242. const sx = w * .12, sy = h * .42, wx = w * .46;
  243. const wallW = prot ? 20 : 5;
  244. const trans = prot ? .04 : .75; // доля звука, прошедшая через стену
  245. const maxR = w * .42;
  246. for (let k = 0; k < 4; k++) {
  247. const r = (t * 80 + k * maxR / 4) % maxR;
  248. const a = 1 - r / maxR;
  249. ctx.beginPath(); ctx.arc(sx, sy, r, 0, Math.PI * 2);
  250. ctx.strokeStyle = `rgba(101,227,255,${(a * .7).toFixed(3)})`; ctx.lineWidth = 1.2; ctx.stroke();
  251. ctx.save();
  252. ctx.beginPath(); ctx.rect(wx + wallW, 0, w, h); ctx.clip();
  253. ctx.beginPath(); ctx.arc(sx, sy, r, 0, Math.PI * 2);
  254. ctx.strokeStyle = prot ? `rgba(255,199,107,${(a * trans * 4).toFixed(3)})` : `rgba(255,101,126,${(a * trans * 1.4).toFixed(3)})`;
  255. ctx.stroke(); ctx.restore();
  256. }
  257. box(ctx, sx - 14, sy - 12, 28, 24, PAL.cyan, '#0f2236');
  258. say(ctx, 'ГОВОРЯЩИЙ', sx, sy + 26, PAL.cyan, 8, 'center');
  259. ctx.fillStyle = prot ? '#3a2e14' : '#2a3848'; ctx.fillRect(wx, 0, wallW, h);
  260. if (prot) {
  261. ctx.strokeStyle = 'rgba(255,199,107,.5)';
  262. for (let y = 0; y < h; y += 8) { ctx.beginPath(); ctx.moveTo(wx, y); ctx.lineTo(wx + wallW, y); ctx.stroke(); }
  263. }
  264. say(ctx, prot ? 'звукоизоляция' : 'тонкая стена', wx + wallW / 2, 12, prot ? PAL.amber : PAL.dim, 7.5, 'center');
  265. if (prot) for (let i = 0; i < 60; i++) {
  266. ctx.fillStyle = `rgba(255,199,107,${rnd(.1, .5).toFixed(2)})`;
  267. ctx.fillRect(rnd(wx + wallW + 6, w - 6), rnd(20, h * .6), 2, 2);
  268. }
  269. const rx0 = wx + wallW + 8, rx1 = w - 8, rc = (rx0 + rx1) / 2;
  270. ctx.strokeStyle = PAL.red; ctx.lineWidth = 1.2;
  271. ctx.beginPath(); ctx.arc(rc, h * .2, 9, 0, Math.PI * 2); ctx.stroke();
  272. say(ctx, 'ПРИЁМНИК', rc, h * .2 + 18, PAL.red, 8, 'center');
  273. const y0 = h * .66, amp = h * .14;
  274. ctx.beginPath();
  275. for (let x = rx0, i = 0; x <= rx1; x += 3, i++) {
  276. const env = (Math.sin(t * 3 + i * .05) + 1) / 2;
  277. const speech = Math.sin(i * .4 + t * 9) * env * .8 + Math.sin(i * .9 - t * 5) * .3;
  278. const noise = (Math.random() - .5) * (prot ? .9 : .08);
  279. const y = y0 - (speech * trans + noise) * amp;
  280. i ? ctx.lineTo(x, y) : ctx.moveTo(x, y);
  281. }
  282. ctx.strokeStyle = prot ? PAL.amber : PAL.red; ctx.lineWidth = 1.2; ctx.stroke();
  283. const phrase = 'СОВЕЩАНИЕ В 15:00';
  284. S.acc += S.dt * trans * 4.4;
  285. if (S.acc > phrase.length + 10) S.acc = 0;
  286. const got = Math.min(phrase.length, Math.floor(S.acc));
  287. say(ctx, phrase.slice(0, got) + '·'.repeat(phrase.length - got), 8, h - 10, prot ? PAL.dim : PAL.red, 9);
  288. S.status = prot
  289. ? { text: `Разборчивость речи ${Math.round(trans * 100)}%: раскрыто ${got} из ${phrase.length} симв.`, tone: 'ok' }
  290. : { text: `Фраза раскрыта: «${phrase.slice(0, got)}»`, tone: 'bad' };
  291. }
  292. /* --- 3. ЭЛЕКТРОМАГНИТНЫЙ: поле, экранирующий корпус и спектр побочного сигнала --- */
  293. function sceneEM(ctx, w, h, t, prot, S) {
  294. const dx = w * .16, dy = h * .5, dw = w * .16, dh = h * .36;
  295. const r0 = prot ? dw * .2 : dw * .6;
  296. const maxR = prot ? dw * .45 : w * .18;
  297. for (let i = 0; i < 26; i++) {
  298. const a = i / 26 * Math.PI * 2 + t * .25;
  299. const r = r0 + ((t * 40 + i * 11) % (maxR - r0));
  300. ctx.fillStyle = `rgba(255,199,107,${((1 - r / maxR) * (prot ? .25 : .8)).toFixed(2)})`;
  301. ctx.fillRect(dx + Math.cos(a) * r - 1, dy + Math.sin(a) * r * .8, 2, 2);
  302. }
  303. box(ctx, dx - dw / 2, dy - dh / 2, dw, dh, PAL.cyan, '#0c1a2a');
  304. box(ctx, dx - 10, dy - 8, 20, 16, PAL.amber, null);
  305. say(ctx, 'ПК / БЛОК', dx, dy + dh / 2 + (prot ? 26 : 12), PAL.cyan, 8, 'center');
  306. if (prot) {
  307. ctx.setLineDash([2, 3]); box(ctx, dx - dw / 2 - 9, dy - dh / 2 - 9, dw + 18, dh + 18, PAL.green, null); ctx.setLineDash([]);
  308. say(ctx, 'экран', dx, dy - dh / 2 - 19, PAL.green, 8, 'center');
  309. }
  310. const x0 = w * .47, x1 = w * .96, y0 = h * .16, y1 = h * .8;
  311. ctx.strokeStyle = 'rgba(101,227,255,.25)'; ctx.beginPath();
  312. ctx.moveTo(x0, y0); ctx.lineTo(x0, y1); ctx.lineTo(x1, y1); ctx.stroke();
  313. const f0 = x0 + (x1 - x0) * .4;
  314. const A0 = prot ? .04 : .9;
  315. const bitIdx = Math.floor(t * 6) % 8;
  316. const bit = (0b10110010 >> (7 - bitIdx)) & 1;
  317. const sbA = (bit ? .32 : .1) * (prot ? .1 : 1);
  318. const floorN = prot ? .24 : .05;
  319. ctx.beginPath();
  320. for (let x = x0; x <= x1; x += 2) {
  321. const g = Math.exp(-((x - f0) ** 2) / 32);
  322. const s = Math.exp(-((x - (f0 - 22)) ** 2) / 12) + Math.exp(-((x - (f0 + 22)) ** 2) / 12);
  323. const v = Math.min(1, floorN * Math.random() + .03 + A0 * g + sbA * s);
  324. const y = y1 - v * (y1 - y0);
  325. x === x0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
  326. }
  327. ctx.strokeStyle = prot ? PAL.amber : PAL.cyan; ctx.lineWidth = 1.2; ctx.stroke();
  328. const yTh = y1 - .35 * (y1 - y0);
  329. ctx.setLineDash([4, 4]); ctx.strokeStyle = 'rgba(92,229,178,.6)';
  330. ctx.beginPath(); ctx.moveTo(x0, yTh); ctx.lineTo(x1, yTh); ctx.stroke(); ctx.setLineDash([]);
  331. const sw = x0 + ((t * .5) % 1) * (x1 - x0);
  332. ctx.strokeStyle = 'rgba(231,237,246,.25)'; ctx.beginPath(); ctx.moveTo(sw, y0); ctx.lineTo(sw, y1); ctx.stroke();
  333. say(ctx, 'СПЕКТР', x0 + 4, y0 - 9, PAL.dim, 8);
  334. say(ctx, `бит ${bit}`, x1, y0 - 9, PAL.amber, 8, 'right');
  335. say(ctx, prot ? 'экран + зашумление' : 'без экранирования', 8, h - 10, PAL.dim, 8.5);
  336. S.status = A0 > .35
  337. ? { text: 'Побочный сигнал выделен: боковые полосы меняются вместе с битами', tone: 'bad' }
  338. : { text: 'Сигнал ниже порога обнаружения: в спектре только шум', tone: 'ok' };
  339. }
  340. /* --- 4. СЕТЕВОЙ: пакеты, перехват на коммутаторе и шифрование --- */
  341. function sceneNetwork(ctx, w, h, t, prot, S) {
  342. const P = { pc: [w * .14, h * .36], fw: [w * .5, h * .36], srv: [w * .86, h * .36], sn: [w * .5, h * .84] };
  343. const bw = 64, bh = 30;
  344. const line = (a, b, col, dash) => {
  345. ctx.beginPath(); ctx.moveTo(a[0], a[1]); ctx.lineTo(b[0], b[1]);
  346. ctx.strokeStyle = col; ctx.lineWidth = 1.2; ctx.setLineDash(dash || []); ctx.stroke(); ctx.setLineDash([]);
  347. };
  348. line(P.pc, P.fw, 'rgba(101,227,255,.45)');
  349. line(P.fw, P.srv, 'rgba(101,227,255,.45)');
  350. const mid = [(P.fw[0] + P.sn[0]) / 2, (P.fw[1] + P.sn[1]) / 2];
  351. if (!prot) line(P.fw, P.sn, PAL.amber, [4, 4]);
  352. else {
  353. line(P.fw, P.sn, 'rgba(255,101,126,.3)', [2, 4]);
  354. ctx.strokeStyle = PAL.red; ctx.lineWidth = 2; ctx.beginPath();
  355. ctx.moveTo(mid[0] - 6, mid[1] - 6); ctx.lineTo(mid[0] + 6, mid[1] + 6);
  356. ctx.moveTo(mid[0] - 6, mid[1] + 6); ctx.lineTo(mid[0] + 6, mid[1] - 6); ctx.stroke();
  357. }
  358. say(ctx, prot ? 'шифрованный канал' : 'открытый текст', (P.pc[0] + P.fw[0]) / 2, P.pc[1] + 26, prot ? PAL.green : PAL.amber, 8, 'center');
  359. const node = (p, label, col) => {
  360. box(ctx, p[0] - bw / 2, p[1] - bh / 2, bw, bh, col, '#0c1a2a');
  361. say(ctx, label, p[0], p[1], PAL.text, 8, 'center', true);
  362. };
  363. node(P.pc, 'ПК', PAL.cyan);
  364. node(P.srv, 'СЕРВЕР', PAL.cyan);
  365. node(P.fw, prot ? 'ЭКРАН' : 'КОММУТ.', prot ? PAL.green : PAL.cyan);
  366. node(P.sn, 'ПЕРЕХВАТЧИК', prot ? PAL.dim : PAL.red);
  367. const plain = ['PIN 4821', 'ДОГОВОР-77', 'СУММА 1.2M', 'PIN 4821', 'OTP 552'];
  368. for (let k = 0; k < plain.length; k++) {
  369. const cyc = t * .45 + k / plain.length;
  370. const n = Math.floor(cyc), p = cyc - n;
  371. let x, y;
  372. if (p < .5) { const q = p * 2; x = P.pc[0] + (P.fw[0] - P.pc[0]) * q; y = P.pc[1]; }
  373. else { const q = (p - .5) * 2; x = P.fw[0] + (P.srv[0] - P.fw[0]) * q; y = P.fw[1]; }
  374. const text = prot ? scramble(plain[k].length) : plain[k];
  375. const pw = 58, ph = 13, py = y - 24;
  376. box(ctx, x - pw / 2, py - ph / 2, pw, ph, prot ? PAL.green : PAL.amber, prot ? 'rgba(92,229,178,.15)' : 'rgba(255,199,107,.18)');
  377. say(ctx, text, x, py, prot ? PAL.green : PAL.amber, 7.5, 'center');
  378. if (p >= .5 && S.seen[k] !== n) {
  379. S.seen[k] = n;
  380. if (prot) { S.blocked++; S.log.push(`${stamp(t)} ОТКАЗ: перехват заблокирован`); }
  381. else { S.cap++; S.log.push(`${stamp(t)} ПЕРЕХВАТ: «${plain[k]}»`); }
  382. S.log = S.log.slice(-3);
  383. }
  384. }
  385. S.log.forEach((s, i) => say(ctx, s, 8, h * .6 + i * 13, prot ? PAL.green : PAL.red, 8));
  386. S.status = prot
  387. ? { text: `Экран блокирует перехват. Отказов: ${S.blocked}, открытого текста нет`, tone: 'ok' }
  388. : { text: `Перехвачено пакетов с открытым текстом: ${S.cap}`, tone: 'bad' };
  389. }
  390. /* --- 5. ФИЗИЧЕСКИЙ: носитель, проходная, СКУД и журнал --- */
  391. function scenePhysical(ctx, w, h, t, prot, S) {
  392. const gx = w * .5, gy = h * .56, a = w * .12, out = w * .9;
  393. const T = 8, p = (t % T) / T;
  394. box(ctx, 0, h * .14, gx - 12, h * .66, 'rgba(101,227,255,.35)', 'rgba(101,227,255,.04)');
  395. say(ctx, 'КАБИНЕТ', 8, h * .14 + 10, PAL.dim, 8);
  396. box(ctx, 4, h * .58, 40, 34, PAL.amber, null);
  397. say(ctx, 'СЕЙФ', 24, h * .58 + 17, PAL.amber, 7, 'center');
  398. ctx.fillStyle = '#1a2a3e'; ctx.fillRect(gx - 16, gy - 30, 6, 60); ctx.fillRect(gx + 10, gy - 30, 6, 60);
  399. if (prot) {
  400. ctx.strokeStyle = PAL.red; ctx.lineWidth = 3;
  401. ctx.beginPath(); ctx.moveTo(gx - 10, gy); ctx.lineTo(gx + 10, gy); ctx.stroke();
  402. const sy = gy - 30 + ((t * 1.5) % 1) * 60;
  403. ctx.strokeStyle = 'rgba(101,227,255,.8)'; ctx.lineWidth = 1.2;
  404. ctx.beginPath(); ctx.moveTo(gx - 16, sy); ctx.lineTo(gx + 16, sy); ctx.stroke();
  405. say(ctx, 'СКУД', gx, gy - 42, PAL.cyan, 8, 'center');
  406. } else {
  407. say(ctx, 'ОТКРЫТО', gx, gy - 42, PAL.red, 8, 'center');
  408. }
  409. const x = prot
  410. ? (p < .5 ? a + (gx - 36 - a) * smooth(p / .5) : (gx - 36) + (a - (gx - 36)) * smooth((p - .5) / .5))
  411. : a + (out - 30 - a) * smooth(p);
  412. const stolen = !prot && p > .8;
  413. figure(ctx, x, gy, PAL.text);
  414. const thiefX = out;
  415. figure(ctx, thiefX, gy, PAL.red);
  416. say(ctx, 'злоумышленник', thiefX, gy + 16, PAL.red, 7.5, 'center');
  417. const fx = stolen ? thiefX - 9 : x + 9, fy = stolen ? gy - 10 : gy - 10;
  418. ctx.fillStyle = PAL.amber; ctx.fillRect(fx - 4, fy - 3, 8, 5);
  419. if (prot) say(ctx, 'шифр.', fx, fy - 9, PAL.green, 7, 'center');
  420. const cyc = Math.floor(t / T);
  421. if (S.seen.phys !== cyc && p > .6) {
  422. S.seen.phys = cyc;
  423. S.log.push(`${stamp(t)} ` + (prot ? 'СКУД: пропуск не предъявлен, вынос запрещён' : 'Проход без учёта: носитель вынесен'));
  424. S.log = S.log.slice(-3);
  425. }
  426. S.log.forEach((s, i) => say(ctx, s, 8, h - 38 + i * 12, prot ? PAL.green : PAL.red, 8));
  427. S.status = prot
  428. ? { text: 'Пропускной режим работает: носитель не выходит из помещения', tone: 'ok' }
  429. : { text: stolen ? 'Носитель вынесен без учёта и передан постороннему' : 'Проход без проверки: носитель выносится наружу', tone: 'bad' };
  430. }
  431. const SCENES = { visual: sceneVisual, acoustic: sceneAcoustic, electromagnetic: sceneEM, network: sceneNetwork, physical: scenePhysical };
  432. function drawScene(dt) {
  433. if (!S.ch) return;
  434. const { ctx, w, h } = sceneC;
  435. if (!w) return;
  436. S.t += dt; S.dt = dt; S.status = null;
  437. ctx.fillStyle = '#060b14'; ctx.fillRect(0, 0, w, h);
  438. gridBg(ctx, w, h);
  439. SCENES[S.ch](ctx, w, h, S.t, S.prot, S);
  440. const st = S.status || { text: '', tone: '' };
  441. if (st.text !== S.last) {
  442. S.last = st.text;
  443. const el = $('#sceneStatus');
  444. el.textContent = st.text;
  445. el.className = 'scene-status ' + st.tone;
  446. }
  447. }
  448. function resetScene() {
  449. S.t = 0; S.acc = 0; S.seen = {}; S.log = []; S.cap = 0; S.blocked = 0; S.last = '';
  450. }
  451. function renderModal() {
  452. const d = CH[S.ch];
  453. $('#modalCode').textContent = d.code;
  454. $('#modalTitle').textContent = d.title;
  455. $('#modalDesc').textContent = d.desc;
  456. $('#modalMech').textContent = d.mech;
  457. $('#modalProt').textContent = d.prot;
  458. $('#modalEx').innerHTML = '<b>Пример:</b> ' + esc(d.ex);
  459. const pt = $('#protToggle');
  460. pt.textContent = S.prot ? 'Снять защиту' : 'Включить защиту';
  461. pt.setAttribute('aria-pressed', String(S.prot));
  462. }
  463. function openChannel(id) {
  464. S.ch = id; S.prot = false; resetScene();
  465. renderModal();
  466. modal.classList.add('open');
  467. sceneC.resize();
  468. addLoop('scene', drawScene);
  469. beep(780, .07, 'triangle');
  470. $('#modalClose').focus();
  471. }
  472. function closeModal() {
  473. modal.classList.remove('open');
  474. removeLoop('scene');
  475. S.ch = null;
  476. }
  477. $$('.ch').forEach(b => b.addEventListener('click', () => openChannel(b.dataset.channel)));
  478. $('#modalClose').addEventListener('click', closeModal);
  479. $('#modalOk').addEventListener('click', closeModal);
  480. $('#protToggle').addEventListener('click', () => {
  481. S.prot = !S.prot; resetScene();
  482. beep(S.prot ? 520 : 300, .08, 'square', .03);
  483. renderModal();
  484. });
  485. modal.addEventListener('click', e => { if (e.target === modal) closeModal(); });
  486. document.addEventListener('keydown', e => { if (e.key === 'Escape' && modal.classList.contains('open')) closeModal(); });
  487. /* ===================== 02. СИМУЛЯТОР ПЕРЕХВАТА ===================== */
  488. const SPB = 8; // отсчётов на бит
  489. const VMIN = -.6, VMAX = 1.2; // диапазон амплитуды на графике
  490. const enc = new TextEncoder(), dec = new TextDecoder('utf-8');
  491. const simText = $('#simText'), simDist = $('#simDist'), simShield = $('#simShield'), simJam = $('#simJam');
  492. const simC = setupCanvas($('#simWave'));
  493. let sim = null;
  494. const curText = () => (simText.value || '').slice(0, 16) || ' ';
  495. function textToBits(text) {
  496. const bytes = enc.encode(text), bits = [];
  497. for (const b of bytes) for (let i = 7; i >= 0; i--) bits.push((b >> i) & 1);
  498. return { bytes, bits };
  499. }
  500. function simParams() {
  501. const d = +simDist.value, s = +simShield.value, j = +simJam.value / 100;
  502. const A = Math.min(1, 1 / (d * d)) * Math.pow(10, -s / 20); // амплитуда на приёмнике
  503. const sigma = .03 + j * .5; // σ шума на отсчёт
  504. const sigmaAvg = sigma / Math.sqrt(SPB); // σ после усреднения
  505. const snrLin = A / sigmaAvg;
  506. const snrDb = 20 * Math.log10(Math.max(A, 1e-9) / sigmaAvg);
  507. const pBit = Q(snrLin / 2); // вероятность ошибки на бит
  508. return { d, s, j, A, sigma, snrDb, pBit };
  509. }
  510. function updateScene() {
  511. const p = simParams();
  512. const nBits = textToBits(curText()).bits.length;
  513. const rxPct = 35 + ((p.d - 1) / 29) * 50;
  514. $('#rx').style.left = rxPct + '%';
  515. $('#rxDist').textContent = p.d + ' м';
  516. $('#dVal').textContent = p.d + ' м';
  517. $('#sVal').textContent = p.s + ' дБ';
  518. $('#jVal').textContent = Math.round(p.j * 100) + '%';
  519. const beam = $('#beam');
  520. beam.style.width = (rxPct - 12) + '%';
  521. beam.style.opacity = clamp(1 + Math.log10(Math.max(p.A, 1e-6)) / 3, .06, 1);
  522. const shield = $('#shield');
  523. shield.style.borderWidth = (1 + p.s / 8) + 'px';
  524. shield.style.borderColor = `rgba(101,227,255,${(.2 + p.s / 100).toFixed(2)})`;
  525. shield.style.boxShadow = p.s > 0 ? `0 0 ${p.s / 2}px rgba(101,227,255,${(p.s / 150).toFixed(2)})` : 'none';
  526. const jam = $('#jam');
  527. jam.style.opacity = (p.j * .9).toFixed(2);
  528. jam.style.width = jam.style.height = (48 + p.j * 60) + 'px';
  529. jam.style.margin = `-${(24 + p.j * 30)}px 0 0 -${(24 + p.j * 30)}px`;
  530. $('#snrVal').textContent = p.snrDb.toFixed(1) + ' дБ';
  531. $('#snrVal').style.color = p.snrDb > 10 ? 'var(--green)' : p.snrDb > 0 ? 'var(--amber)' : 'var(--red)';
  532. const pAll = Math.pow(1 - p.pBit, nBits);
  533. $('#pVal').textContent = pAll < .001 ? '< 0.1%' : (pAll * 100).toFixed(1) + '%';
  534. $('#pVal').style.color = pAll > .6 ? 'var(--green)' : pAll > .2 ? 'var(--amber)' : 'var(--red)';
  535. $('#pBar').style.width = (pAll * 100).toFixed(1) + '%';
  536. const st = $('#sigState');
  537. if (p.snrDb > 10) { st.textContent = '● сигнал выделяется'; st.style.color = 'var(--green)'; }
  538. else if (p.snrDb > 0) { st.textContent = '● сигнал едва различим'; st.style.color = 'var(--amber)'; }
  539. else { st.textContent = '● сигнал тонет в шуме'; st.style.color = 'var(--red)'; }
  540. }
  541. [simDist, simShield, simJam, simText].forEach(el => el.addEventListener('input', updateScene));
  542. updateScene();
  543. function transmit() {
  544. const text = curText();
  545. const { bytes, bits } = textToBits(text);
  546. const p = simParams();
  547. const N = bits.length * SPB;
  548. const ideal = new Float32Array(N), received = new Float32Array(N);
  549. for (let i = 0; i < bits.length; i++) {
  550. for (let k = 0; k < SPB; k++) {
  551. const idx = i * SPB + k;
  552. ideal[idx] = bits[i];
  553. received[idx] = bits[i] * p.A + gauss() * p.sigma;
  554. }
  555. }
  556. // приёмник: усреднение по битовому интервалу и порог A/2
  557. const decBits = []; let errors = 0;
  558. for (let i = 0; i < bits.length; i++) {
  559. let s = 0;
  560. for (let k = 0; k < SPB; k++) s += received[i * SPB + k];
  561. const b = (s / SPB) > p.A / 2 ? 1 : 0;
  562. decBits.push(b);
  563. if (b !== bits[i]) errors++;
  564. }
  565. const outBytes = new Uint8Array(bytes.length);
  566. for (let i = 0; i < bytes.length; i++) {
  567. let v = 0;
  568. for (let j = 0; j < 8; j++) v = (v << 1) | decBits[i * 8 + j];
  569. outBytes[i] = v;
  570. }
  571. sim = {
  572. ideal, received, N, p, text, total: bits.length, errors,
  573. decoded: dec.decode(outBytes),
  574. t: 0, dur: reduceMotion ? .05 : 2.4, finished: false
  575. };
  576. $('#decoded').innerHTML = '<span class="empty">приём…</span>';
  577. $('#verdict').textContent = '';
  578. beep(440, .05, 'sine', .03);
  579. addLoop('sim', drawSim);
  580. }
  581. function drawSim(dt) {
  582. const { ctx, w, h } = simC;
  583. if (!sim || !w) return;
  584. sim.t = Math.min(sim.t + dt, sim.dur);
  585. const n = Math.floor(sim.t / sim.dur * sim.N);
  586. ctx.clearRect(0, 0, w, h);
  587. const laneH = h / 2;
  588. ctx.strokeStyle = 'rgba(101,227,255,.12)'; ctx.lineWidth = 1;
  589. ctx.beginPath(); ctx.moveTo(0, laneH); ctx.lineTo(w, laneH); ctx.stroke();
  590. const yOf = (v, top) => top + 14 + (1 - (v - VMIN) / (VMAX - VMIN)) * (laneH - 28);
  591. // передача
  592. trace(ctx, sim.ideal, n, w, 0, yOf, 'rgba(101,227,255,.95)');
  593. // приём
  594. trace(ctx, sim.received, n, w, laneH, yOf, 'rgba(255,199,107,.9)');
  595. // порог решения
  596. const yTh = yOf(sim.p.A / 2, laneH);
  597. ctx.setLineDash([4, 4]); ctx.strokeStyle = 'rgba(92,229,178,.7)';
  598. ctx.beginPath(); ctx.moveTo(0, yTh); ctx.lineTo(w, yTh); ctx.stroke(); ctx.setLineDash([]);
  599. // курсор развёртки
  600. const xc = n / sim.N * w;
  601. ctx.strokeStyle = 'rgba(231,237,246,.5)';
  602. ctx.beginPath(); ctx.moveTo(xc, 0); ctx.lineTo(xc, h); ctx.stroke();
  603. if (sim.t >= sim.dur && !sim.finished) {
  604. sim.finished = true;
  605. removeLoop('sim');
  606. showResult();
  607. }
  608. }
  609. function trace(ctx, data, n, w, top, yOf, color) {
  610. if (n < 2) return;
  611. ctx.beginPath();
  612. for (let i = 0; i < n; i++) {
  613. const x = i / sim.N * w, y = yOf(data[i], top);
  614. i ? ctx.lineTo(x, y) : ctx.moveTo(x, y);
  615. }
  616. ctx.strokeStyle = color; ctx.lineWidth = 1.3; ctx.stroke();
  617. }
  618. function showResult() {
  619. const s = sim, ber = s.errors / s.total;
  620. const orig = Array.from(s.text), got = Array.from(s.decoded);
  621. let html = '';
  622. got.forEach((ch, i) => {
  623. const ok = ch === orig[i];
  624. html += `<span class="${ok ? 'ok' : 'bad'}" style="animation-delay:${i * 60}ms">${esc(ch)}</span>`;
  625. });
  626. $('#decoded').innerHTML = html || '<span class="empty">пусто</span>';
  627. $('#resBer').textContent = `${(ber * 100).toFixed(1)}%`;
  628. const full = s.errors === 0;
  629. const v = $('#verdict');
  630. v.className = 'verdict ' + (full ? 'bad-text' : 'ok-text');
  631. v.textContent = full
  632. ? `Сообщение получено без ошибок (${s.errors} из ${s.total} бит). Канал утечки работает.`
  633. : `Ошибок ${s.errors} из ${s.total} бит. Сообщение искажено: защита частично сработала.`;
  634. beep(full ? 900 : 260, .12, full ? 'sine' : 'sawtooth', .035);
  635. }
  636. $('#simGo').addEventListener('click', transmit);
  637. $('#simReset').addEventListener('click', () => {
  638. sim = null; removeLoop('sim');
  639. simDist.value = 3; simShield.value = 0; simJam.value = 0; simText.value = 'PIN: 4821';
  640. $('#decoded').innerHTML = '<span class="empty">— нажмите «Передать»</span>';
  641. $('#verdict').textContent = '';
  642. $('#resBer').textContent = '—';
  643. const c = simC; c.ctx.clearRect(0, 0, c.w, c.h);
  644. updateScene();
  645. });
  646. /* ===================== 03. ОЦЕНКА РИСКА ===================== */
  647. const MEAS = [
  648. { id: 'access', name: 'Контроль доступа', hint: 'уязвимость ×0.6', f: 'v', k: .6 },
  649. { id: 'shield', name: 'Экранирование', hint: 'уязвимость ×0.7', f: 'v', k: .7 },
  650. { id: 'monitor', name: 'Мониторинг', hint: 'ущерб ×0.85 (быстрая реакция)', f: 'i', k: .85 },
  651. { id: 'physical', name: 'Физическая охрана', hint: 'угроза ×0.6', f: 't', k: .6 },
  652. { id: 'crypto', name: 'Шифрование', hint: 'ущерб ×0.5', f: 'i', k: .5 }
  653. ];
  654. const RS = { t: 70, v: 70, i: 80 };
  655. const onMeasures = new Set();
  656. const LEVEL = R => R < 25 ? ['НИЗКИЙ', '#5ce5b2'] : R < 50 ? ['СРЕДНИЙ', '#ffc76b'] : R < 75 ? ['ВЫСОКИЙ', '#ff657e'] : ['КРИТИЧЕСКИЙ', '#ff657e'];
  657. function calcRisk(extra) {
  658. const set = extra ? new Set([...onMeasures, extra]) : onMeasures;
  659. const m = { t: 1, v: 1, i: 1 };
  660. set.forEach(id => { const x = MEAS.find(q => q.id === id); m[x.f] *= x.k; });
  661. const eff = { t: RS.t * m.t, v: RS.v * m.v, i: RS.i * m.i };
  662. return { eff, R: eff.t * eff.v * eff.i / 10000 };
  663. }
  664. function buildMeasures() {
  665. $('#measures').innerHTML = MEAS.map(m => `
  666. <button class="measure" data-id="${m.id}" aria-pressed="false">
  667. <b>${esc(m.name)}</b><small>${esc(m.hint)}</small>
  668. </button>`).join('');
  669. $$('.measure').forEach(b => b.addEventListener('click', () => {
  670. const id = b.dataset.id;
  671. onMeasures.has(id) ? onMeasures.delete(id) : onMeasures.add(id);
  672. beep(onMeasures.has(id) ? 620 : 380, .06, 'triangle', .035);
  673. renderRisk();
  674. }));
  675. }
  676. function renderRisk() {
  677. const { eff, R } = calcRisk();
  678. const R0 = calcRisk().R;
  679. $$('.measure').forEach(b => b.setAttribute('aria-pressed', String(onMeasures.has(b.dataset.id))));
  680. $('#needle').style.transform = `rotate(${(-90 + R * 1.8).toFixed(1)}deg)`;
  681. $('#rVal').textContent = R.toFixed(1);
  682. const [lvl, col] = LEVEL(R);
  683. $('#rLevel').textContent = lvl;
  684. $('#rLevel').setAttribute('fill', col);
  685. $('#formula').innerHTML =
  686. `R = T · V · I / 10 000<br>` +
  687. `R = ${eff.t.toFixed(0)} · ${eff.v.toFixed(0)} · ${eff.i.toFixed(0)} / 10 000 = <b>${R.toFixed(1)}</b>` +
  688. (onMeasures.size ? `<br><span style="color:var(--dim)">без мер было бы ${R0.toFixed(1)}</span>` : '');
  689. for (const k of ['t', 'v', 'i']) {
  690. const raw = RS[k];
  691. $(`#${k}Num`).textContent = `${eff[k].toFixed(0)} / ${raw}`;
  692. $(`#${k}Fill`).style.width = clamp(eff[k], 0, 100) + '%';
  693. $(`#${k}Ghost`).style.width = clamp(raw, 0, 100) + '%';
  694. $(`#${k}Val`).textContent = raw;
  695. }
  696. // подсказка: какая мера даст наибольшее снижение риска
  697. const tip = $('#tip');
  698. const candidates = MEAS.filter(m => !onMeasures.has(m.id)).map(m => ({ m, r: calcRisk(m.id).R }));
  699. if (!candidates.length) {
  700. tip.textContent = 'Все меры включены. Остаточный риск показывает, что защита не может устранить угрозу полностью: нужен контроль и пересмотр.';
  701. } else if (R < 10) {
  702. tip.textContent = 'Риск очень низкий. Поддерживайте меры и регулярно проводите переоценку.';
  703. } else {
  704. candidates.sort((a, b) => a.r - b.r);
  705. const best = candidates[0];
  706. tip.innerHTML = `Совет: включите «<b>${esc(best.m.name)}</b>» — риск снизится примерно до ${best.r.toFixed(1)}.`;
  707. }
  708. }
  709. function bindSliders() {
  710. [['sT', 't'], ['sV', 'v'], ['sI', 'i']].forEach(([id, k]) => {
  711. const el = $('#' + id);
  712. el.addEventListener('input', () => { RS[k] = +el.value; renderRisk(); });
  713. });
  714. }
  715. buildMeasures();
  716. bindSliders();
  717. renderRisk();
  718. /* ===================== 04. ИГРА «СОЕДИНИ» ===================== */
  719. const MCH = [
  720. { id: 'visual', name: 'Визуальный' },
  721. { id: 'acoustic', name: 'Акустический' },
  722. { id: 'electromagnetic', name: 'Электромагнитный' },
  723. { id: 'network', name: 'Сетевой' },
  724. { id: 'physical', name: 'Физический' }
  725. ];
  726. const MMS = [
  727. { id: 'filters', name: 'Экранные фильтры и режим «чистого стола»', ch: 'visual' },
  728. { id: 'soundproof', name: 'Звукоизоляция переговорных комнат', ch: 'acoustic' },
  729. { id: 'shield', name: 'Экранирование и фильтрация линий питания', ch: 'electromagnetic' },
  730. { id: 'segment', name: 'Сегментация сети и шифрование трафика', ch: 'network' },
  731. { id: 'access', name: 'Пропускной режим и учёт носителей', ch: 'physical' },
  732. { id: 'bright', name: 'Повысить яркость монитора', ch: null } // лишняя мера
  733. ];
  734. let mSel = null, mPairs = {}, mChecked = false;
  735. function buildMatch() {
  736. const chCol = $('#colCh'), msCol = $('#colMs');
  737. chCol.innerHTML = MCH.map(c => `<button class="mi" data-ch="${c.id}"><b>${esc(c.name)}</b><small></small></button>`).join('');
  738. const order = [...MMS].sort(() => Math.random() - .5);
  739. msCol.innerHTML = order.map(m => `<button class="mi" data-ms="${m.id}">${esc(m.name)}</button>`).join('');
  740. $$('[data-ch]', chCol).forEach(b => b.addEventListener('click', () => clickChannel(b.dataset.ch)));
  741. $$('[data-ms]', msCol).forEach(b => b.addEventListener('click', () => clickMeasure(b.dataset.ms)));
  742. mSel = null; mPairs = {}; mChecked = false;
  743. renderMatch();
  744. }
  745. function clickChannel(id) {
  746. if (mPairs[id]) { delete mPairs[id]; mChecked = false; beep(300, .06, 'triangle', .03); }
  747. else mSel = mSel === id ? null : id;
  748. renderMatch();
  749. }
  750. function clickMeasure(id) {
  751. if (mSel) {
  752. for (const k in mPairs) if (mPairs[k] === id) delete mPairs[k]; // мера переходит к новому каналу
  753. mPairs[mSel] = id;
  754. mSel = null; mChecked = false;
  755. beep(560, .06, 'triangle', .035);
  756. } else {
  757. const k = Object.keys(mPairs).find(c => mPairs[c] === id);
  758. if (k) { delete mPairs[k]; mChecked = false; }
  759. }
  760. renderMatch();
  761. }
  762. function renderMatch() {
  763. $$('#colCh [data-ch]').forEach(b => {
  764. const id = b.dataset.ch, paired = mPairs[id];
  765. const m = paired && MMS.find(x => x.id === paired);
  766. b.classList.toggle('sel', mSel === id);
  767. b.classList.toggle('used', !!paired);
  768. b.classList.toggle('ok', mChecked && !!paired && m.ch === id);
  769. b.classList.toggle('bad', mChecked && !!paired && m.ch !== id);
  770. b.querySelector('small').textContent = m ? '→ ' + (m.name.length > 34 ? m.name.slice(0, 34) + '…' : m.name) : '';
  771. });
  772. $$('#colMs [data-ms]').forEach(b => {
  773. const id = b.dataset.ms;
  774. const k = Object.keys(mPairs).find(c => mPairs[c] === id);
  775. b.classList.toggle('used', !!k);
  776. b.classList.toggle('ok', mChecked && !!k && MMS.find(x => x.id === id).ch === k);
  777. b.classList.toggle('bad', mChecked && !!k && MMS.find(x => x.id === id).ch !== k);
  778. });
  779. requestAnimationFrame(drawLinks);
  780. }
  781. function drawLinks() {
  782. const board = $('#board'), svg = $('#links');
  783. const br = board.getBoundingClientRect();
  784. let html = '';
  785. for (const ch in mPairs) {
  786. const a = board.querySelector(`[data-ch="${ch}"]`).getBoundingClientRect();
  787. const b = board.querySelector(`[data-ms="${mPairs[ch]}"]`).getBoundingClientRect();
  788. const x1 = a.right - br.left, y1 = a.top + a.height / 2 - br.top;
  789. const x2 = b.left - br.left, y2 = b.top + b.height / 2 - br.top;
  790. const mx = (x1 + x2) / 2;
  791. const cls = mChecked ? (MMS.find(x => x.id === mPairs[ch]).ch === ch ? 'ok' : 'bad') : '';
  792. html += `<path class="link ${cls}" pathLength="1" d="M${x1} ${y1} C${mx} ${y1} ${mx} ${y2} ${x2} ${y2}"/>`;
  793. }
  794. svg.innerHTML = html;
  795. const count = Object.keys(mPairs).length;
  796. $('#mScore').textContent = mChecked
  797. ? `ВЕРНО: ${Object.keys(mPairs).filter(c => MMS.find(x => x.id === mPairs[c]).ch === c).length} ИЗ ${MCH.length}`
  798. : `СОЕДИНЕНО: ${count} ИЗ ${MCH.length}`;
  799. }
  800. $('#mCheck').addEventListener('click', () => {
  801. mChecked = true;
  802. const good = Object.keys(mPairs).filter(c => MMS.find(x => x.id === mPairs[c]).ch === c).length;
  803. beep(good === MCH.length ? 880 : 300, .12, good === MCH.length ? 'sine' : 'sawtooth', .035);
  804. renderMatch();
  805. });
  806. $('#mReset').addEventListener('click', buildMatch);
  807. addEventListener('resize', () => requestAnimationFrame(drawLinks));
  808. buildMatch();
  809. /* ===================== 05. ТЕСТ ===================== */
  810. const QUIZ = [
  811. { q: 'Что означает аббревиатура ПЭМИН?',
  812. o: ['Программа электромагнитной изоляции нейронов', 'Побочные электромагнитные излучения и наводки', 'Протокол электронной маскировки информации', 'Пакет эталонных мер информационной надёжности'], a: 1,
  813. e: 'ПЭМИН — побочные электромагнитные излучения и наводки технических средств. Это один из ключевых каналов в ТЗИ.' },
  814. { q: 'Из чего состоит триада информационной безопасности (CIA)?',
  815. o: ['Скорость, надёжность, масштаб', 'Конфиденциальность, целостность, доступность', 'Шифрование, хеширование, подпись', 'Авторизация, аутентификация, аудит'], a: 1,
  816. e: 'Конфиденциальность — доступ только у своих; целостность — данные не искажены; доступность — данные доступны, когда нужны.' },
  817. { q: 'Ослабление сигнала на 20 дБ по амплитуде означает, что он уменьшился примерно в…',
  818. o: ['2 раза', '10 раз', '100 раз', '1000 раз'], a: 1,
  819. e: 'По амплитуде 20 дБ соответствуют уменьшению в 10 раз. Так считает экран в симуляторе.' },
  820. { q: 'Что такое активное зашумление?',
  821. o: ['Звукоизоляция помещения', 'Излучение ложных сигналов, маскирующих полезный', 'Отключение питания при подозрении на утечку', 'Резервное копирование данных'], a: 1,
  822. e: 'Зашумление создаёт помехи, которые маскируют полезный сигнал и затрудняют его выделение приёмником.' },
  823. { q: 'Какой канал утечки связан с речевой информацией и вибрацией конструкций?',
  824. o: ['Визуальный', 'Акустический', 'Сетевой', 'Физический'], a: 1,
  825. e: 'Акустический канал: речь распространяется по воздуху и через строительные конструкции.' },
  826. { q: 'Что такое аттестация объекта информатизации?',
  827. o: ['Выдача сотруднику пропуска', 'Смена паролей раз в год', 'Подтверждение соответствия объекта требованиям безопасности информации', 'Установка антивируса на один компьютер'], a: 2,
  828. e: 'Аттестация документально подтверждает, что объект соответствует требованиям по защите информации.' },
  829. { q: 'Главная задача экранирования оборудования?',
  830. o: ['Ускорить работу процессора', 'Ослабить электромагнитные поля на пути распространения', 'Увеличить яркость экрана', 'Уменьшить вес корпуса'], a: 1,
  831. e: 'Экран (металлический корпус, сетка, фильтры) ослабляет излучение и наводки.' },
  832. { q: 'В упрощённой модели из этой лаборатории риск считают так:',
  833. o: ['Угроза + Уязвимость + Ущерб', 'Угроза × Уязвимость × Ущерб', 'Ущерб − Защита', 'Защита ÷ Угроза'], a: 1,
  834. e: 'Произведение факторов: если хотя бы один фактор близок к нулю, риск почти исчезает.' }
  835. ];
  836. let qi = 0, qScore = 0;
  837. const quizBox = $('#quizBox');
  838. function renderQuiz() {
  839. if (qi >= QUIZ.length) {
  840. const pct = Math.round(qScore / QUIZ.length * 100);
  841. const msg = pct >= 85 ? 'Отличный результат: вы хорошо понимаете принципы ТЗИ.'
  842. : pct >= 60 ? 'Хороший результат. Перечитайте раздел «Каналы утечки».'
  843. : 'Стоит повторить материал: начните с раздела «Каналы» и симулятора.';
  844. quizBox.innerHTML = `
  845. <div class="q-end pop">
  846. <div class="big">${qScore}/${QUIZ.length}</div>
  847. <h3>${pct}% правильных ответов</h3>
  848. <p>${msg}</p>
  849. <button class="btn btn-primary" id="qRestart">ПРОЙТИ ЕЩЁ РАЗ</button>
  850. </div>`;
  851. $('#qRestart').addEventListener('click', () => { qi = 0; qScore = 0; renderQuiz(); });
  852. return;
  853. }
  854. const item = QUIZ[qi];
  855. quizBox.innerHTML = `
  856. <div class="q-top"><span class="label">ВОПРОС ${qi + 1} / ${QUIZ.length}</span><span class="val">ОЧКИ: ${qScore}</span></div>
  857. <div class="q-bar"><i style="width:${qi / QUIZ.length * 100}%"></i></div>
  858. <h3 class="q-text pop">${esc(item.q)}</h3>
  859. <div class="q-opts">${item.o.map((t, i) => `<button class="q-opt" data-i="${i}">${esc(t)}</button>`).join('')}</div>
  860. <div class="q-exp" id="qExp" aria-live="polite"></div>
  861. <div class="q-nav"><button class="btn btn-ghost" id="qNext" disabled>ДАЛЕЕ →</button></div>`;
  862. let answered = false;
  863. $$('.q-opt', quizBox).forEach(b => b.addEventListener('click', () => {
  864. if (answered) return;
  865. answered = true;
  866. const i = +b.dataset.i, ok = i === item.a;
  867. if (ok) { qScore++; beep(880, .1, 'sine'); } else beep(180, .2, 'sawtooth', .04);
  868. $$('.q-opt', quizBox).forEach((x, j) => {
  869. x.disabled = true;
  870. if (j === item.a) x.classList.add('right');
  871. else if (j === i) x.classList.add('wrong');
  872. });
  873. $('#qExp').innerHTML = `<b class="${ok ? 'ok-text' : 'bad-text'}">${ok ? 'Верно!' : 'Неверно.'}</b> ${esc(item.e)}`;
  874. const next = $('#qNext');
  875. next.disabled = false;
  876. next.textContent = qi === QUIZ.length - 1 ? 'ПОКАЗАТЬ РЕЗУЛЬТАТ' : 'ДАЛЕЕ →';
  877. const val = quizBox.querySelector('.val');
  878. if (val) val.textContent = 'ОЧКИ: ' + qScore;
  879. }));
  880. $('#qNext').addEventListener('click', () => { qi++; renderQuiz(); });
  881. }
  882. renderQuiz();
  883. /* ===================== 06. ЧЕК-ЛИСТ ЗАЩИТЫ ===================== */
  884. const CHECK = [
  885. 'Права доступа разграничены по задачам',
  886. 'Экраны защищены фильтрами, блокировка при уходе',
  887. 'Техника проверена на ПЭМИН и наводки (по нормам ТЗИ)',
  888. 'Ведётся учёт всех носителей информации',
  889. 'Конфиденциальные переговоры — в звукоизолированных помещениях',
  890. 'Сетевой трафик шифруется и журналируется',
  891. 'Есть пропускной режим и контроль посетителей',
  892. 'Сотрудники регулярно проходят обучение'
  893. ];
  894. const checksBox = $('#checks');
  895. checksBox.innerHTML = CHECK.map((t, i) =>
  896. `<label class="check"><input type="checkbox" data-i="${i}"><span>${esc(t)}</span></label>`).join('');
  897. function updateChecklist() {
  898. const boxes = $$('input', checksBox);
  899. let done = 0;
  900. boxes.forEach(b => {
  901. const on = b.checked;
  902. b.parentElement.classList.toggle('done', on);
  903. if (on) done++;
  904. });
  905. const pct = Math.round(done / CHECK.length * 100);
  906. $('#cPct').textContent = pct + '%';
  907. $('#cFill').style.width = pct + '%';
  908. $('#cText').innerHTML = pct >= 90
  909. ? '<span class="ok-text">Высокий уровень.</span> Поддерживайте регулярный контроль и переаттестацию.'
  910. : pct >= 50
  911. ? '<span style="color:var(--amber)">Средний уровень.</span> Закройте пробелы в самых рискованных каналах.'
  912. : '<span class="bad-text">Низкий уровень.</span> Защита почти не выстроена: начните с доступа и учёта носителей.';
  913. }
  914. checksBox.addEventListener('change', updateChecklist);
  915. updateChecklist();