Compare commits

...
15 changed files with 127 additions and 169 deletions
+1
View File
@@ -1,4 +1,5 @@
#!/bin/sh #!/bin/sh
# shellcheck disable=SC1007
set -eu set -eu
REPO_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) REPO_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
+1
View File
@@ -1,4 +1,5 @@
#!/bin/sh #!/bin/sh
# shellcheck disable=SC1007
set -eu set -eu
REPO_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) REPO_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
+49 -15
View File
@@ -3,7 +3,7 @@ import json
import os import os
import urllib.error import urllib.error
import urllib.request import urllib.request
from datetime import datetime, timezone from datetime import datetime, timedelta, timezone
AW_URL = os.environ.get("AW_SERVER_URL", "http://127.0.0.1:5600") AW_URL = os.environ.get("AW_SERVER_URL", "http://127.0.0.1:5600")
@@ -70,25 +70,48 @@ def to_iso_utc(ts):
return ts.replace("+00:00", "Z") return ts.replace("+00:00", "Z")
def parse_iso_utc(ts: str):
if ts.endswith("Z"):
ts = ts[:-1] + "+00:00"
return datetime.fromisoformat(ts).astimezone(timezone.utc)
def build_window_title(users, active_count): def build_window_title(users, active_count):
if not users: if not users:
return "RDP idle" return "RDP idle"
return f"RDP active ({active_count}): " + ", ".join(users) return f"RDP active ({active_count}): " + ", ".join(users)
def _is_session_active(row_data):
if isinstance(row_data.get("active"), bool):
return row_data.get("active")
state = str(row_data.get("state", "")).strip().lower()
return state in {"active", "активно"}
def transform(events): def transform(events):
out_afk = [] out_afk = []
out_win = [] out_win = []
last_ts = None last_ts = None
grouped = {}
for e in events: for e in events:
ts = e.get("timestamp") ts = e.get("timestamp")
if not ts: if not ts:
continue continue
duration = float(e.get("duration", 0.0)) grouped.setdefault(ts, []).append(e)
data = e.get("data") or {}
active_users = data.get("activeUsers") or [] for ts in sorted(grouped.keys()):
active_count = int(data.get("activeCount", len(active_users))) rows = grouped[ts]
duration = max(float(r.get("duration", 0.0)) for r in rows)
active_users = []
for r in rows:
data = r.get("data") or {}
user = str(data.get("username", "")).strip()
if user and _is_session_active(data):
active_users.append(user)
active_users = sorted(set(active_users))
active_count = len(active_users)
is_active = active_count > 0 is_active = active_count > 0
afk_data = {"status": "not-afk" if is_active else "afk", "source": "aw-worktime-ui-bridge"} afk_data = {"status": "not-afk" if is_active else "afk", "source": "aw-worktime-ui-bridge"}
@@ -112,18 +135,29 @@ def main():
ensure_bucket(AFK_BUCKET, "afkstatus", "aw-worktime-ui-bridge") ensure_bucket(AFK_BUCKET, "afkstatus", "aw-worktime-ui-bridge")
ensure_bucket(WINDOW_BUCKET, "currentwindow", "aw-worktime-ui-bridge") ensure_bucket(WINDOW_BUCKET, "currentwindow", "aw-worktime-ui-bridge")
query = { now_utc = datetime.now(timezone.utc)
"query": [ recent = _req("GET", f"/api/0/buckets/{SESSIONS_BUCKET}/events?limit=5000") or []
"events = query_bucket(find_bucket($bid));", if not recent:
"RETURN = sort_by_timestamp(events);", return
],
"timeperiods": [[last_ts, to_iso_utc(datetime.now(timezone.utc).isoformat())]], try:
} last_dt = parse_iso_utc(last_ts)
rows = _req("POST", f"/api/0/query/?bid={SESSIONS_BUCKET}", query) or [] except Exception:
if not rows or not rows[0]: last_dt = datetime(1970, 1, 1, tzinfo=timezone.utc)
events = []
for e in recent:
ts = e.get("timestamp")
if not ts:
continue
try:
if parse_iso_utc(ts) > last_dt:
events.append(e)
except Exception:
continue
if not events:
return return
events = rows[0]
afk_events, win_events, new_last_ts = transform(events) afk_events, win_events, new_last_ts = transform(events)
if not afk_events or not win_events or not new_last_ts: if not afk_events or not win_events or not new_last_ts:
return return
+1 -1
View File
@@ -18,7 +18,7 @@ echo "=== ActivityWatch Data Check: $HOSTNAME_FILTER ==="
echo "" echo ""
echo -n "Server connectivity... " echo -n "Server connectivity... "
RESP=$(no_proxy=10.10.10.13 curl -s --connect-timeout 10 --max-time 15 "$SERVER/api/0/info" 2>&1) RESP=$(no_proxy=10.10.10.13 curl -s --connect-timeout 10 --max-time 15 "$SERVER/api/0/info" 2>&1)
if [ $? -eq 0 ] && echo "$RESP" | jq -e '.version' > /dev/null 2>&1; then if echo "$RESP" | jq -e '.version' > /dev/null 2>&1; then
VERSION=$(echo "$RESP" | jq -r '.version') VERSION=$(echo "$RESP" | jq -r '.version')
echo -e "${GREEN}OK${NC} (aw-server v$VERSION)" echo -e "${GREEN}OK${NC} (aw-server v$VERSION)"
else else
+1 -1
View File
@@ -22,7 +22,7 @@ echo ""
echo -e "${CYAN}--- 1. AW Server ($SERVER) ---${NC}" echo -e "${CYAN}--- 1. AW Server ($SERVER) ---${NC}"
echo -n " Connectivity... " echo -n " Connectivity... "
RESP=$(no_proxy=10.10.10.13 curl -s --connect-timeout 10 --max-time 15 "$SERVER/api/0/info" 2>&1) RESP=$(no_proxy=10.10.10.13 curl -s --connect-timeout 10 --max-time 15 "$SERVER/api/0/info" 2>&1)
if [ $? -eq 0 ] && echo "$RESP" | jq -e '.version' > /dev/null 2>&1; then if echo "$RESP" | jq -e '.version' > /dev/null 2>&1; then
VERSION=$(echo "$RESP" | jq -r '.version') VERSION=$(echo "$RESP" | jq -r '.version')
echo -e " ${GREEN}OK${NC} (aw-server $VERSION)" echo -e " ${GREEN}OK${NC} (aw-server $VERSION)"
else else
@@ -1,4 +1,4 @@
[CmdletBinding()] [CmdletBinding()]
param( param(
[string]$ConfigPath = 'C:\ProgramData\AWatch-rus\deployment-config.json', [string]$ConfigPath = 'C:\ProgramData\AWatch-rus\deployment-config.json',
[string]$ServerHost, [string]$ServerHost,
@@ -516,35 +516,6 @@ function Test-LooksLikeMojibakeQuestionMarks {
return $Value -match '\?{2,}' return $Value -match '\?{2,}'
} }
function Test-IsGenericDocumentName {
param([AllowNull()][string]$Value)
if ([string]::IsNullOrWhiteSpace($Value)) { return $true }
$generic = @(
'^\s*Печать документа\s*$',
'^\s*Print Document\s*$',
'^\s*Document\s*$',
'^\s*Документ\s*$',
'^\s*Remote Downlevel Document\s*$',
'^\s*Local Downlevel Document\s*$',
'^\s*Untitled\s*$',
'^\s*Без имени\s*$',
'^\s*Без названия\s*$'
)
foreach ($pattern in $generic) {
if ($Value -match $pattern) { return $true }
}
return $false
}
function Test-NeedsBetterDocumentName {
param([AllowNull()][string]$Value)
if ([string]::IsNullOrWhiteSpace($Value)) { return $true }
if (Test-LooksLikeMojibakeQuestionMarks -Value $Value) { return $true }
if (Test-IsGenericDocumentName -Value $Value) { return $true }
if ($Value -match '^[0-9]+$') { return $true }
return $false
}
function Normalize-OwnerForMatch { function Normalize-OwnerForMatch {
param([AllowNull()][string]$Value) param([AllowNull()][string]$Value)
if ([string]::IsNullOrWhiteSpace($Value)) { return '' } if ([string]::IsNullOrWhiteSpace($Value)) { return '' }
@@ -631,7 +602,7 @@ function Get-PrintServiceDocumentFallback {
) )
$preferred = [string]$EventSummary.DocumentName $preferred = [string]$EventSummary.DocumentName
if (-not (Test-NeedsBetterDocumentName -Value $preferred)) { if (-not (Test-LooksLikeMojibakeQuestionMarks -Value $preferred) -and $preferred -notmatch '^[0-9]+$') {
return $preferred return $preferred
} }
@@ -644,13 +615,17 @@ function Get-PrintServiceDocumentFallback {
if ($candidate -eq $preferred) { continue } if ($candidate -eq $preferred) { continue }
if ($Owner -and $candidate -like "*$Owner*") { continue } if ($Owner -and $candidate -like "*$Owner*") { continue }
if ($PrinterName -and $candidate -like "*$PrinterName*") { continue } if ($PrinterName -and $candidate -like "*$PrinterName*") { continue }
if (Test-NeedsBetterDocumentName -Value $candidate) { continue } if (Test-LooksLikeMojibakeQuestionMarks -Value $candidate) { continue }
if ($candidate -match '[\\/:]' -and $candidate -match '\.[A-Za-z0-9]{1,8}$') { if ($candidate -match '[\\/:]' -and $candidate -match '\.[A-Za-z0-9]{1,8}$') {
$pathCandidates.Add($candidate) $pathCandidates.Add($candidate)
continue continue
} }
if ($candidate -match '^[0-9]+$') {
continue
}
$textCandidates.Add($candidate) $textCandidates.Add($candidate)
} }
@@ -780,6 +755,8 @@ $script:SeenPrintJob = @{}
$script:SeenPrintEvent = @{} $script:SeenPrintEvent = @{}
$script:LastClipboardHash = $null $script:LastClipboardHash = $null
$script:PulseSeconds = [Math]::Max($resolvedPollSeconds * 3, 30) $script:PulseSeconds = [Math]::Max($resolvedPollSeconds * 3, 30)
$script:SelfTestIntervalSeconds = [Math]::Max($resolvedPollSeconds * 10, 60)
$script:LastSelfTestAt = [datetime]::MinValue
$script:LocalAgentLogsEnabled = $resolvedLocalAgentLogsEnabled $script:LocalAgentLogsEnabled = $resolvedLocalAgentLogsEnabled
$script:LogPath = $resolvedLogPath $script:LogPath = $resolvedLogPath
$script:IncidentArtifactsRoot = $resolvedIncidentArtifactsRoot $script:IncidentArtifactsRoot = $resolvedIncidentArtifactsRoot
@@ -791,6 +768,15 @@ Write-EndpointLog ("endpoint collector started against {0}" -f $script:ApiBase)
while ($true) { while ($true) {
try { try {
$nowUtc = (Get-Date).ToUniversalTime()
if (($nowUtc - $script:LastSelfTestAt).TotalSeconds -ge $script:SelfTestIntervalSeconds) {
Send-EndpointSignalHeartbeat -SignalType 'self_test' -Data @{
collector = 'dlp-endpoint-signals'
policyEnabled = [bool]$script:Policy.defaults.enabled
}
$script:LastSelfTestAt = $nowUtc
}
if (-not $script:Policy.defaults.enabled) { if (-not $script:Policy.defaults.enabled) {
Start-Sleep -Seconds $resolvedPollSeconds Start-Sleep -Seconds $resolvedPollSeconds
continue continue
@@ -848,12 +834,12 @@ while ($true) {
if ($script:SeenPrintJob.ContainsKey($jobId)) { continue } if ($script:SeenPrintJob.ContainsKey($jobId)) { continue }
$script:SeenPrintJob[$jobId] = (Get-Date).ToUniversalTime() $script:SeenPrintJob[$jobId] = (Get-Date).ToUniversalTime()
$printerName = Normalize-PrinterForMatch -Value ([string]$job.Name) $printerName = [string]$job.Name
$documentName = [string]$job.Document $documentName = [string]$job.Document
$owner = [string]$job.Owner $owner = [string]$job.Owner
$documentNameOriginal = $documentName $documentNameOriginal = $documentName
if (Test-NeedsBetterDocumentName -Value $documentName) { if (Test-LooksLikeMojibakeQuestionMarks -Value $documentName) {
$eventDocumentName = Get-BetterDocumentNameFromPrintServiceEvents -Owner $owner -PrinterName $printerName $eventDocumentName = Get-BetterDocumentNameFromPrintServiceEvents -Owner $owner -PrinterName $printerName
if ($eventDocumentName) { if ($eventDocumentName) {
$documentName = $eventDocumentName $documentName = $eventDocumentName
@@ -98,6 +98,13 @@ function Get-SessionRecords {
return $records return $records
} }
function Test-SessionIsActive {
param([AllowNull()][string]$State)
if ([string]::IsNullOrWhiteSpace($State)) { return $false }
$s = $State.Trim().ToLowerInvariant()
return ($s -eq 'active') -or ($s -like 'актив*')
}
$cfg = Get-Config -Path $ConfigPath $cfg = Get-Config -Path $ConfigPath
$hostValue = if ($Hostname) { $Hostname } else { [string]$env:COMPUTERNAME } $hostValue = if ($Hostname) { $Hostname } else { [string]$env:COMPUTERNAME }
$apiBase = '{0}://{1}:{2}/api/0' -f [string]$cfg.server.scheme, [string]$cfg.server.host, [string]$cfg.server.port $apiBase = '{0}://{1}:{2}/api/0' -f [string]$cfg.server.scheme, [string]$cfg.server.host, [string]$cfg.server.port
@@ -137,7 +144,7 @@ while ($true) {
sessionId = [int]$rec.sessionId sessionId = [int]$rec.sessionId
sessionName = [string]$rec.sessionName sessionName = [string]$rec.sessionName
state = [string]$rec.state state = [string]$rec.state
active = ($rec.state -match 'Active') active = (Test-SessionIsActive -State ([string]$rec.state))
hostname = $hostValue hostname = $hostValue
source = 'worktime-session-collector' source = 'worktime-session-collector'
} }
+1
View File
@@ -1,4 +1,5 @@
#!/bin/sh #!/bin/sh
# shellcheck disable=SC1007
set -eu set -eu
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
+1
View File
@@ -1,4 +1,5 @@
#!/bin/sh #!/bin/sh
# shellcheck disable=SC1007
set -eu set -eu
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
+1
View File
@@ -4,6 +4,7 @@ set -euo pipefail
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT_DIR" cd "$ROOT_DIR"
# shellcheck disable=SC2034
KIT_DIR="install-kit-awindows-20260427-211240" KIT_DIR="install-kit-awindows-20260427-211240"
python - <<'PY' python - <<'PY'
@@ -49,6 +49,7 @@ while [ "$#" -gt 0 ]; do
esac esac
done done
# shellcheck disable=SC1007
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
sh "${SCRIPT_DIR}/install_aw_linux_client.sh" \ sh "${SCRIPT_DIR}/install_aw_linux_client.sh" \
+4 -2
View File
@@ -21,9 +21,11 @@ prompt_secret() {
if [[ -n "${!var_name:-}" ]]; then if [[ -n "${!var_name:-}" ]]; then
return 0 return 0
fi fi
read -r -s -p "${prompt}: " "$var_name" local _val
read -r -s -p "${prompt}: " _val
echo echo
export "$var_name" printf -v "$var_name" '%s' "$_val"
declare -gx "$var_name"
} }
require_cmd git require_cmd git
+3
View File
@@ -6,7 +6,10 @@ cd "$ROOT_DIR"
KIT_DIR="install-kit-awindows-20260427-211240" KIT_DIR="install-kit-awindows-20260427-211240"
MANIFEST="$KIT_DIR/MANIFEST.txt" MANIFEST="$KIT_DIR/MANIFEST.txt"
# ZIP/TAR variables are declared for archive checks in this script; keep them for clarity
# shellcheck disable=SC2034
ZIP_ARCHIVE="install-kit-awindows-20260427-211240.zip" ZIP_ARCHIVE="install-kit-awindows-20260427-211240.zip"
# shellcheck disable=SC2034
TAR_ARCHIVE="install-kit-awindows-20260427-211240.tar.gz" TAR_ARCHIVE="install-kit-awindows-20260427-211240.tar.gz"
required_files=( required_files=(
+27 -114
View File
@@ -1,4 +1,4 @@
[CmdletBinding()] [CmdletBinding()]
param( param(
[string]$ConfigPath = 'C:\ProgramData\AWatch-rus\deployment-config.json', [string]$ConfigPath = 'C:\ProgramData\AWatch-rus\deployment-config.json',
[string]$ServerHost, [string]$ServerHost,
@@ -54,32 +54,13 @@ function Ensure-Bucket {
return return
} }
try {
Invoke-RestMethod -Method Get -Uri "$($script:ApiBase)/buckets/$BucketId" | Out-Null
$script:KnownBuckets[$BucketId] = $true
return
}
catch {
}
$body = @{ $body = @{
client = $ClientName client = $ClientName
type = $BucketType type = $BucketType
hostname = $script:Hostname hostname = $script:Hostname
} | ConvertTo-Json -Compress } | ConvertTo-Json -Compress
try { Invoke-AwJsonPost -Uri "$($script:ApiBase)/buckets/$BucketId" -Json $body
Invoke-AwJsonPost -Uri "$($script:ApiBase)/buckets/$BucketId" -Json $body
}
catch {
try {
Invoke-RestMethod -Method Get -Uri "$($script:ApiBase)/buckets/$BucketId" | Out-Null
}
catch {
Write-EndpointLog "Bucket create/check failed for ${BucketId}: $($_.Exception.Message)"
throw
}
}
$script:KnownBuckets[$BucketId] = $true $script:KnownBuckets[$BucketId] = $true
} }
@@ -243,10 +224,6 @@ function Show-EnforcementNotification {
[Parameter(Mandatory = $true)][string]$Title, [Parameter(Mandatory = $true)][string]$Title,
[Parameter(Mandatory = $true)][string]$Body [Parameter(Mandatory = $true)][string]$Body
) )
if ($script:HeadlessMode) {
Write-EndpointLog ("headless mode: skip notification title={0}" -f $Title)
return $false
}
try { try {
Add-Type -AssemblyName System.Windows.Forms -ErrorAction SilentlyContinue Add-Type -AssemblyName System.Windows.Forms -ErrorAction SilentlyContinue
$icon = New-Object System.Windows.Forms.NotifyIcon $icon = New-Object System.Windows.Forms.NotifyIcon
@@ -258,11 +235,9 @@ function Show-EnforcementNotification {
$icon.ShowBalloonTip(5000) $icon.ShowBalloonTip(5000)
Start-Sleep -Milliseconds 200 Start-Sleep -Milliseconds 200
$icon.Dispose() $icon.Dispose()
return $true
} }
catch { catch {
Write-EndpointLog ("notification failed: {0}" -f $_.Exception.Message) Write-EndpointLog ("notification failed: {0}" -f $_.Exception.Message)
return $false
} }
} }
@@ -449,9 +424,6 @@ function Evaluate-ClipboardRules {
[string]$ClipboardText, [string]$ClipboardText,
[string]$ClipboardHash [string]$ClipboardHash
) )
if ([string]::IsNullOrEmpty($ClipboardText) -or [string]::IsNullOrEmpty($ClipboardHash)) {
return
}
foreach ($rule in @($script:Policy.endpoint.clipboard)) { foreach ($rule in @($script:Policy.endpoint.clipboard)) {
if (-not $rule) { continue } if (-not $rule) { continue }
@@ -482,13 +454,8 @@ function Evaluate-ClipboardRules {
$enforced = $false $enforced = $false
if ($action -eq 'block') { if ($action -eq 'block') {
if ($script:HeadlessMode) { $enforced = Invoke-ClipboardEnforcement
Write-EndpointLog ("headless fallback: clipboard rule={0} requires block, skipped interactive enforcement" -f $ruleId) Show-EnforcementNotification -Title 'DLP: буфер обмена очищен' -Body $message
}
else {
$enforced = Invoke-ClipboardEnforcement
[void](Show-EnforcementNotification -Title 'DLP: буфер обмена очищен' -Body $message)
}
} }
Send-DlpIncidentHeartbeat -RuleId $ruleId -Action $action -Severity $severity -Message $message -SignalType 'clipboard' -Data @{ Send-DlpIncidentHeartbeat -RuleId $ruleId -Action $action -Severity $severity -Message $message -SignalType 'clipboard' -Data @{
@@ -522,13 +489,8 @@ function Evaluate-UsbRules {
$enforced = $false $enforced = $false
if ($action -eq 'block') { if ($action -eq 'block') {
if ($script:HeadlessMode) { $enforced = Invoke-UsbWriteBlockEnforcement -DriveLetter $DriveLetter
Write-EndpointLog ("headless fallback: usb rule={0} requires block, skipped interactive enforcement drive={1}" -f $ruleId, $DriveLetter) Show-EnforcementNotification -Title 'DLP: USB заблокирован для записи' -Body $message
}
else {
$enforced = Invoke-UsbWriteBlockEnforcement -DriveLetter $DriveLetter
[void](Show-EnforcementNotification -Title 'DLP: USB заблокирован для записи' -Body $message)
}
} }
Send-DlpIncidentHeartbeat -RuleId $ruleId -Action $action -Severity $severity -Message $message -SignalType 'usb_insert' -Data @{ Send-DlpIncidentHeartbeat -RuleId $ruleId -Action $action -Severity $severity -Message $message -SignalType 'usb_insert' -Data @{
@@ -572,13 +534,8 @@ function Evaluate-PrintRules {
$enforced = $false $enforced = $false
if ($action -eq 'block') { if ($action -eq 'block') {
if ($script:HeadlessMode) { $enforced = Invoke-PrintJobEnforcement -PrinterName $PrinterName -DocumentName $DocumentName -Owner $Owner
Write-EndpointLog ("headless fallback: print rule={0} requires block, skipped interactive enforcement printer={1}" -f $ruleId, $PrinterName) Show-EnforcementNotification -Title 'DLP: печать заблокирована' -Body $message
}
else {
$enforced = Invoke-PrintJobEnforcement -PrinterName $PrinterName -DocumentName $DocumentName -Owner $Owner
[void](Show-EnforcementNotification -Title 'DLP: печать заблокирована' -Body $message)
}
} }
Send-DlpIncidentHeartbeat -RuleId $ruleId -Action $action -Severity $severity -Message $message -SignalType 'print_job' -Data @{ Send-DlpIncidentHeartbeat -RuleId $ruleId -Action $action -Severity $severity -Message $message -SignalType 'print_job' -Data @{
@@ -597,35 +554,6 @@ function Test-LooksLikeMojibakeQuestionMarks {
return $Value -match '\?{2,}' return $Value -match '\?{2,}'
} }
function Test-IsGenericDocumentName {
param([AllowNull()][string]$Value)
if ([string]::IsNullOrWhiteSpace($Value)) { return $true }
$generic = @(
'^\s*Печать документа\s*$',
'^\s*Print Document\s*$',
'^\s*Document\s*$',
'^\s*Документ\s*$',
'^\s*Remote Downlevel Document\s*$',
'^\s*Local Downlevel Document\s*$',
'^\s*Untitled\s*$',
'^\s*Без имени\s*$',
'^\s*Без названия\s*$'
)
foreach ($pattern in $generic) {
if ($Value -match $pattern) { return $true }
}
return $false
}
function Test-NeedsBetterDocumentName {
param([AllowNull()][string]$Value)
if ([string]::IsNullOrWhiteSpace($Value)) { return $true }
if (Test-LooksLikeMojibakeQuestionMarks -Value $Value) { return $true }
if (Test-IsGenericDocumentName -Value $Value) { return $true }
if ($Value -match '^[0-9]+$') { return $true }
return $false
}
function Normalize-OwnerForMatch { function Normalize-OwnerForMatch {
param([AllowNull()][string]$Value) param([AllowNull()][string]$Value)
if ([string]::IsNullOrWhiteSpace($Value)) { return '' } if ([string]::IsNullOrWhiteSpace($Value)) { return '' }
@@ -712,7 +640,7 @@ function Get-PrintServiceDocumentFallback {
) )
$preferred = [string]$EventSummary.DocumentName $preferred = [string]$EventSummary.DocumentName
if (-not (Test-NeedsBetterDocumentName -Value $preferred)) { if (-not (Test-LooksLikeMojibakeQuestionMarks -Value $preferred) -and $preferred -notmatch '^[0-9]+$') {
return $preferred return $preferred
} }
@@ -725,13 +653,17 @@ function Get-PrintServiceDocumentFallback {
if ($candidate -eq $preferred) { continue } if ($candidate -eq $preferred) { continue }
if ($Owner -and $candidate -like "*$Owner*") { continue } if ($Owner -and $candidate -like "*$Owner*") { continue }
if ($PrinterName -and $candidate -like "*$PrinterName*") { continue } if ($PrinterName -and $candidate -like "*$PrinterName*") { continue }
if (Test-NeedsBetterDocumentName -Value $candidate) { continue } if (Test-LooksLikeMojibakeQuestionMarks -Value $candidate) { continue }
if ($candidate -match '[\\/:]' -and $candidate -match '\.[A-Za-z0-9]{1,8}$') { if ($candidate -match '[\\/:]' -and $candidate -match '\.[A-Za-z0-9]{1,8}$') {
$pathCandidates.Add($candidate) $pathCandidates.Add($candidate)
continue continue
} }
if ($candidate -match '^[0-9]+$') {
continue
}
$textCandidates.Add($candidate) $textCandidates.Add($candidate)
} }
@@ -830,7 +762,6 @@ function Get-BetterDocumentNameFromPrintServiceEvents {
} }
} }
catch { catch {
Write-EndpointLog ("printservice fallback failed: {0}" -f $_.Exception.Message)
} }
return $null return $null
@@ -862,21 +793,28 @@ $script:SeenPrintJob = @{}
$script:SeenPrintEvent = @{} $script:SeenPrintEvent = @{}
$script:LastClipboardHash = $null $script:LastClipboardHash = $null
$script:PulseSeconds = [Math]::Max($resolvedPollSeconds * 3, 30) $script:PulseSeconds = [Math]::Max($resolvedPollSeconds * 3, 30)
$script:SelfTestIntervalSeconds = [Math]::Max($resolvedPollSeconds * 10, 60)
$script:LastSelfTestAt = [datetime]::MinValue
$script:LocalAgentLogsEnabled = $resolvedLocalAgentLogsEnabled $script:LocalAgentLogsEnabled = $resolvedLocalAgentLogsEnabled
$script:LogPath = $resolvedLogPath $script:LogPath = $resolvedLogPath
$script:IncidentArtifactsRoot = $resolvedIncidentArtifactsRoot $script:IncidentArtifactsRoot = $resolvedIncidentArtifactsRoot
$script:IncidentScreenshotEnabled = $resolvedIncidentScreenshotEnabled $script:IncidentScreenshotEnabled = $resolvedIncidentScreenshotEnabled
$script:ScreenshotTypesLoaded = $false $script:ScreenshotTypesLoaded = $false
$script:HeadlessMode = ($env:SESSIONNAME -eq 'Service') -or (-not [Environment]::UserInteractive)
Load-DlpPolicy -Path $resolvedPolicyPath Load-DlpPolicy -Path $resolvedPolicyPath
Write-EndpointLog ("endpoint collector started against {0}" -f $script:ApiBase) Write-EndpointLog ("endpoint collector started against {0}" -f $script:ApiBase)
if ($script:HeadlessMode) {
Write-EndpointLog "headless mode enabled: enforcement UI is disabled, incident heartbeat and logs only"
}
while ($true) { while ($true) {
try { try {
$nowUtc = (Get-Date).ToUniversalTime()
if (($nowUtc - $script:LastSelfTestAt).TotalSeconds -ge $script:SelfTestIntervalSeconds) {
Send-EndpointSignalHeartbeat -SignalType 'self_test' -Data @{
collector = 'dlp-endpoint-signals'
policyEnabled = [bool]$script:Policy.defaults.enabled
}
$script:LastSelfTestAt = $nowUtc
}
if (-not $script:Policy.defaults.enabled) { if (-not $script:Policy.defaults.enabled) {
Start-Sleep -Seconds $resolvedPollSeconds Start-Sleep -Seconds $resolvedPollSeconds
continue continue
@@ -897,7 +835,6 @@ while ($true) {
} }
} }
catch { catch {
Write-EndpointLog ("clipboard poll failed: {0}" -f $_.Exception.Message)
} }
try { try {
@@ -925,7 +862,6 @@ while ($true) {
} }
} }
catch { catch {
Write-EndpointLog ("usb poll failed: {0}" -f $_.Exception.Message)
} }
try { try {
@@ -936,33 +872,23 @@ while ($true) {
if ($script:SeenPrintJob.ContainsKey($jobId)) { continue } if ($script:SeenPrintJob.ContainsKey($jobId)) { continue }
$script:SeenPrintJob[$jobId] = (Get-Date).ToUniversalTime() $script:SeenPrintJob[$jobId] = (Get-Date).ToUniversalTime()
$printerName = Normalize-PrinterForMatch -Value ([string]$job.Name) $printerName = [string]$job.Name
$documentName = [string]$job.Document $documentName = [string]$job.Document
$owner = [string]$job.Owner $owner = [string]$job.Owner
$documentNameOriginal = $documentName $documentNameOriginal = $documentName
if (Test-NeedsBetterDocumentName -Value $documentName) { if (Test-LooksLikeMojibakeQuestionMarks -Value $documentName) {
$eventDocumentName = Get-BetterDocumentNameFromPrintServiceEvents -Owner $owner -PrinterName $printerName $eventDocumentName = Get-BetterDocumentNameFromPrintServiceEvents -Owner $owner -PrinterName $printerName
if ($eventDocumentName) { if ($eventDocumentName) {
$documentName = $eventDocumentName $documentName = $eventDocumentName
} }
} }
$printDocumentNorm = if ($documentName) { [string]$documentName } else { '' }
$printSignalKey = ('{0}|{1}|{2}|{3}' -f
(Normalize-PrinterForMatch -Value $printerName),
(Normalize-OwnerForMatch -Value $owner),
$printDocumentNorm.ToLowerInvariant(),
'print_job')
if (-not (Should-EmitByCooldown -Fingerprint $printSignalKey -CooldownSeconds 90)) {
continue
}
Send-EndpointSignalHeartbeat -SignalType 'print_job' -Data @{ Send-EndpointSignalHeartbeat -SignalType 'print_job' -Data @{
printerName = $printerName printerName = $printerName
documentName = $documentName documentName = $documentName
documentNameOriginal = $documentNameOriginal documentNameOriginal = $documentNameOriginal
owner = $owner owner = $owner
eventSource = 'win32_printjob'
} }
Evaluate-PrintRules -PrinterName $printerName -DocumentName $documentName -Owner $owner Evaluate-PrintRules -PrinterName $printerName -DocumentName $documentName -Owner $owner
} }
@@ -976,7 +902,6 @@ while ($true) {
} }
} }
catch { catch {
Write-EndpointLog ("printjob poll failed: {0}" -f $_.Exception.Message)
} }
try { try {
@@ -1004,17 +929,6 @@ while ($true) {
continue continue
} }
$effectiveDocument = if ($resolvedDocument) { [string]$resolvedDocument } else { [string]$documentName }
$printSignalKey = ('{0}|{1}|{2}|{3}' -f
(Normalize-PrinterForMatch -Value $printerName),
(Normalize-OwnerForMatch -Value $owner),
$effectiveDocument.ToLowerInvariant(),
'print_job')
if (-not (Should-EmitByCooldown -Fingerprint $printSignalKey -CooldownSeconds 90)) {
Write-PrintServiceEventTrace -EventSummary $summary -Phase 'skip' -MatchReason 'dedupe-recent-printjob' -ResolvedDocument $resolvedDocument
continue
}
Send-EndpointSignalHeartbeat -SignalType 'print_job' -Data @{ Send-EndpointSignalHeartbeat -SignalType 'print_job' -Data @{
printerName = $printerName printerName = $printerName
documentName = if ($resolvedDocument) { $resolvedDocument } else { $documentName } documentName = if ($resolvedDocument) { $resolvedDocument } else { $documentName }
@@ -1035,7 +949,6 @@ while ($true) {
} }
} }
catch { catch {
Write-EndpointLog ("printservice poll failed: {0}" -f $_.Exception.Message)
} }
} }
catch { catch {
+8 -1
View File
@@ -103,6 +103,13 @@ function Get-SessionRecords {
return $records return $records
} }
function Test-SessionIsActive {
param([AllowNull()][string]$State)
if ([string]::IsNullOrWhiteSpace($State)) { return $false }
$s = $State.Trim().ToLowerInvariant()
return ($s -eq 'active') -or ($s -like 'актив*')
}
$cfg = Get-Config -Path $ConfigPath $cfg = Get-Config -Path $ConfigPath
$hostValue = if ($Hostname) { $Hostname } else { [string]$env:COMPUTERNAME } $hostValue = if ($Hostname) { $Hostname } else { [string]$env:COMPUTERNAME }
$apiBase = '{0}://{1}:{2}/api/0' -f [string]$cfg.server.scheme, [string]$cfg.server.host, [string]$cfg.server.port $apiBase = '{0}://{1}:{2}/api/0' -f [string]$cfg.server.scheme, [string]$cfg.server.host, [string]$cfg.server.port
@@ -142,7 +149,7 @@ while ($true) {
sessionId = [int]$rec.sessionId sessionId = [int]$rec.sessionId
sessionName = [string]$rec.sessionName sessionName = [string]$rec.sessionName
state = [string]$rec.state state = [string]$rec.state
active = ($rec.state -match 'Active') active = (Test-SessionIsActive -State ([string]$rec.state))
hostname = $hostValue hostname = $hostValue
source = 'worktime-session-collector' source = 'worktime-session-collector'
} }