diff --git a/ci/security/service-log-vector-tests.yaml b/ci/security/service-log-vector-tests.yaml new file mode 100644 index 0000000..563d618 --- /dev/null +++ b/ci/security/service-log-vector-tests.yaml @@ -0,0 +1,48 @@ +tests: +- name: json-and-attributes-masking + inputs: + - insert_at: normalize_logs + type: log + log_fields: + message: '{"message":"synthetic healthy","password":"SYNTH_BODY","level":"info"}' + timestamp: '2026-11-30T10:00:00Z' + resources: + service.name: synthetic-svc + k8s.namespace.name: synthetic-ns + k8s.pod.name: synthetic-pod + attributes: + token: SYNTH_ATTR + safe: retained + outputs: + - extract_from: normalize_logs + conditions: + - type: vrl + source: 'assert_eq!(.namespace, "synthetic-ns") + + assert_eq!(.service_name, "synthetic-svc") + + assert_eq!(.severity, "INFO") + + assert!(!contains(encode_json(.), "SYNTH_")) + + assert!(contains!(.attributes_json, "retained")) + + true' +- name: bearer-and-jwt-masking + inputs: + - insert_at: normalize_logs + type: log + log_fields: + message: healthy Bearer SYNTH_BEARER aaaaaaaaaaaaaaaaaaaaaaaa.bbbbbbbbbbbbbbbbbbbbbbbb.cccccccccccccccccccc + resources: + service.name: synthetic-svc + k8s.namespace.name: synthetic-ns + outputs: + - extract_from: normalize_logs + conditions: + - type: vrl + source: 'assert!(!contains(encode_json(.), "SYNTH_BEARER")) + + assert!(contains!(.message, "healthy")) + + true' diff --git a/ci/security/verify-service-logs.py b/ci/security/verify-service-logs.py new file mode 100644 index 0000000..13d0edf --- /dev/null +++ b/ci/security/verify-service-logs.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +from pathlib import Path +import yaml,json,subprocess,tempfile,time,socket,urllib.request +import argparse +import os + +parser = argparse.ArgumentParser(description="Local service-log config/masking tests; no cluster or real S3 access") +parser.add_argument('--collector-bin', required=True) +parser.add_argument('--vector-bin', required=True) +args = parser.parse_args() +repo = Path(__file__).resolve().parents[2] +temporary = tempfile.TemporaryDirectory(prefix='service-log-check-') +root = Path(temporary.name) +with socket.socket() as port_socket: + port_socket.bind(('127.0.0.1', 0)) + port = port_socket.getsockname()[1] + +cfg=yaml.safe_load((repo / 'infrastructure/opentelemetry-collector/uralkal/opentelemetry-collector.yaml').read_text())['spec']['values']['alternateConfig'] +config={'receivers':{'otlp':{'protocols':{'http':{'endpoint':'127.0.0.1:' + str(port)}}}},'processors':{'transform/mask_logs':cfg['processors']['transform/mask_logs']},'exporters':{'file/test':{'path':str(root/'masked.json')}},'service':{'pipelines':{'logs':{'receivers':['otlp'],'processors':['transform/mask_logs'],'exporters':['file/test']}},'telemetry':{'logs':{'level':'warn'},'metrics':{'level':'none'}}}} +p=root/'collector-test.yaml';p.write_text(yaml.safe_dump(config,sort_keys=False)) +bin=args.collector_bin +r=subprocess.run([bin,'validate','--config',str(p)],capture_output=True,text=True);print('validate',r.returncode);print(r.stderr[:3000] if r.returncode else '');assert not r.returncode +(root/'masked.json').unlink(missing_ok=True) +errors=open(root/'collector-stderr.txt','w') +proc=subprocess.Popen([bin,'--config',str(p)],stdout=subprocess.DEVNULL,stderr=errors) +try: + for i in range(100): + if proc.poll() is not None:raise RuntimeError((root/'collector-stderr.txt').read_text()[:3000]) + try: + with socket.create_connection(('127.0.0.1',port),timeout=.2):break + except OSError:time.sleep(.1) + def v(x): + if isinstance(x,str):return {'stringValue':x} + if isinstance(x,dict):return {'kvlistValue':{'values':[{'key':k,'value':v(a)} for k,a in x.items()]}} + if isinstance(x,list):return {'arrayValue':{'values':[v(a) for a in x]}} + if isinstance(x,int):return {'intValue':str(x)} + jwt='a'*24+'.'+'b'*24+'.'+'c'*20 + bodies=[ + 'healthy-msg password="SYNTH_PWD" token=SYNTH_TOKEN Authorization: Bearer SYNTH_BEARER '+jwt+' https://synthetic-user:SYNTH_URL@local/path', + json.dumps({'message':'healthy-json','nested':{'password':'SYNTH_JSON'},'cookie':'SYNTH_COOKIE'}), + {'message':'healthy-map','nested':{'client_secret':'SYNTH_MAP'},'token':834891}, + ] + resource={'service.name':'mask-test','k8s.namespace.name':'synthetic-ns','nested':{'password':'SYNTH_RESOURCE','keep':'visible'},'url':'https://u:SYNTH_RESOURCE_URL@local/path'} + attrs={'nested':{'api_key':'SYNTH_ATTR_KEY','keep':'retained'},'cookies':['SYNTH_ARRAY_COOKIE'],'message':'Bearer SYNTH_ATTR_BEARER','count':42} + data={'resourceLogs':[{'resource':{'attributes':[{'key':k,'value':v(a)} for k,a in resource.items()]},'scopeLogs':[{'scope':{'name':'offline-mask-test'},'logRecords':[{'timeUnixNano':str(time.time_ns()),'body':v(body),'attributes':[{'key':k,'value':v(a)} for k,a in attrs.items()]} for body in bodies]}]}]} + req=urllib.request.Request('http://127.0.0.1:' + str(port) + '/v1/logs',data=json.dumps(data).encode(),headers={'Content-Type':'application/json'},method='POST') + with urllib.request.urlopen(req,timeout=10) as response:print('OTLP HTTP',response.status,response.read().decode()) + for _ in range(100): + if (root/'masked.json').exists() and (root/'masked.json').stat().st_size>0:break + time.sleep(.1) +finally: + proc.terminate();proc.wait(timeout=10);errors.close() +text=(root/'masked.json').read_text() +for value in ['SYNTH_PWD','SYNTH_TOKEN','SYNTH_BEARER',jwt,'SYNTH_URL','SYNTH_JSON','SYNTH_COOKIE','SYNTH_MAP','834891','SYNTH_RESOURCE','SYNTH_RESOURCE_URL','SYNTH_ATTR_KEY','SYNTH_ARRAY_COOKIE','SYNTH_ATTR_BEARER']: + assert value not in text,'Unmasked synthetic value: '+value +for value in ['healthy-msg','healthy-json','healthy-map','synthetic-ns','mask-test','visible','retained']: + assert value in text,'Lost nonsensitive value: '+value +print('Synthetic redaction and metadata preservation: PASS') + +# Validate the complete gateway/agent configs with only synthetic Kafka credentials/CA. +subprocess.run(['openssl', 'req', '-x509', '-newkey', 'rsa:2048', '-nodes', + '-keyout', str(root / 'synthetic.key'), '-out', str(root / 'synthetic-ca.crt'), + '-days', '1', '-subj', '/CN=synthetic-offline-validation'], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True) +kafka = cfg['exporters']['kafka/traces'] +kafka['auth']['sasl']['username'] = 'synthetic' +kafka['auth']['sasl']['password'] = 'synthetic' +kafka['auth']['tls']['ca_file'] = str(root / 'synthetic-ca.crt') +full = root / 'gateway-full.yaml' +full.write_text(yaml.safe_dump(cfg, sort_keys=False)) +env = dict(os.environ, MY_POD_IP='127.0.0.1', CONTOUR='uralkal', + KAFKA_BROKERS='127.0.0.1:19092', S3_BUCKET='service-logs', + S3_ENDPOINT='http://127.0.0.1:19000') +for path in [full, repo / 'infrastructure/opentelemetry-agent/base/collector.yaml']: + subprocess.run([bin, 'validate', '--config', str(path)], env=env, check=True) +vector = yaml.safe_load((repo / 'infrastructure/vector/base/vector.yaml').read_text()) +vector['data_dir'] = str(root / 'vector-data') +(root / 'vector-data').mkdir() +vector['sinks']['minio_logs']['batch_encoding']['schema_file'] = str(repo / 'infrastructure/vector/base/logs.schema') +credentials = root / 'synthetic-aws-credentials' +credentials.write_text('[default]\naws_access_key_id = synthetic\naws_secret_access_key = synthetic\n') +credentials.chmod(0o600) +vector['sinks']['minio_logs']['auth']['credentials_file'] = str(credentials) +vector['tests'] = yaml.safe_load((repo / 'ci/security/service-log-vector-tests.yaml').read_text())['tests'] +path = root / 'vector-check.yaml' +path.write_text(yaml.safe_dump(vector, sort_keys=False)) +subprocess.run([args.vector_bin, 'validate', '--skip-healthchecks', str(path)], env=env, check=True) +subprocess.run([args.vector_bin, 'test', str(path)], env=env, check=True) +temporary.cleanup() +print('All local service-log checks passed. Live MinIO/Vault/registry delivery is not tested.') diff --git a/clusters/uralkal/kustomization.yaml b/clusters/uralkal/kustomization.yaml index feb4f73..246dd93 100644 --- a/clusters/uralkal/kustomization.yaml +++ b/clusters/uralkal/kustomization.yaml @@ -18,8 +18,8 @@ resources: - ../../infrastructure/istio-config/uralkal - ../../infrastructure/s3-proxy/uralkal - ../../infrastructure/opentelemetry-collector/uralkal - # - ../../infrastructure/opentelemetry-agent/uralkal - # - ../../infrastructure/vector/uralkal + - ../../infrastructure/opentelemetry-agent/uralkal + - ../../infrastructure/vector/uralkal - ../../infrastructure/security-audit/uralkal - ../../infrastructure/vmstack/uralkal - ../../infrastructure/local-path-provisioner/uralkal diff --git a/infrastructure/opentelemetry-collector/uralkal/opentelemetry-collector.yaml b/infrastructure/opentelemetry-collector/uralkal/opentelemetry-collector.yaml index 032703a..2d70e33 100644 --- a/infrastructure/opentelemetry-collector/uralkal/opentelemetry-collector.yaml +++ b/infrastructure/opentelemetry-collector/uralkal/opentelemetry-collector.yaml @@ -167,6 +167,28 @@ spec: attributes: - {action: insert, key: k8s.cluster.name, value: "${env:CONTOUR}"} - {action: insert, key: deployment.environment, value: "${env:CONTOUR}"} + transform/mask_logs: + error_mode: propagate + log_statements: + - context: log + statements: + - set(log.body, String(log.body)) where not IsString(log.body) + - replace_pattern(log.body, "(?i)Bearer\\s+[A-Za-z0-9._~+/-]+=*", "Bearer ***") where IsString(log.body) + - replace_pattern(log.body, "(?i)[\"']?(password|passwd|pwd|token|secret|client_secret|api[_-]?key|authorization|cookies?|signature|x-amz-signature)[\"']?\\s*[:=]\\s*(\"(\\\\.|[^\"\\\\])*\"|'[^']*'|[^,;\\s}]+)", "[REDACTED]") where IsString(log.body) + - replace_pattern(log.body, "[A-Za-z0-9_-]{20,}\\.[A-Za-z0-9_-]{20,}\\.[A-Za-z0-9_-]{10,}", "***jwt***") where IsString(log.body) + - replace_pattern(log.body, "(?i)([a-z][a-z0-9+.-]*://)[^/@\\s]+:[^/@\\s]+@", "$$1***@") where IsString(log.body) + - flatten(log.attributes) + - delete_matching_keys(log.attributes, "(?i)(^|[._-])(password|passwd|pwd|token|secret|client[._-]?secret|api[._-]?key|access[._-]?key|authorization|cookies?|signature|x[._-]amz[._-]signature)([._-]|$$)") + - replace_all_patterns(log.attributes, "value", "(?i)Bearer\\s+[A-Za-z0-9._~+/-]+=*", "Bearer ***") + - replace_all_patterns(log.attributes, "value", "(?i)[\"']?(password|passwd|pwd|token|secret|client_secret|api[_-]?key|authorization|cookies?|signature|x-amz-signature)[\"']?\\s*[:=]\\s*(\"(\\\\.|[^\"\\\\])*\"|'[^']*'|[^,;\\s}]+)", "[REDACTED]") + - replace_all_patterns(log.attributes, "value", "[A-Za-z0-9_-]{20,}\\.[A-Za-z0-9_-]{20,}\\.[A-Za-z0-9_-]{10,}", "***jwt***") + - replace_all_patterns(log.attributes, "value", "(?i)([a-z][a-z0-9+.-]*://)[^/@\\s]+:[^/@\\s]+@", "$$1***@") + - flatten(resource.attributes) + - delete_matching_keys(resource.attributes, "(?i)(^|[._-])(password|passwd|pwd|token|secret|client[._-]?secret|api[._-]?key|access[._-]?key|authorization|cookies?|signature|x[._-]amz[._-]signature)([._-]|$$)") + - replace_all_patterns(resource.attributes, "value", "(?i)Bearer\\s+[A-Za-z0-9._~+/-]+=*", "Bearer ***") + - replace_all_patterns(resource.attributes, "value", "(?i)[\"']?(password|passwd|pwd|token|secret|client_secret|api[_-]?key|authorization|cookies?|signature|x-amz-signature)[\"']?\\s*[:=]\\s*(\"(\\\\.|[^\"\\\\])*\"|'[^']*'|[^,;\\s}]+)", "[REDACTED]") + - replace_all_patterns(resource.attributes, "value", "[A-Za-z0-9_-]{20,}\\.[A-Za-z0-9_-]{20,}\\.[A-Za-z0-9_-]{10,}", "***jwt***") + - replace_all_patterns(resource.attributes, "value", "(?i)([a-z][a-z0-9+.-]*://)[^/@\\s]+:[^/@\\s]+@", "$$1***@") # Маскирование (п.23), строже access-collector: значения чувствительных параметров # (password=, client_secret, token=, signature, X-Amz-Signature — в т.ч. в query # http.url/http.target, т.к. спаны несут URL с query), Bearer-токены и JWT. @@ -214,7 +236,7 @@ spec: logs: receivers: [otlp] # No batch/memory queue at this hop: preserve upstream retry on failure. - processors: [memory_limiter, resource] + processors: [memory_limiter, resource, transform/mask_logs] exporters: [otlp/logs] traces: receivers: [otlp, zipkin] diff --git a/infrastructure/vector/README.md b/infrastructure/vector/README.md index cd1a497..3041983 100644 --- a/infrastructure/vector/README.md +++ b/infrastructure/vector/README.md @@ -17,7 +17,7 @@ | Файлы | Фиксированная схема `base/logs.schema`, Zstd 3, 300 секунд либо 64 MiB входных событий | | Хранилище | `http://10.133.0.245:9000/service-logs`, объекты под `logs/` | | Retention | Lifecycle удаляет текущие объекты через 14 дней; отдельные правила для предыдущих версий и delete markers | -| Секрет | Vault KV v2 `secrets/apps/vector/minio`, поля `access_key` и `secret_key` | +| Секрет | Vault KV v2 `secrets/apps/vector/minio`, поля `access_key`, `secret_key` и `bucket` | | Доступ Vault | Kubernetes Auth role/policy `vector-logs`, только SA `vector-logs` в namespace `vector` | Пример ключа: @@ -101,8 +101,12 @@ PV/PVC не создаются. Буфер переживает перезапу Секреты подставляются Vault Agent один раз при старте. После ротации ключей нужно перезапустить StatefulSet Vector. Текущий MinIO endpoint использует HTTP, как существующий pipeline трейсов; TLS потребует серверного endpoint и CA. -Маскирование распространённых ключей/Bearer — дополнительная защита, не замена -запрету записи секретов приложениями. +Маскирование распространённых ключей/Bearer выполняется в logs pipeline gateway +до отправки в Vector и повторно в Vector. Вложенные log/resource attributes +в gateway переводятся в плоские dotted keys; чувствительные ключи удаляются. +Нестроковый body приводится к строке. Ошибки обработки gateway возвращаются +отправителю для повторной доставки, а не отправляют немаскированную запись дальше. +Это дополнительная защита, не замена запрету записи секретов приложениями. Expiration 14 дней считается от создания объекта, не от даты в ключе. Удаление асинхронное. На новом бакете versioning не включается; если его @@ -110,6 +114,28 @@ Expiration 14 дней считается от создания объекта, noncurrent. Следовательно, versioning может увеличить фактический срок хранения. Object Lock/Legal Hold могут блокировать удаление. +## Локальная проверка перед раскаткой + +Проверено официальными бинарниками Collector `0.121.0` и Vector `0.56.0`: + +```bash +python3 ci/security/verify-service-logs.py \ + --collector-bin /path/to/otelcol-contrib \ + --vector-bin /path/to/vector +``` + +Требуются Python 3, PyYAML и openssl. Проверка запускает временный Collector +на случайном localhost-порту, отправляет только синтетические OTLP-логи и +проверяет маскирование текста/JSON/body-map, вложенных атрибутов, cookies-массивов, +Bearer/JWT и credentials в URL. Проверяет сохранение обычных полей и metadata, +валидирует полный gateway/agent config и запускает VRL-тесты из фактического +Vector-конфига. Используются временные файлы и фиктивные credentials/CA; +к кластеру, Vault и реальному MinIO скрипт не подключается. + +Локальная проверка не подтверждает доступность образов в закрытом registry, +получение ключей из Vault и фактическую запись/retention Parquet в MinIO. +Эти сценарии проверяются оператором после раскатки. + ## Источники - https://opentelemetry.io/docs/platforms/kubernetes/collector/components/ diff --git a/infrastructure/vector/base/vector.yaml b/infrastructure/vector/base/vector.yaml index 1b5b25e..a6a9a62 100644 --- a/infrastructure/vector/base/vector.yaml +++ b/infrastructure/vector/base/vector.yaml @@ -2,7 +2,6 @@ data_dir: /var/lib/vector api: enabled: true address: 0.0.0.0:8686 - playground: false sources: otlp: @@ -28,8 +27,8 @@ transforms: if is_object(parsed) && is_empty(app) { app = object!(parsed) } - ts = to_timestamp(.timestamp) ?? now() - observed = to_timestamp(.observed_timestamp) ?? ts + ts = timestamp(.timestamp) ?? parse_timestamp(string(.timestamp) ?? "", format: "%+") ?? now() + observed = timestamp(.observed_timestamp) ?? parse_timestamp(string(.observed_timestamp) ?? "", format: "%+") ?? ts service_name = string(resources."service.name") ?? string(resources.app) ?? string(resources."k8s.container.name") ?? "unknown" if service_name == "" { service_name = string(resources.app) ?? string(resources."k8s.container.name") ?? "unknown"