| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989 |
- document.documentElement.classList.replace('no-js','js');
- /* ===================== ОБЩИЕ УТИЛИТЫ ===================== */
- const $ = (s, r = document) => r.querySelector(s);
- const $$ = (s, r = document) => [...r.querySelectorAll(s)];
- const esc = s => String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
- const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
- const reduceMotion = !!(window.matchMedia && matchMedia('(prefers-reduced-motion: reduce)').matches);
- /* Звук: Web Audio, включается кнопкой в шапке */
- let soundOn = false, actx = null;
- function beep(freq = 660, dur = .09, type = 'sine', vol = .05) {
- if (!soundOn) return;
- try {
- actx = actx || new (window.AudioContext || window.webkitAudioContext)();
- const o = actx.createOscillator(), g = actx.createGain();
- o.type = type; o.frequency.value = freq;
- g.gain.setValueAtTime(vol, actx.currentTime);
- g.gain.exponentialRampToValueAtTime(0.0001, actx.currentTime + dur);
- o.connect(g).connect(actx.destination);
- o.start(); o.stop(actx.currentTime + dur);
- } catch (e) { /* звук не обязателен */ }
- }
- /* Единый цикл анимации: компоненты подключаются и отключаются, без утечек */
- const loops = new Map();
- let lastTs = performance.now();
- function frame(ts) {
- const dt = Math.min((ts - lastTs) / 1000, .05);
- lastTs = ts;
- loops.forEach(fn => fn(dt));
- requestAnimationFrame(frame);
- }
- requestAnimationFrame(frame);
- const addLoop = (name, fn) => loops.set(name, fn);
- const removeLoop = name => loops.delete(name);
- /* Холст с учётом плотности пикселей и размеров */
- function setupCanvas(canvas) {
- const c = { canvas, ctx: canvas.getContext('2d'), w: 0, h: 0 };
- c.resize = () => {
- const r = canvas.getBoundingClientRect();
- const dpr = Math.min(window.devicePixelRatio || 1, 2);
- canvas.width = Math.max(1, Math.round(r.width * dpr));
- canvas.height = Math.max(1, Math.round(r.height * dpr));
- c.ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
- c.w = r.width; c.h = r.height;
- };
- c.resize();
- if ('ResizeObserver' in window) new ResizeObserver(c.resize).observe(canvas);
- else window.addEventListener('resize', c.resize);
- return c;
- }
- /* Математика: функция ошибок и хвост нормального распределения */
- function erfc(x) {
- const z = Math.abs(x), t = 1 / (1 + .5 * z);
- const r = t * Math.exp(-z * z - 1.26551223 + t * (1.00002368 + t * (.37409196 + t * (.09678418 +
- t * (-.18628806 + t * (.27886807 + t * (-1.13520398 + t * (1.48851587 + t * (-.82215223 + t * .17087277)))))))));
- return x >= 0 ? r : 2 - r;
- }
- const Q = x => .5 * erfc(x / Math.SQRT2);
- 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()); };
- /* ===================== ШАПКА, ПРОГРЕСС, ПОЯВЛЕНИЕ ===================== */
- const clockEl = $('#clock');
- const tickClock = () => { clockEl.textContent = new Date().toLocaleTimeString('ru-RU', { hour12: false }); };
- tickClock(); setInterval(tickClock, 1000);
- const nav = $('#nav'), burger = $('#burger');
- burger.addEventListener('click', () => {
- const open = nav.classList.toggle('open');
- burger.setAttribute('aria-expanded', String(open));
- });
- $$('#nav a').forEach(a => a.addEventListener('click', () => {
- nav.classList.remove('open');
- burger.setAttribute('aria-expanded', 'false');
- }));
- const progressEl = $('#progress');
- const onScroll = () => {
- const max = document.documentElement.scrollHeight - innerHeight;
- progressEl.style.transform = `scaleX(${max > 0 ? scrollY / max : 0})`;
- };
- addEventListener('scroll', onScroll, { passive: true });
- onScroll();
- const revealIO = new IntersectionObserver(entries => entries.forEach(e => {
- if (e.isIntersecting) { e.target.classList.add('in'); revealIO.unobserve(e.target); }
- }), { threshold: .12 });
- $$('.reveal').forEach(el => revealIO.observe(el));
- const activeIO = new IntersectionObserver(entries => entries.forEach(e => {
- if (!e.isIntersecting) return;
- $$('#nav a').forEach(a => a.classList.toggle('active', a.getAttribute('href') === '#' + e.target.id));
- }), { rootMargin: '-45% 0px -50% 0px' });
- $$('main section[id]').forEach(s => activeIO.observe(s));
- const soundBtn = $('#soundBtn');
- soundBtn.addEventListener('click', () => {
- soundOn = !soundOn;
- soundBtn.setAttribute('aria-pressed', String(soundOn));
- soundBtn.textContent = soundOn ? 'ЗВУК: ВКЛ' : 'ЗВУК: ВЫКЛ';
- if (soundOn) beep(660, .12, 'sine', .05);
- });
- /* ===================== HERO: ОСЦИЛЛОГРАФ ===================== */
- const heroC = setupCanvas($('#wave'));
- let heroPhase = 0;
- function drawHero(dt) {
- const { ctx, w, h } = heroC;
- if (!w) return;
- heroPhase += dt * 2;
- ctx.clearRect(0, 0, w, h);
- ctx.strokeStyle = 'rgba(101,227,255,.12)'; ctx.lineWidth = 1;
- ctx.beginPath(); ctx.moveTo(0, h / 2); ctx.lineTo(w, h / 2); ctx.stroke();
- for (let line = 0; line < 3; line++) {
- ctx.beginPath();
- for (let x = 0; x <= w; x += 2) {
- const k = x / w;
- let y = h * .5 + Math.sin(k * 16 + heroPhase + line * .5) * h * .12 + Math.sin(k * 5 - heroPhase * 1.4) * h * .07;
- if (line === 1) y += (Math.random() - .5) * h * .035;
- x === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
- }
- ctx.lineWidth = line === 1 ? 1.6 : .8;
- ctx.strokeStyle = line === 1 ? 'rgba(101,227,255,.9)' : 'rgba(101,227,255,.18)';
- ctx.shadowColor = '#65e3ff';
- ctx.shadowBlur = line === 1 ? 10 : 0;
- ctx.stroke();
- }
- ctx.shadowBlur = 0;
- }
- const heroBtn = $('#heroPlay');
- function setHero(on) {
- if (on) addLoop('hero', drawHero); else removeLoop('hero');
- heroBtn.setAttribute('aria-pressed', String(on));
- heroBtn.textContent = on ? 'Ⅱ Пауза осциллографа' : '▶ Запустить осциллограф';
- }
- heroBtn.addEventListener('click', () => setHero(heroBtn.getAttribute('aria-pressed') !== 'true'));
- setHero(!reduceMotion);
- if (reduceMotion) drawHero(0);
- setInterval(() => { $('#dbVal').textContent = (40 + Math.random() * 5).toFixed(1) + ' dB'; }, 700);
- /* ===================== 01. КАНАЛЫ: ОТДЕЛЬНАЯ СЦЕНА ДЛЯ КАЖДОГО КАНАЛА ===================== */
- const CH = {
- visual: {
- code: 'CHANNEL 01 / VISUAL', title: 'Визуальный канал',
- desc: 'Информация может быть получена простым наблюдением: через экран монитора, бумажные документы, доски или открытые окна.',
- mech: 'Наблюдение за отображаемой или напечатанной информацией без доступа к самой системе.',
- prot: 'Экранные фильтры, монитор развёрнут от прохода, блокировка экрана, режим «чистого стола».',
- ex: 'Распечатка с паролем лежала на столе в открытом офисе, и её прочитал посетитель.'
- },
- acoustic: {
- code: 'CHANNEL 02 / ACOUSTIC', title: 'Акустический канал',
- desc: 'Речевые сведения становятся доступны за пределами помещения через воздух и строительные конструкции (вибрацию).',
- mech: 'Звуковые волны распространяются через воздух, стены, окна, трубы и вентиляцию.',
- prot: 'Звукоизоляция переговорных, виброизоляция, маскирующий шум, правила обсуждения конфиденциальных вопросов.',
- ex: 'Переговоры в соседнем кабинете слышны через тонкую стену и вентиляционный короб.'
- },
- electromagnetic: {
- code: 'CHANNEL 03 / EM', title: 'Электромагнитный канал',
- desc: 'Работающая техника создаёт побочные электромагнитные излучения и наводки (ПЭМИН). При определённых условиях они могут нести информацию, которую обрабатывает устройство.',
- mech: 'Побочные излучения и наводки на линиях связи и питания технических средств.',
- prot: 'Экранирование помещений и оборудования, фильтрация линий, зашумление, размещение техники по нормам ТЗИ.',
- ex: 'Экранирование и фильтры на линиях питания — одна из основных мер, которые проверяют при аттестации.'
- },
- network: {
- code: 'CHANNEL 04 / NETWORK', title: 'Сетевой канал',
- desc: 'Данные могут покинуть организацию по сети при нарушении разграничения доступа, ошибках настройки или заражении устройства.',
- mech: 'Передача данных по коммуникационным каналам, несанкционированное подключение, неправомерный доступ.',
- prot: 'Сегментация сети, разграничение прав, шифрование трафика, журналирование, мониторинг соединений, обновления.',
- ex: 'Файл с персональными данными отправлен на внешний адрес после заражения рабочей станции.'
- },
- physical: {
- code: 'CHANNEL 05 / PHYSICAL', title: 'Физический канал',
- desc: 'Утечка может происходить через потерю флешек и дисков, несанкционированное копирование или вынос документов.',
- mech: 'Физическое перемещение носителя или доступ к устройству вне установленного контроля.',
- prot: 'Учёт носителей, пропускной режим, защищённое хранение, безопасное уничтожение, контроль портов и периферии.',
- ex: 'Незашифрованная флешка с базой клиентов потеряна в такси.'
- }
- };
- const modal = $('#modal');
- const sceneC = setupCanvas($('#chScene'));
- const S = { ch: null, prot: false, t: 0, dt: 0, acc: 0, seen: {}, log: [], cap: 0, blocked: 0, status: null, last: '' };
- const PAL = { cyan: '#65e3ff', green: '#5ce5b2', amber: '#ffc76b', red: '#ff657e', dim: '#5d6e83', text: '#e7edf6' };
- const GLYPHS = '#%&$@x7Qz9<>/';
- function say(ctx, s, x, y, color, sz = 10, align = 'left', bold = false) {
- ctx.fillStyle = color;
- ctx.font = `${bold ? '700 ' : ''}${sz}px "Space Mono", ui-monospace, Consolas, monospace`;
- ctx.textAlign = align; ctx.textBaseline = 'middle';
- ctx.fillText(s, x, y);
- }
- const smooth = x => x * x * (3 - 2 * x);
- const rnd = (a, b) => a + Math.random() * (b - a);
- const scramble = n => Array.from({ length: n }, () => GLYPHS[Math.floor(Math.random() * GLYPHS.length)]).join('');
- const stamp = t => '10:' + String(Math.floor(t) % 60).padStart(2, '0');
- function box(ctx, x, y, w, h, stroke, fill) {
- if (fill) { ctx.fillStyle = fill; ctx.fillRect(x, y, w, h); }
- ctx.strokeStyle = stroke; ctx.lineWidth = 1.2; ctx.strokeRect(x, y, w, h);
- }
- function figure(ctx, x, y, col) {
- ctx.strokeStyle = col; ctx.lineWidth = 1.6;
- ctx.beginPath(); ctx.arc(x, y - 22, 5, 0, Math.PI * 2); ctx.stroke();
- ctx.beginPath();
- ctx.moveTo(x, y - 16); ctx.lineTo(x, y - 6);
- ctx.moveTo(x, y - 6); ctx.lineTo(x - 4, y);
- ctx.moveTo(x, y - 6); ctx.lineTo(x + 4, y);
- ctx.moveTo(x, y - 13); ctx.lineTo(x + 6, y - 9);
- ctx.stroke();
- }
- function gridBg(ctx, w, h) {
- ctx.strokeStyle = 'rgba(101,227,255,.05)'; ctx.lineWidth = 1; ctx.beginPath();
- for (let x = 0; x < w; x += 24) { ctx.moveTo(x, 0); ctx.lineTo(x, h); }
- for (let y = 0; y < h; y += 24) { ctx.moveTo(0, y); ctx.lineTo(w, y); }
- ctx.stroke();
- }
- /* --- 1. ВИЗУАЛЬНЫЙ: конус видимости и фильтр конфиденциальности --- */
- function sceneVisual(ctx, w, h, t, prot, S) {
- const R = Math.min(w * .3, h * .42), mx = w * .3, my = h * .5, mw = w * .2, mh = h * .5;
- const fx = mx + mw / 2;
- const half = prot ? .42 : 1.25; // полуугол видимости экрана, рад
- const phi = Math.sin(t * .45) * 1.15; // угол наблюдателя, рад
- const readable = Math.abs(phi) < half;
- ctx.beginPath(); ctx.moveTo(fx, my);
- ctx.lineTo(fx + R * 1.1 * Math.cos(-half), my + R * 1.1 * Math.sin(-half));
- ctx.lineTo(fx + R * 1.1 * Math.cos(half), my + R * 1.1 * Math.sin(half));
- ctx.closePath();
- ctx.fillStyle = prot ? 'rgba(92,229,178,.07)' : 'rgba(255,101,126,.09)';
- ctx.fill();
- box(ctx, mx - mw / 2, my - mh / 2, mw, mh, 'rgba(101,227,255,.5)', '#0b1624');
- ctx.fillStyle = '#1a2a3e'; ctx.fillRect(mx - 3, my + mh / 2, 6, 10);
- ['ДОГОВОР № 77/26', 'СУММА 1 200 000', 'PIN: 4821', 'СЕКРЕТНО'].forEach((s, i) => {
- const y = my - mh / 2 + 16 + i * 14, x = mx - mw / 2 + 7;
- if (readable) say(ctx, s, x, y, PAL.green, 8.5);
- else { ctx.fillStyle = '#2a3a4d'; ctx.fillRect(x, y - 3, s.length * 5.2, 6); }
- });
- if (prot) {
- ctx.fillStyle = 'rgba(255,199,107,.75)'; ctx.fillRect(fx + 3, my - mh / 2, 3, mh);
- say(ctx, 'фильтр', fx + 9, my - mh / 2 + 6, PAL.amber, 8);
- }
- const ox = mx + R * Math.cos(phi), oy = my + R * Math.sin(phi);
- ctx.setLineDash([3, 4]); ctx.strokeStyle = readable ? PAL.red : PAL.dim;
- ctx.beginPath(); ctx.moveTo(ox, oy); ctx.lineTo(fx, my); ctx.stroke(); ctx.setLineDash([]);
- ctx.fillStyle = '#1b2a40'; ctx.strokeStyle = readable ? PAL.red : PAL.cyan; ctx.lineWidth = 1.5;
- ctx.beginPath(); ctx.arc(ox, oy, 8, 0, Math.PI * 2); ctx.fill(); ctx.stroke();
- say(ctx, 'наблюдатель', ox, oy + 17, PAL.dim, 8, 'center');
- const deg = Math.round(Math.abs(phi) * 180 / Math.PI);
- say(ctx, `угол ${deg}° · видимость до ${Math.round(half * 180 / Math.PI)}°`, 8, h - 10, PAL.dim, 8.5);
- S.status = readable
- ? { text: `Наблюдатель под углом ${deg}° читает экран: данные раскрыты`, tone: 'bad' }
- : { text: `Под углом ${deg}° экран не читается: фильтр работает`, tone: 'ok' };
- }
- /* --- 2. АКУСТИЧЕСКИЙ: волны, стена, маскирующий шум и разборчивость речи --- */
- function sceneAcoustic(ctx, w, h, t, prot, S) {
- const sx = w * .12, sy = h * .42, wx = w * .46;
- const wallW = prot ? 20 : 5;
- const trans = prot ? .04 : .75; // доля звука, прошедшая через стену
- const maxR = w * .42;
- for (let k = 0; k < 4; k++) {
- const r = (t * 80 + k * maxR / 4) % maxR;
- const a = 1 - r / maxR;
- ctx.beginPath(); ctx.arc(sx, sy, r, 0, Math.PI * 2);
- ctx.strokeStyle = `rgba(101,227,255,${(a * .7).toFixed(3)})`; ctx.lineWidth = 1.2; ctx.stroke();
- ctx.save();
- ctx.beginPath(); ctx.rect(wx + wallW, 0, w, h); ctx.clip();
- ctx.beginPath(); ctx.arc(sx, sy, r, 0, Math.PI * 2);
- ctx.strokeStyle = prot ? `rgba(255,199,107,${(a * trans * 4).toFixed(3)})` : `rgba(255,101,126,${(a * trans * 1.4).toFixed(3)})`;
- ctx.stroke(); ctx.restore();
- }
- box(ctx, sx - 14, sy - 12, 28, 24, PAL.cyan, '#0f2236');
- say(ctx, 'ГОВОРЯЩИЙ', sx, sy + 26, PAL.cyan, 8, 'center');
- ctx.fillStyle = prot ? '#3a2e14' : '#2a3848'; ctx.fillRect(wx, 0, wallW, h);
- if (prot) {
- ctx.strokeStyle = 'rgba(255,199,107,.5)';
- for (let y = 0; y < h; y += 8) { ctx.beginPath(); ctx.moveTo(wx, y); ctx.lineTo(wx + wallW, y); ctx.stroke(); }
- }
- say(ctx, prot ? 'звукоизоляция' : 'тонкая стена', wx + wallW / 2, 12, prot ? PAL.amber : PAL.dim, 7.5, 'center');
- if (prot) for (let i = 0; i < 60; i++) {
- ctx.fillStyle = `rgba(255,199,107,${rnd(.1, .5).toFixed(2)})`;
- ctx.fillRect(rnd(wx + wallW + 6, w - 6), rnd(20, h * .6), 2, 2);
- }
- const rx0 = wx + wallW + 8, rx1 = w - 8, rc = (rx0 + rx1) / 2;
- ctx.strokeStyle = PAL.red; ctx.lineWidth = 1.2;
- ctx.beginPath(); ctx.arc(rc, h * .2, 9, 0, Math.PI * 2); ctx.stroke();
- say(ctx, 'ПРИЁМНИК', rc, h * .2 + 18, PAL.red, 8, 'center');
- const y0 = h * .66, amp = h * .14;
- ctx.beginPath();
- for (let x = rx0, i = 0; x <= rx1; x += 3, i++) {
- const env = (Math.sin(t * 3 + i * .05) + 1) / 2;
- const speech = Math.sin(i * .4 + t * 9) * env * .8 + Math.sin(i * .9 - t * 5) * .3;
- const noise = (Math.random() - .5) * (prot ? .9 : .08);
- const y = y0 - (speech * trans + noise) * amp;
- i ? ctx.lineTo(x, y) : ctx.moveTo(x, y);
- }
- ctx.strokeStyle = prot ? PAL.amber : PAL.red; ctx.lineWidth = 1.2; ctx.stroke();
- const phrase = 'СОВЕЩАНИЕ В 15:00';
- S.acc += S.dt * trans * 4.4;
- if (S.acc > phrase.length + 10) S.acc = 0;
- const got = Math.min(phrase.length, Math.floor(S.acc));
- say(ctx, phrase.slice(0, got) + '·'.repeat(phrase.length - got), 8, h - 10, prot ? PAL.dim : PAL.red, 9);
- S.status = prot
- ? { text: `Разборчивость речи ${Math.round(trans * 100)}%: раскрыто ${got} из ${phrase.length} симв.`, tone: 'ok' }
- : { text: `Фраза раскрыта: «${phrase.slice(0, got)}»`, tone: 'bad' };
- }
- /* --- 3. ЭЛЕКТРОМАГНИТНЫЙ: поле, экранирующий корпус и спектр побочного сигнала --- */
- function sceneEM(ctx, w, h, t, prot, S) {
- const dx = w * .16, dy = h * .5, dw = w * .16, dh = h * .36;
- const r0 = prot ? dw * .2 : dw * .6;
- const maxR = prot ? dw * .45 : w * .18;
- for (let i = 0; i < 26; i++) {
- const a = i / 26 * Math.PI * 2 + t * .25;
- const r = r0 + ((t * 40 + i * 11) % (maxR - r0));
- ctx.fillStyle = `rgba(255,199,107,${((1 - r / maxR) * (prot ? .25 : .8)).toFixed(2)})`;
- ctx.fillRect(dx + Math.cos(a) * r - 1, dy + Math.sin(a) * r * .8, 2, 2);
- }
- box(ctx, dx - dw / 2, dy - dh / 2, dw, dh, PAL.cyan, '#0c1a2a');
- box(ctx, dx - 10, dy - 8, 20, 16, PAL.amber, null);
- say(ctx, 'ПК / БЛОК', dx, dy + dh / 2 + (prot ? 26 : 12), PAL.cyan, 8, 'center');
- if (prot) {
- ctx.setLineDash([2, 3]); box(ctx, dx - dw / 2 - 9, dy - dh / 2 - 9, dw + 18, dh + 18, PAL.green, null); ctx.setLineDash([]);
- say(ctx, 'экран', dx, dy - dh / 2 - 19, PAL.green, 8, 'center');
- }
- const x0 = w * .47, x1 = w * .96, y0 = h * .16, y1 = h * .8;
- ctx.strokeStyle = 'rgba(101,227,255,.25)'; ctx.beginPath();
- ctx.moveTo(x0, y0); ctx.lineTo(x0, y1); ctx.lineTo(x1, y1); ctx.stroke();
- const f0 = x0 + (x1 - x0) * .4;
- const A0 = prot ? .04 : .9;
- const bitIdx = Math.floor(t * 6) % 8;
- const bit = (0b10110010 >> (7 - bitIdx)) & 1;
- const sbA = (bit ? .32 : .1) * (prot ? .1 : 1);
- const floorN = prot ? .24 : .05;
- ctx.beginPath();
- for (let x = x0; x <= x1; x += 2) {
- const g = Math.exp(-((x - f0) ** 2) / 32);
- const s = Math.exp(-((x - (f0 - 22)) ** 2) / 12) + Math.exp(-((x - (f0 + 22)) ** 2) / 12);
- const v = Math.min(1, floorN * Math.random() + .03 + A0 * g + sbA * s);
- const y = y1 - v * (y1 - y0);
- x === x0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
- }
- ctx.strokeStyle = prot ? PAL.amber : PAL.cyan; ctx.lineWidth = 1.2; ctx.stroke();
- const yTh = y1 - .35 * (y1 - y0);
- ctx.setLineDash([4, 4]); ctx.strokeStyle = 'rgba(92,229,178,.6)';
- ctx.beginPath(); ctx.moveTo(x0, yTh); ctx.lineTo(x1, yTh); ctx.stroke(); ctx.setLineDash([]);
- const sw = x0 + ((t * .5) % 1) * (x1 - x0);
- ctx.strokeStyle = 'rgba(231,237,246,.25)'; ctx.beginPath(); ctx.moveTo(sw, y0); ctx.lineTo(sw, y1); ctx.stroke();
- say(ctx, 'СПЕКТР', x0 + 4, y0 - 9, PAL.dim, 8);
- say(ctx, `бит ${bit}`, x1, y0 - 9, PAL.amber, 8, 'right');
- say(ctx, prot ? 'экран + зашумление' : 'без экранирования', 8, h - 10, PAL.dim, 8.5);
- S.status = A0 > .35
- ? { text: 'Побочный сигнал выделен: боковые полосы меняются вместе с битами', tone: 'bad' }
- : { text: 'Сигнал ниже порога обнаружения: в спектре только шум', tone: 'ok' };
- }
- /* --- 4. СЕТЕВОЙ: пакеты, перехват на коммутаторе и шифрование --- */
- function sceneNetwork(ctx, w, h, t, prot, S) {
- const P = { pc: [w * .14, h * .36], fw: [w * .5, h * .36], srv: [w * .86, h * .36], sn: [w * .5, h * .84] };
- const bw = 64, bh = 30;
- const line = (a, b, col, dash) => {
- ctx.beginPath(); ctx.moveTo(a[0], a[1]); ctx.lineTo(b[0], b[1]);
- ctx.strokeStyle = col; ctx.lineWidth = 1.2; ctx.setLineDash(dash || []); ctx.stroke(); ctx.setLineDash([]);
- };
- line(P.pc, P.fw, 'rgba(101,227,255,.45)');
- line(P.fw, P.srv, 'rgba(101,227,255,.45)');
- const mid = [(P.fw[0] + P.sn[0]) / 2, (P.fw[1] + P.sn[1]) / 2];
- if (!prot) line(P.fw, P.sn, PAL.amber, [4, 4]);
- else {
- line(P.fw, P.sn, 'rgba(255,101,126,.3)', [2, 4]);
- ctx.strokeStyle = PAL.red; ctx.lineWidth = 2; ctx.beginPath();
- ctx.moveTo(mid[0] - 6, mid[1] - 6); ctx.lineTo(mid[0] + 6, mid[1] + 6);
- ctx.moveTo(mid[0] - 6, mid[1] + 6); ctx.lineTo(mid[0] + 6, mid[1] - 6); ctx.stroke();
- }
- say(ctx, prot ? 'шифрованный канал' : 'открытый текст', (P.pc[0] + P.fw[0]) / 2, P.pc[1] + 26, prot ? PAL.green : PAL.amber, 8, 'center');
- const node = (p, label, col) => {
- box(ctx, p[0] - bw / 2, p[1] - bh / 2, bw, bh, col, '#0c1a2a');
- say(ctx, label, p[0], p[1], PAL.text, 8, 'center', true);
- };
- node(P.pc, 'ПК', PAL.cyan);
- node(P.srv, 'СЕРВЕР', PAL.cyan);
- node(P.fw, prot ? 'ЭКРАН' : 'КОММУТ.', prot ? PAL.green : PAL.cyan);
- node(P.sn, 'ПЕРЕХВАТЧИК', prot ? PAL.dim : PAL.red);
- const plain = ['PIN 4821', 'ДОГОВОР-77', 'СУММА 1.2M', 'PIN 4821', 'OTP 552'];
- for (let k = 0; k < plain.length; k++) {
- const cyc = t * .45 + k / plain.length;
- const n = Math.floor(cyc), p = cyc - n;
- let x, y;
- if (p < .5) { const q = p * 2; x = P.pc[0] + (P.fw[0] - P.pc[0]) * q; y = P.pc[1]; }
- else { const q = (p - .5) * 2; x = P.fw[0] + (P.srv[0] - P.fw[0]) * q; y = P.fw[1]; }
- const text = prot ? scramble(plain[k].length) : plain[k];
- const pw = 58, ph = 13, py = y - 24;
- 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)');
- say(ctx, text, x, py, prot ? PAL.green : PAL.amber, 7.5, 'center');
- if (p >= .5 && S.seen[k] !== n) {
- S.seen[k] = n;
- if (prot) { S.blocked++; S.log.push(`${stamp(t)} ОТКАЗ: перехват заблокирован`); }
- else { S.cap++; S.log.push(`${stamp(t)} ПЕРЕХВАТ: «${plain[k]}»`); }
- S.log = S.log.slice(-3);
- }
- }
- S.log.forEach((s, i) => say(ctx, s, 8, h * .6 + i * 13, prot ? PAL.green : PAL.red, 8));
- S.status = prot
- ? { text: `Экран блокирует перехват. Отказов: ${S.blocked}, открытого текста нет`, tone: 'ok' }
- : { text: `Перехвачено пакетов с открытым текстом: ${S.cap}`, tone: 'bad' };
- }
- /* --- 5. ФИЗИЧЕСКИЙ: носитель, проходная, СКУД и журнал --- */
- function scenePhysical(ctx, w, h, t, prot, S) {
- const gx = w * .5, gy = h * .56, a = w * .12, out = w * .9;
- const T = 8, p = (t % T) / T;
- box(ctx, 0, h * .14, gx - 12, h * .66, 'rgba(101,227,255,.35)', 'rgba(101,227,255,.04)');
- say(ctx, 'КАБИНЕТ', 8, h * .14 + 10, PAL.dim, 8);
- box(ctx, 4, h * .58, 40, 34, PAL.amber, null);
- say(ctx, 'СЕЙФ', 24, h * .58 + 17, PAL.amber, 7, 'center');
- ctx.fillStyle = '#1a2a3e'; ctx.fillRect(gx - 16, gy - 30, 6, 60); ctx.fillRect(gx + 10, gy - 30, 6, 60);
- if (prot) {
- ctx.strokeStyle = PAL.red; ctx.lineWidth = 3;
- ctx.beginPath(); ctx.moveTo(gx - 10, gy); ctx.lineTo(gx + 10, gy); ctx.stroke();
- const sy = gy - 30 + ((t * 1.5) % 1) * 60;
- ctx.strokeStyle = 'rgba(101,227,255,.8)'; ctx.lineWidth = 1.2;
- ctx.beginPath(); ctx.moveTo(gx - 16, sy); ctx.lineTo(gx + 16, sy); ctx.stroke();
- say(ctx, 'СКУД', gx, gy - 42, PAL.cyan, 8, 'center');
- } else {
- say(ctx, 'ОТКРЫТО', gx, gy - 42, PAL.red, 8, 'center');
- }
- const x = prot
- ? (p < .5 ? a + (gx - 36 - a) * smooth(p / .5) : (gx - 36) + (a - (gx - 36)) * smooth((p - .5) / .5))
- : a + (out - 30 - a) * smooth(p);
- const stolen = !prot && p > .8;
- figure(ctx, x, gy, PAL.text);
- const thiefX = out;
- figure(ctx, thiefX, gy, PAL.red);
- say(ctx, 'злоумышленник', thiefX, gy + 16, PAL.red, 7.5, 'center');
- const fx = stolen ? thiefX - 9 : x + 9, fy = stolen ? gy - 10 : gy - 10;
- ctx.fillStyle = PAL.amber; ctx.fillRect(fx - 4, fy - 3, 8, 5);
- if (prot) say(ctx, 'шифр.', fx, fy - 9, PAL.green, 7, 'center');
- const cyc = Math.floor(t / T);
- if (S.seen.phys !== cyc && p > .6) {
- S.seen.phys = cyc;
- S.log.push(`${stamp(t)} ` + (prot ? 'СКУД: пропуск не предъявлен, вынос запрещён' : 'Проход без учёта: носитель вынесен'));
- S.log = S.log.slice(-3);
- }
- S.log.forEach((s, i) => say(ctx, s, 8, h - 38 + i * 12, prot ? PAL.green : PAL.red, 8));
- S.status = prot
- ? { text: 'Пропускной режим работает: носитель не выходит из помещения', tone: 'ok' }
- : { text: stolen ? 'Носитель вынесен без учёта и передан постороннему' : 'Проход без проверки: носитель выносится наружу', tone: 'bad' };
- }
- const SCENES = { visual: sceneVisual, acoustic: sceneAcoustic, electromagnetic: sceneEM, network: sceneNetwork, physical: scenePhysical };
- function drawScene(dt) {
- if (!S.ch) return;
- const { ctx, w, h } = sceneC;
- if (!w) return;
- S.t += dt; S.dt = dt; S.status = null;
- ctx.fillStyle = '#060b14'; ctx.fillRect(0, 0, w, h);
- gridBg(ctx, w, h);
- SCENES[S.ch](ctx, w, h, S.t, S.prot, S);
- const st = S.status || { text: '', tone: '' };
- if (st.text !== S.last) {
- S.last = st.text;
- const el = $('#sceneStatus');
- el.textContent = st.text;
- el.className = 'scene-status ' + st.tone;
- }
- }
- function resetScene() {
- S.t = 0; S.acc = 0; S.seen = {}; S.log = []; S.cap = 0; S.blocked = 0; S.last = '';
- }
- function renderModal() {
- const d = CH[S.ch];
- $('#modalCode').textContent = d.code;
- $('#modalTitle').textContent = d.title;
- $('#modalDesc').textContent = d.desc;
- $('#modalMech').textContent = d.mech;
- $('#modalProt').textContent = d.prot;
- $('#modalEx').innerHTML = '<b>Пример:</b> ' + esc(d.ex);
- const pt = $('#protToggle');
- pt.textContent = S.prot ? 'Снять защиту' : 'Включить защиту';
- pt.setAttribute('aria-pressed', String(S.prot));
- }
- function openChannel(id) {
- S.ch = id; S.prot = false; resetScene();
- renderModal();
- modal.classList.add('open');
- sceneC.resize();
- addLoop('scene', drawScene);
- beep(780, .07, 'triangle');
- $('#modalClose').focus();
- }
- function closeModal() {
- modal.classList.remove('open');
- removeLoop('scene');
- S.ch = null;
- }
- $$('.ch').forEach(b => b.addEventListener('click', () => openChannel(b.dataset.channel)));
- $('#modalClose').addEventListener('click', closeModal);
- $('#modalOk').addEventListener('click', closeModal);
- $('#protToggle').addEventListener('click', () => {
- S.prot = !S.prot; resetScene();
- beep(S.prot ? 520 : 300, .08, 'square', .03);
- renderModal();
- });
- modal.addEventListener('click', e => { if (e.target === modal) closeModal(); });
- document.addEventListener('keydown', e => { if (e.key === 'Escape' && modal.classList.contains('open')) closeModal(); });
- /* ===================== 02. СИМУЛЯТОР ПЕРЕХВАТА ===================== */
- const SPB = 8; // отсчётов на бит
- const VMIN = -.6, VMAX = 1.2; // диапазон амплитуды на графике
- const enc = new TextEncoder(), dec = new TextDecoder('utf-8');
- const simText = $('#simText'), simDist = $('#simDist'), simShield = $('#simShield'), simJam = $('#simJam');
- const simC = setupCanvas($('#simWave'));
- let sim = null;
- const curText = () => (simText.value || '').slice(0, 16) || ' ';
- function textToBits(text) {
- const bytes = enc.encode(text), bits = [];
- for (const b of bytes) for (let i = 7; i >= 0; i--) bits.push((b >> i) & 1);
- return { bytes, bits };
- }
- function simParams() {
- const d = +simDist.value, s = +simShield.value, j = +simJam.value / 100;
- const A = Math.min(1, 1 / (d * d)) * Math.pow(10, -s / 20); // амплитуда на приёмнике
- const sigma = .03 + j * .5; // σ шума на отсчёт
- const sigmaAvg = sigma / Math.sqrt(SPB); // σ после усреднения
- const snrLin = A / sigmaAvg;
- const snrDb = 20 * Math.log10(Math.max(A, 1e-9) / sigmaAvg);
- const pBit = Q(snrLin / 2); // вероятность ошибки на бит
- return { d, s, j, A, sigma, snrDb, pBit };
- }
- function updateScene() {
- const p = simParams();
- const nBits = textToBits(curText()).bits.length;
- const rxPct = 35 + ((p.d - 1) / 29) * 50;
- $('#rx').style.left = rxPct + '%';
- $('#rxDist').textContent = p.d + ' м';
- $('#dVal').textContent = p.d + ' м';
- $('#sVal').textContent = p.s + ' дБ';
- $('#jVal').textContent = Math.round(p.j * 100) + '%';
- const beam = $('#beam');
- beam.style.width = (rxPct - 12) + '%';
- beam.style.opacity = clamp(1 + Math.log10(Math.max(p.A, 1e-6)) / 3, .06, 1);
- const shield = $('#shield');
- shield.style.borderWidth = (1 + p.s / 8) + 'px';
- shield.style.borderColor = `rgba(101,227,255,${(.2 + p.s / 100).toFixed(2)})`;
- shield.style.boxShadow = p.s > 0 ? `0 0 ${p.s / 2}px rgba(101,227,255,${(p.s / 150).toFixed(2)})` : 'none';
- const jam = $('#jam');
- jam.style.opacity = (p.j * .9).toFixed(2);
- jam.style.width = jam.style.height = (48 + p.j * 60) + 'px';
- jam.style.margin = `-${(24 + p.j * 30)}px 0 0 -${(24 + p.j * 30)}px`;
- $('#snrVal').textContent = p.snrDb.toFixed(1) + ' дБ';
- $('#snrVal').style.color = p.snrDb > 10 ? 'var(--green)' : p.snrDb > 0 ? 'var(--amber)' : 'var(--red)';
- const pAll = Math.pow(1 - p.pBit, nBits);
- $('#pVal').textContent = pAll < .001 ? '< 0.1%' : (pAll * 100).toFixed(1) + '%';
- $('#pVal').style.color = pAll > .6 ? 'var(--green)' : pAll > .2 ? 'var(--amber)' : 'var(--red)';
- $('#pBar').style.width = (pAll * 100).toFixed(1) + '%';
- const st = $('#sigState');
- if (p.snrDb > 10) { st.textContent = '● сигнал выделяется'; st.style.color = 'var(--green)'; }
- else if (p.snrDb > 0) { st.textContent = '● сигнал едва различим'; st.style.color = 'var(--amber)'; }
- else { st.textContent = '● сигнал тонет в шуме'; st.style.color = 'var(--red)'; }
- }
- [simDist, simShield, simJam, simText].forEach(el => el.addEventListener('input', updateScene));
- updateScene();
- function transmit() {
- const text = curText();
- const { bytes, bits } = textToBits(text);
- const p = simParams();
- const N = bits.length * SPB;
- const ideal = new Float32Array(N), received = new Float32Array(N);
- for (let i = 0; i < bits.length; i++) {
- for (let k = 0; k < SPB; k++) {
- const idx = i * SPB + k;
- ideal[idx] = bits[i];
- received[idx] = bits[i] * p.A + gauss() * p.sigma;
- }
- }
- // приёмник: усреднение по битовому интервалу и порог A/2
- const decBits = []; let errors = 0;
- for (let i = 0; i < bits.length; i++) {
- let s = 0;
- for (let k = 0; k < SPB; k++) s += received[i * SPB + k];
- const b = (s / SPB) > p.A / 2 ? 1 : 0;
- decBits.push(b);
- if (b !== bits[i]) errors++;
- }
- const outBytes = new Uint8Array(bytes.length);
- for (let i = 0; i < bytes.length; i++) {
- let v = 0;
- for (let j = 0; j < 8; j++) v = (v << 1) | decBits[i * 8 + j];
- outBytes[i] = v;
- }
- sim = {
- ideal, received, N, p, text, total: bits.length, errors,
- decoded: dec.decode(outBytes),
- t: 0, dur: reduceMotion ? .05 : 2.4, finished: false
- };
- $('#decoded').innerHTML = '<span class="empty">приём…</span>';
- $('#verdict').textContent = '';
- beep(440, .05, 'sine', .03);
- addLoop('sim', drawSim);
- }
- function drawSim(dt) {
- const { ctx, w, h } = simC;
- if (!sim || !w) return;
- sim.t = Math.min(sim.t + dt, sim.dur);
- const n = Math.floor(sim.t / sim.dur * sim.N);
- ctx.clearRect(0, 0, w, h);
- const laneH = h / 2;
- ctx.strokeStyle = 'rgba(101,227,255,.12)'; ctx.lineWidth = 1;
- ctx.beginPath(); ctx.moveTo(0, laneH); ctx.lineTo(w, laneH); ctx.stroke();
- const yOf = (v, top) => top + 14 + (1 - (v - VMIN) / (VMAX - VMIN)) * (laneH - 28);
- // передача
- trace(ctx, sim.ideal, n, w, 0, yOf, 'rgba(101,227,255,.95)');
- // приём
- trace(ctx, sim.received, n, w, laneH, yOf, 'rgba(255,199,107,.9)');
- // порог решения
- const yTh = yOf(sim.p.A / 2, laneH);
- ctx.setLineDash([4, 4]); ctx.strokeStyle = 'rgba(92,229,178,.7)';
- ctx.beginPath(); ctx.moveTo(0, yTh); ctx.lineTo(w, yTh); ctx.stroke(); ctx.setLineDash([]);
- // курсор развёртки
- const xc = n / sim.N * w;
- ctx.strokeStyle = 'rgba(231,237,246,.5)';
- ctx.beginPath(); ctx.moveTo(xc, 0); ctx.lineTo(xc, h); ctx.stroke();
- if (sim.t >= sim.dur && !sim.finished) {
- sim.finished = true;
- removeLoop('sim');
- showResult();
- }
- }
- function trace(ctx, data, n, w, top, yOf, color) {
- if (n < 2) return;
- ctx.beginPath();
- for (let i = 0; i < n; i++) {
- const x = i / sim.N * w, y = yOf(data[i], top);
- i ? ctx.lineTo(x, y) : ctx.moveTo(x, y);
- }
- ctx.strokeStyle = color; ctx.lineWidth = 1.3; ctx.stroke();
- }
- function showResult() {
- const s = sim, ber = s.errors / s.total;
- const orig = Array.from(s.text), got = Array.from(s.decoded);
- let html = '';
- got.forEach((ch, i) => {
- const ok = ch === orig[i];
- html += `<span class="${ok ? 'ok' : 'bad'}" style="animation-delay:${i * 60}ms">${esc(ch)}</span>`;
- });
- $('#decoded').innerHTML = html || '<span class="empty">пусто</span>';
- $('#resBer').textContent = `${(ber * 100).toFixed(1)}%`;
- const full = s.errors === 0;
- const v = $('#verdict');
- v.className = 'verdict ' + (full ? 'bad-text' : 'ok-text');
- v.textContent = full
- ? `Сообщение получено без ошибок (${s.errors} из ${s.total} бит). Канал утечки работает.`
- : `Ошибок ${s.errors} из ${s.total} бит. Сообщение искажено: защита частично сработала.`;
- beep(full ? 900 : 260, .12, full ? 'sine' : 'sawtooth', .035);
- }
- $('#simGo').addEventListener('click', transmit);
- $('#simReset').addEventListener('click', () => {
- sim = null; removeLoop('sim');
- simDist.value = 3; simShield.value = 0; simJam.value = 0; simText.value = 'PIN: 4821';
- $('#decoded').innerHTML = '<span class="empty">— нажмите «Передать»</span>';
- $('#verdict').textContent = '';
- $('#resBer').textContent = '—';
- const c = simC; c.ctx.clearRect(0, 0, c.w, c.h);
- updateScene();
- });
- /* ===================== 03. ОЦЕНКА РИСКА ===================== */
- const MEAS = [
- { id: 'access', name: 'Контроль доступа', hint: 'уязвимость ×0.6', f: 'v', k: .6 },
- { id: 'shield', name: 'Экранирование', hint: 'уязвимость ×0.7', f: 'v', k: .7 },
- { id: 'monitor', name: 'Мониторинг', hint: 'ущерб ×0.85 (быстрая реакция)', f: 'i', k: .85 },
- { id: 'physical', name: 'Физическая охрана', hint: 'угроза ×0.6', f: 't', k: .6 },
- { id: 'crypto', name: 'Шифрование', hint: 'ущерб ×0.5', f: 'i', k: .5 }
- ];
- const RS = { t: 70, v: 70, i: 80 };
- const onMeasures = new Set();
- const LEVEL = R => R < 25 ? ['НИЗКИЙ', '#5ce5b2'] : R < 50 ? ['СРЕДНИЙ', '#ffc76b'] : R < 75 ? ['ВЫСОКИЙ', '#ff657e'] : ['КРИТИЧЕСКИЙ', '#ff657e'];
- function calcRisk(extra) {
- const set = extra ? new Set([...onMeasures, extra]) : onMeasures;
- const m = { t: 1, v: 1, i: 1 };
- set.forEach(id => { const x = MEAS.find(q => q.id === id); m[x.f] *= x.k; });
- const eff = { t: RS.t * m.t, v: RS.v * m.v, i: RS.i * m.i };
- return { eff, R: eff.t * eff.v * eff.i / 10000 };
- }
- function buildMeasures() {
- $('#measures').innerHTML = MEAS.map(m => `
- <button class="measure" data-id="${m.id}" aria-pressed="false">
- <b>${esc(m.name)}</b><small>${esc(m.hint)}</small>
- </button>`).join('');
- $$('.measure').forEach(b => b.addEventListener('click', () => {
- const id = b.dataset.id;
- onMeasures.has(id) ? onMeasures.delete(id) : onMeasures.add(id);
- beep(onMeasures.has(id) ? 620 : 380, .06, 'triangle', .035);
- renderRisk();
- }));
- }
- function renderRisk() {
- const { eff, R } = calcRisk();
- const R0 = calcRisk().R;
- $$('.measure').forEach(b => b.setAttribute('aria-pressed', String(onMeasures.has(b.dataset.id))));
- $('#needle').style.transform = `rotate(${(-90 + R * 1.8).toFixed(1)}deg)`;
- $('#rVal').textContent = R.toFixed(1);
- const [lvl, col] = LEVEL(R);
- $('#rLevel').textContent = lvl;
- $('#rLevel').setAttribute('fill', col);
- $('#formula').innerHTML =
- `R = T · V · I / 10 000<br>` +
- `R = ${eff.t.toFixed(0)} · ${eff.v.toFixed(0)} · ${eff.i.toFixed(0)} / 10 000 = <b>${R.toFixed(1)}</b>` +
- (onMeasures.size ? `<br><span style="color:var(--dim)">без мер было бы ${R0.toFixed(1)}</span>` : '');
- for (const k of ['t', 'v', 'i']) {
- const raw = RS[k];
- $(`#${k}Num`).textContent = `${eff[k].toFixed(0)} / ${raw}`;
- $(`#${k}Fill`).style.width = clamp(eff[k], 0, 100) + '%';
- $(`#${k}Ghost`).style.width = clamp(raw, 0, 100) + '%';
- $(`#${k}Val`).textContent = raw;
- }
- // подсказка: какая мера даст наибольшее снижение риска
- const tip = $('#tip');
- const candidates = MEAS.filter(m => !onMeasures.has(m.id)).map(m => ({ m, r: calcRisk(m.id).R }));
- if (!candidates.length) {
- tip.textContent = 'Все меры включены. Остаточный риск показывает, что защита не может устранить угрозу полностью: нужен контроль и пересмотр.';
- } else if (R < 10) {
- tip.textContent = 'Риск очень низкий. Поддерживайте меры и регулярно проводите переоценку.';
- } else {
- candidates.sort((a, b) => a.r - b.r);
- const best = candidates[0];
- tip.innerHTML = `Совет: включите «<b>${esc(best.m.name)}</b>» — риск снизится примерно до ${best.r.toFixed(1)}.`;
- }
- }
- function bindSliders() {
- [['sT', 't'], ['sV', 'v'], ['sI', 'i']].forEach(([id, k]) => {
- const el = $('#' + id);
- el.addEventListener('input', () => { RS[k] = +el.value; renderRisk(); });
- });
- }
- buildMeasures();
- bindSliders();
- renderRisk();
- /* ===================== 04. ИГРА «СОЕДИНИ» ===================== */
- const MCH = [
- { id: 'visual', name: 'Визуальный' },
- { id: 'acoustic', name: 'Акустический' },
- { id: 'electromagnetic', name: 'Электромагнитный' },
- { id: 'network', name: 'Сетевой' },
- { id: 'physical', name: 'Физический' }
- ];
- const MMS = [
- { id: 'filters', name: 'Экранные фильтры и режим «чистого стола»', ch: 'visual' },
- { id: 'soundproof', name: 'Звукоизоляция переговорных комнат', ch: 'acoustic' },
- { id: 'shield', name: 'Экранирование и фильтрация линий питания', ch: 'electromagnetic' },
- { id: 'segment', name: 'Сегментация сети и шифрование трафика', ch: 'network' },
- { id: 'access', name: 'Пропускной режим и учёт носителей', ch: 'physical' },
- { id: 'bright', name: 'Повысить яркость монитора', ch: null } // лишняя мера
- ];
- let mSel = null, mPairs = {}, mChecked = false;
- function buildMatch() {
- const chCol = $('#colCh'), msCol = $('#colMs');
- chCol.innerHTML = MCH.map(c => `<button class="mi" data-ch="${c.id}"><b>${esc(c.name)}</b><small></small></button>`).join('');
- const order = [...MMS].sort(() => Math.random() - .5);
- msCol.innerHTML = order.map(m => `<button class="mi" data-ms="${m.id}">${esc(m.name)}</button>`).join('');
- $$('[data-ch]', chCol).forEach(b => b.addEventListener('click', () => clickChannel(b.dataset.ch)));
- $$('[data-ms]', msCol).forEach(b => b.addEventListener('click', () => clickMeasure(b.dataset.ms)));
- mSel = null; mPairs = {}; mChecked = false;
- renderMatch();
- }
- function clickChannel(id) {
- if (mPairs[id]) { delete mPairs[id]; mChecked = false; beep(300, .06, 'triangle', .03); }
- else mSel = mSel === id ? null : id;
- renderMatch();
- }
- function clickMeasure(id) {
- if (mSel) {
- for (const k in mPairs) if (mPairs[k] === id) delete mPairs[k]; // мера переходит к новому каналу
- mPairs[mSel] = id;
- mSel = null; mChecked = false;
- beep(560, .06, 'triangle', .035);
- } else {
- const k = Object.keys(mPairs).find(c => mPairs[c] === id);
- if (k) { delete mPairs[k]; mChecked = false; }
- }
- renderMatch();
- }
- function renderMatch() {
- $$('#colCh [data-ch]').forEach(b => {
- const id = b.dataset.ch, paired = mPairs[id];
- const m = paired && MMS.find(x => x.id === paired);
- b.classList.toggle('sel', mSel === id);
- b.classList.toggle('used', !!paired);
- b.classList.toggle('ok', mChecked && !!paired && m.ch === id);
- b.classList.toggle('bad', mChecked && !!paired && m.ch !== id);
- b.querySelector('small').textContent = m ? '→ ' + (m.name.length > 34 ? m.name.slice(0, 34) + '…' : m.name) : '';
- });
- $$('#colMs [data-ms]').forEach(b => {
- const id = b.dataset.ms;
- const k = Object.keys(mPairs).find(c => mPairs[c] === id);
- b.classList.toggle('used', !!k);
- b.classList.toggle('ok', mChecked && !!k && MMS.find(x => x.id === id).ch === k);
- b.classList.toggle('bad', mChecked && !!k && MMS.find(x => x.id === id).ch !== k);
- });
- requestAnimationFrame(drawLinks);
- }
- function drawLinks() {
- const board = $('#board'), svg = $('#links');
- const br = board.getBoundingClientRect();
- let html = '';
- for (const ch in mPairs) {
- const a = board.querySelector(`[data-ch="${ch}"]`).getBoundingClientRect();
- const b = board.querySelector(`[data-ms="${mPairs[ch]}"]`).getBoundingClientRect();
- const x1 = a.right - br.left, y1 = a.top + a.height / 2 - br.top;
- const x2 = b.left - br.left, y2 = b.top + b.height / 2 - br.top;
- const mx = (x1 + x2) / 2;
- const cls = mChecked ? (MMS.find(x => x.id === mPairs[ch]).ch === ch ? 'ok' : 'bad') : '';
- html += `<path class="link ${cls}" pathLength="1" d="M${x1} ${y1} C${mx} ${y1} ${mx} ${y2} ${x2} ${y2}"/>`;
- }
- svg.innerHTML = html;
- const count = Object.keys(mPairs).length;
- $('#mScore').textContent = mChecked
- ? `ВЕРНО: ${Object.keys(mPairs).filter(c => MMS.find(x => x.id === mPairs[c]).ch === c).length} ИЗ ${MCH.length}`
- : `СОЕДИНЕНО: ${count} ИЗ ${MCH.length}`;
- }
- $('#mCheck').addEventListener('click', () => {
- mChecked = true;
- const good = Object.keys(mPairs).filter(c => MMS.find(x => x.id === mPairs[c]).ch === c).length;
- beep(good === MCH.length ? 880 : 300, .12, good === MCH.length ? 'sine' : 'sawtooth', .035);
- renderMatch();
- });
- $('#mReset').addEventListener('click', buildMatch);
- addEventListener('resize', () => requestAnimationFrame(drawLinks));
- buildMatch();
- /* ===================== 05. ТЕСТ ===================== */
- const QUIZ = [
- { q: 'Что означает аббревиатура ПЭМИН?',
- o: ['Программа электромагнитной изоляции нейронов', 'Побочные электромагнитные излучения и наводки', 'Протокол электронной маскировки информации', 'Пакет эталонных мер информационной надёжности'], a: 1,
- e: 'ПЭМИН — побочные электромагнитные излучения и наводки технических средств. Это один из ключевых каналов в ТЗИ.' },
- { q: 'Из чего состоит триада информационной безопасности (CIA)?',
- o: ['Скорость, надёжность, масштаб', 'Конфиденциальность, целостность, доступность', 'Шифрование, хеширование, подпись', 'Авторизация, аутентификация, аудит'], a: 1,
- e: 'Конфиденциальность — доступ только у своих; целостность — данные не искажены; доступность — данные доступны, когда нужны.' },
- { q: 'Ослабление сигнала на 20 дБ по амплитуде означает, что он уменьшился примерно в…',
- o: ['2 раза', '10 раз', '100 раз', '1000 раз'], a: 1,
- e: 'По амплитуде 20 дБ соответствуют уменьшению в 10 раз. Так считает экран в симуляторе.' },
- { q: 'Что такое активное зашумление?',
- o: ['Звукоизоляция помещения', 'Излучение ложных сигналов, маскирующих полезный', 'Отключение питания при подозрении на утечку', 'Резервное копирование данных'], a: 1,
- e: 'Зашумление создаёт помехи, которые маскируют полезный сигнал и затрудняют его выделение приёмником.' },
- { q: 'Какой канал утечки связан с речевой информацией и вибрацией конструкций?',
- o: ['Визуальный', 'Акустический', 'Сетевой', 'Физический'], a: 1,
- e: 'Акустический канал: речь распространяется по воздуху и через строительные конструкции.' },
- { q: 'Что такое аттестация объекта информатизации?',
- o: ['Выдача сотруднику пропуска', 'Смена паролей раз в год', 'Подтверждение соответствия объекта требованиям безопасности информации', 'Установка антивируса на один компьютер'], a: 2,
- e: 'Аттестация документально подтверждает, что объект соответствует требованиям по защите информации.' },
- { q: 'Главная задача экранирования оборудования?',
- o: ['Ускорить работу процессора', 'Ослабить электромагнитные поля на пути распространения', 'Увеличить яркость экрана', 'Уменьшить вес корпуса'], a: 1,
- e: 'Экран (металлический корпус, сетка, фильтры) ослабляет излучение и наводки.' },
- { q: 'В упрощённой модели из этой лаборатории риск считают так:',
- o: ['Угроза + Уязвимость + Ущерб', 'Угроза × Уязвимость × Ущерб', 'Ущерб − Защита', 'Защита ÷ Угроза'], a: 1,
- e: 'Произведение факторов: если хотя бы один фактор близок к нулю, риск почти исчезает.' }
- ];
- let qi = 0, qScore = 0;
- const quizBox = $('#quizBox');
- function renderQuiz() {
- if (qi >= QUIZ.length) {
- const pct = Math.round(qScore / QUIZ.length * 100);
- const msg = pct >= 85 ? 'Отличный результат: вы хорошо понимаете принципы ТЗИ.'
- : pct >= 60 ? 'Хороший результат. Перечитайте раздел «Каналы утечки».'
- : 'Стоит повторить материал: начните с раздела «Каналы» и симулятора.';
- quizBox.innerHTML = `
- <div class="q-end pop">
- <div class="big">${qScore}/${QUIZ.length}</div>
- <h3>${pct}% правильных ответов</h3>
- <p>${msg}</p>
- <button class="btn btn-primary" id="qRestart">ПРОЙТИ ЕЩЁ РАЗ</button>
- </div>`;
- $('#qRestart').addEventListener('click', () => { qi = 0; qScore = 0; renderQuiz(); });
- return;
- }
- const item = QUIZ[qi];
- quizBox.innerHTML = `
- <div class="q-top"><span class="label">ВОПРОС ${qi + 1} / ${QUIZ.length}</span><span class="val">ОЧКИ: ${qScore}</span></div>
- <div class="q-bar"><i style="width:${qi / QUIZ.length * 100}%"></i></div>
- <h3 class="q-text pop">${esc(item.q)}</h3>
- <div class="q-opts">${item.o.map((t, i) => `<button class="q-opt" data-i="${i}">${esc(t)}</button>`).join('')}</div>
- <div class="q-exp" id="qExp" aria-live="polite"></div>
- <div class="q-nav"><button class="btn btn-ghost" id="qNext" disabled>ДАЛЕЕ →</button></div>`;
- let answered = false;
- $$('.q-opt', quizBox).forEach(b => b.addEventListener('click', () => {
- if (answered) return;
- answered = true;
- const i = +b.dataset.i, ok = i === item.a;
- if (ok) { qScore++; beep(880, .1, 'sine'); } else beep(180, .2, 'sawtooth', .04);
- $$('.q-opt', quizBox).forEach((x, j) => {
- x.disabled = true;
- if (j === item.a) x.classList.add('right');
- else if (j === i) x.classList.add('wrong');
- });
- $('#qExp').innerHTML = `<b class="${ok ? 'ok-text' : 'bad-text'}">${ok ? 'Верно!' : 'Неверно.'}</b> ${esc(item.e)}`;
- const next = $('#qNext');
- next.disabled = false;
- next.textContent = qi === QUIZ.length - 1 ? 'ПОКАЗАТЬ РЕЗУЛЬТАТ' : 'ДАЛЕЕ →';
- const val = quizBox.querySelector('.val');
- if (val) val.textContent = 'ОЧКИ: ' + qScore;
- }));
- $('#qNext').addEventListener('click', () => { qi++; renderQuiz(); });
- }
- renderQuiz();
- /* ===================== 06. ЧЕК-ЛИСТ ЗАЩИТЫ ===================== */
- const CHECK = [
- 'Права доступа разграничены по задачам',
- 'Экраны защищены фильтрами, блокировка при уходе',
- 'Техника проверена на ПЭМИН и наводки (по нормам ТЗИ)',
- 'Ведётся учёт всех носителей информации',
- 'Конфиденциальные переговоры — в звукоизолированных помещениях',
- 'Сетевой трафик шифруется и журналируется',
- 'Есть пропускной режим и контроль посетителей',
- 'Сотрудники регулярно проходят обучение'
- ];
- const checksBox = $('#checks');
- checksBox.innerHTML = CHECK.map((t, i) =>
- `<label class="check"><input type="checkbox" data-i="${i}"><span>${esc(t)}</span></label>`).join('');
- function updateChecklist() {
- const boxes = $$('input', checksBox);
- let done = 0;
- boxes.forEach(b => {
- const on = b.checked;
- b.parentElement.classList.toggle('done', on);
- if (on) done++;
- });
- const pct = Math.round(done / CHECK.length * 100);
- $('#cPct').textContent = pct + '%';
- $('#cFill').style.width = pct + '%';
- $('#cText').innerHTML = pct >= 90
- ? '<span class="ok-text">Высокий уровень.</span> Поддерживайте регулярный контроль и переаттестацию.'
- : pct >= 50
- ? '<span style="color:var(--amber)">Средний уровень.</span> Закройте пробелы в самых рискованных каналах.'
- : '<span class="bad-text">Низкий уровень.</span> Защита почти не выстроена: начните с доступа и учёта носителей.';
- }
- checksBox.addEventListener('change', updateChecklist);
- updateChecklist();
|