security
Законодательный уровень информационной безопасности
Соответствие требованиям GDPR, HIPAA, PCI DSS и других стандартов
•
#security
#compliance
#gdpr
#regulations
Законодательный уровень информационной безопасности
Соблюдение законодательных требований и стандартов информационной безопасности.
GDPR (General Data Protection Regulation)
Основные принципы
class GDPRCompliance {
// Принцип 1: Законность, справедливость и прозрачность
async processPersonalData(data: PersonalData, purpose: string): Promise<void> {
// Проверяем наличие согласия
const consent = await this.getConsent(data.userId, purpose);
if (!consent) {
throw new Error('No consent for processing');
}
// Логируем обработку
await this.auditLog({
action: 'process_personal_data',
userId: data.userId,
purpose,
legalBasis: 'consent',
timestamp: new Date()
});
}
// Принцип 2: Ограничение цели
validatePurpose(purpose: string): boolean {
const allowedPurposes = [
'service_provision',
'marketing',
'analytics',
'legal_obligation'
];
return allowedPurposes.includes(purpose);
}
// Принцип 3: Минимизация данных
minimizeData(data: PersonalData): MinimalData {
// Собираем только необходимые данные
return {
userId: data.userId,
email: data.email,
// Не собираем лишние поля
};
}
// Принцип 4: Точность
async updatePersonalData(userId: string, updates: Partial<PersonalData>): Promise<void> {
await db.users.update(userId, updates);
await this.auditLog({
action: 'update_personal_data',
userId,
fields: Object.keys(updates),
timestamp: new Date()
});
}
// Принцип 5: Ограничение хранения
async enforceRetentionPolicy(): Promise<void> {
const retentionPeriod = 365 * 2; // 2 года
const cutoffDate = new Date();
cutoffDate.setDate(cutoffDate.getDate() - retentionPeriod);
// Удаляем устаревшие данные
await db.users.deleteWhere({
lastActive: { $lt: cutoffDate },
deletionRequested: false
});
}
// Принцип 6: Целостность и конфиденциальность
async protectData(data: PersonalData): Promise<EncryptedData> {
// Шифруем персональные данные
const encrypted = await this.encrypt(JSON.stringify(data));
return {
data: encrypted,
algorithm: 'AES-256-GCM',
keyId: 'key-123'
};
}
private async getConsent(userId: string, purpose: string): Promise<boolean> {
const consent = await db.consents.findOne({ userId, purpose });
return consent?.granted === true;
}
private async auditLog(event: any): Promise<void> {
await db.auditLog.insert(event);
}
private async encrypt(data: string): Promise<string> {
return 'encrypted-data';
}
}
interface PersonalData {
userId: string;
email: string;
name: string;
phone?: string;
address?: string;
}
interface MinimalData {
userId: string;
email: string;
}
interface EncryptedData {
data: string;
algorithm: string;
keyId: string;
}
Права субъектов данных
class DataSubjectRights {
// Право на доступ (Article 15)
async rightToAccess(userId: string): Promise<PersonalDataExport> {
const user = await db.users.findById(userId);
const activities = await db.activities.find({ userId });
const consents = await db.consents.find({ userId });
return {
personalData: user,
processingActivities: activities,
consents: consents,
exportDate: new Date(),
format: 'JSON'
};
}
// Право на исправление (Article 16)
async rightToRectification(
userId: string,
corrections: Partial<PersonalData>
): Promise<void> {
await db.users.update(userId, corrections);
await this.notifyThirdParties(userId, 'rectification', corrections);
}
// Право на удаление (Article 17)
async rightToErasure(userId: string): Promise<void> {
// Проверяем, нет ли законных оснований для хранения
const legalHold = await this.checkLegalHold(userId);
if (legalHold) {
throw new Error('Cannot delete: legal hold');
}
// Удаляем или анонимизируем данные
await db.users.anonymize(userId);
await db.activities.deleteMany({ userId });
await this.auditLog({
action: 'right_to_erasure',
userId,
timestamp: new Date()
});
}
// Право на ограничение обработки (Article 18)
async rightToRestriction(userId: string): Promise<void> {
await db.users.update(userId, {
processingRestricted: true,
restrictionDate: new Date()
});
}
// Право на переносимость данных (Article 20)
async rightToDataPortability(userId: string, format: 'JSON' | 'CSV'): Promise<string> {
const data = await this.rightToAccess(userId);
if (format === 'CSV') {
return this.convertToCSV(data);
}
return JSON.stringify(data, null, 2);
}
// Право на возражение (Article 21)
async rightToObject(userId: string, purpose: string): Promise<void> {
await db.consents.update(
{ userId, purpose },
{ granted: false, objectionDate: new Date() }
);
await this.stopProcessing(userId, purpose);
}
private async checkLegalHold(userId: string): Promise<boolean> {
// Проверяем наличие юридических обязательств
return false;
}
private async notifyThirdParties(
userId: string,
action: string,
data: any
): Promise<void> {
// Уведомляем третьи стороны об изменениях
}
private async stopProcessing(userId: string, purpose: string): Promise<void> {
// Останавливаем обработку для указанной цели
}
private convertToCSV(data: any): string {
// Конвертируем в CSV
return '';
}
private async auditLog(event: any): Promise<void> {
await db.auditLog.insert(event);
}
}
interface PersonalDataExport {
personalData: any;
processingActivities: any[];
consents: any[];
exportDate: Date;
format: string;
}
PCI DSS (Payment Card Industry Data Security Standard)
class PCIDSSCompliance {
// Requirement 1: Firewall Configuration
configureFirewall(): FirewallRules {
return {
inbound: [
{ port: 443, protocol: 'TCP', source: '0.0.0.0/0', action: 'ALLOW' },
{ port: 80, protocol: 'TCP', source: '0.0.0.0/0', action: 'DENY' }
],
outbound: [
{ port: 443, protocol: 'TCP', destination: '0.0.0.0/0', action: 'ALLOW' }
],
default: 'DENY'
};
}
// Requirement 2: No Default Passwords
async enforcePasswordPolicy(): Promise<void> {
const defaultPasswords = ['admin', 'password', '123456'];
const users = await db.users.find({
password: { $in: defaultPasswords.map(p => hashPassword(p)) }
});
for (const user of users) {
await this.forcePasswordReset(user.id);
}
}
// Requirement 3: Protect Stored Cardholder Data
async storeCardData(cardData: CardData): Promise<string> {
// Никогда не храним полный номер карты
const maskedPAN = this.maskPAN(cardData.pan);
const tokenizedPAN = await this.tokenize(cardData.pan);
// Не храним CVV
delete cardData.cvv;
await db.cards.insert({
userId: cardData.userId,
maskedPAN,
token: tokenizedPAN,
expiryDate: cardData.expiryDate
});
return tokenizedPAN;
}
// Requirement 4: Encrypt Transmission
configureEncryption(): EncryptionConfig {
return {
protocol: 'TLS 1.3',
ciphers: ['TLS_AES_256_GCM_SHA384'],
certificateValidation: true,
minimumKeyLength: 2048
};
}
// Requirement 8: Identify and Authenticate Access
async authenticateUser(credentials: Credentials): Promise<AuthResult> {
// Многофакторная аутентификация обязательна
const user = await this.verifyCredentials(credentials);
if (!user.mfaEnabled) {
throw new Error('MFA required for PCI compliance');
}
const mfaValid = await this.verifyMFA(user, credentials.mfaCode);
if (!mfaValid) {
throw new Error('Invalid MFA code');
}
return { success: true, user };
}
// Requirement 10: Track and Monitor Access
async auditAccess(event: AccessEvent): Promise<void> {
await db.auditLog.insert({
timestamp: new Date(),
userId: event.userId,
action: event.action,
resource: event.resource,
result: event.result,
ipAddress: event.ipAddress,
userAgent: event.userAgent
});
}
private maskPAN(pan: string): string {
// Показываем только последние 4 цифры
return `****-****-****-${pan.slice(-4)}`;
}
private async tokenize(pan: string): Promise<string> {
// Используем токенизацию вместо хранения PAN
return 'token-' + crypto.randomBytes(16).toString('hex');
}
private async forcePasswordReset(userId: string): Promise<void> {
await db.users.update(userId, {
passwordResetRequired: true
});
}
private async verifyCredentials(credentials: Credentials): Promise<any> {
return { id: '123', mfaEnabled: true };
}
private async verifyMFA(user: any, code: string): Promise<boolean> {
return true;
}
}
interface CardData {
userId: string;
pan: string;
cvv: string;
expiryDate: string;
}
interface FirewallRules {
inbound: Rule[];
outbound: Rule[];
default: 'ALLOW' | 'DENY';
}
interface Rule {
port: number;
protocol: string;
source?: string;
destination?: string;
action: 'ALLOW' | 'DENY';
}
interface EncryptionConfig {
protocol: string;
ciphers: string[];
certificateValidation: boolean;
minimumKeyLength: number;
}
interface Credentials {
username: string;
password: string;
mfaCode?: string;
}
interface AuthResult {
success: boolean;
user: any;
}
interface AccessEvent {
userId: string;
action: string;
resource: string;
result: 'success' | 'failure';
ipAddress: string;
userAgent: string;
}
HIPAA (Health Insurance Portability and Accountability Act)
class HIPAACompliance {
// Administrative Safeguards
async enforceAccessControl(userId: string, phi: PHI): Promise<boolean> {
// Проверяем, имеет ли пользователь право доступа к PHI
const authorized = await this.checkAuthorization(userId, phi.patientId);
if (!authorized) {
await this.auditLog({
event: 'unauthorized_access_attempt',
userId,
patientId: phi.patientId,
timestamp: new Date()
});
return false;
}
// Логируем доступ
await this.auditLog({
event: 'phi_access',
userId,
patientId: phi.patientId,
timestamp: new Date()
});
return true;
}
// Physical Safeguards
configurePhysicalSecurity(): PhysicalSafeguards {
return {
facilityAccess: 'Badge-controlled',
workstationSecurity: 'Screen locks after 5 minutes',
deviceControls: 'Encrypted mobile devices',
mediaDisposal: 'Secure wiping or physical destruction'
};
}
// Technical Safeguards
async encryptPHI(phi: PHI): Promise<EncryptedPHI> {
// Шифруем PHI в состоянии покоя
const encrypted = await this.encrypt(JSON.stringify(phi));
return {
encryptedData: encrypted,
algorithm: 'AES-256-GCM',
keyId: 'hipaa-key-123',
timestamp: new Date()
};
}
// Breach Notification
async handleBreach(breach: BreachIncident): Promise<void> {
// Оцениваем серьезность нарушения
const affectedRecords = await this.getAffectedRecords(breach);
if (affectedRecords.length >= 500) {
// Уведомляем HHS и СМИ
await this.notifyHHS(breach, affectedRecords);
await this.notifyMedia(breach);
}
// Уведомляем пострадавших пациентов
for (const record of affectedRecords) {
await this.notifyPatient(record.patientId, breach);
}
// Документируем инцидент
await this.documentBreach(breach, affectedRecords);
}
private async checkAuthorization(userId: string, patientId: string): Promise<boolean> {
// Проверяем права доступа
return true;
}
private async encrypt(data: string): Promise<string> {
return 'encrypted-phi';
}
private async getAffectedRecords(breach: BreachIncident): Promise<any[]> {
return [];
}
private async notifyHHS(breach: BreachIncident, records: any[]): Promise<void> {
// Уведомление в течение 60 дней
}
private async notifyMedia(breach: BreachIncident): Promise<void> {
// Уведомление СМИ для крупных нарушений
}
private async notifyPatient(patientId: string, breach: BreachIncident): Promise<void> {
// Уведомление пациента
}
private async documentBreach(breach: BreachIncident, records: any[]): Promise<void> {
// Документирование инцидента
}
private async auditLog(event: any): Promise<void> {
await db.auditLog.insert(event);
}
}
interface PHI {
patientId: string;
name: string;
dateOfBirth: Date;
medicalRecords: any[];
}
interface EncryptedPHI {
encryptedData: string;
algorithm: string;
keyId: string;
timestamp: Date;
}
interface PhysicalSafeguards {
facilityAccess: string;
workstationSecurity: string;
deviceControls: string;
mediaDisposal: string;
}
interface BreachIncident {
id: string;
type: string;
discoveredAt: Date;
description: string;
}
Compliance Management
class ComplianceManager {
async assessCompliance(standard: string): Promise<ComplianceReport> {
const requirements = await this.getRequirements(standard);
const results: ComplianceResult[] = [];
for (const requirement of requirements) {
const result = await this.checkRequirement(requirement);
results.push(result);
}
return {
standard,
assessmentDate: new Date(),
results,
overallStatus: this.calculateOverallStatus(results),
gaps: results.filter(r => r.status !== 'Compliant')
};
}
private async getRequirements(standard: string): Promise<Requirement[]> {
// Получаем требования стандарта
return [];
}
private async checkRequirement(requirement: Requirement): Promise<ComplianceResult> {
// Проверяем выполнение требования
return {
requirementId: requirement.id,
description: requirement.description,
status: 'Compliant',
evidence: [],
notes: ''
};
}
private calculateOverallStatus(results: ComplianceResult[]): string {
const nonCompliant = results.filter(r => r.status !== 'Compliant').length;
if (nonCompliant === 0) return 'Fully Compliant';
if (nonCompliant <= results.length * 0.1) return 'Mostly Compliant';
return 'Non-Compliant';
}
}
interface Requirement {
id: string;
description: string;
controls: string[];
}
interface ComplianceResult {
requirementId: string;
description: string;
status: 'Compliant' | 'Partially Compliant' | 'Non-Compliant';
evidence: string[];
notes: string;
}
interface ComplianceReport {
standard: string;
assessmentDate: Date;
results: ComplianceResult[];
overallStatus: string;
gaps: ComplianceResult[];
}
Заключение
Соблюдение законодательных требований требует:
- Понимания применимых стандартов — GDPR, PCI DSS, HIPAA
- Внедрения контролей — технических, административных, физических
- Регулярного аудита — проверка соответствия
- Документирования — политики, процедуры, доказательства
- Обучения персонала — осведомленность о требованиях