### Start SFTP Server with sftp.New() Source: https://context7.com/open-uem/openuem-agent/llms.txt Initializes and starts an embedded SFTP server. It validates clients against the console's SFTP certificate and caches results. The server runs in a goroutine if configured. ```go import ( "crypto/x509" "github.com/dgraph-io/badger/v4" openuem_utils "github.com/open-uem/utils" "github.com/open-uem/openuem-agent/internal/commands/sftp" ) // Typically called inside agent.Start() sftpServer := sftp.New() caCert, _ := openuem_utils.ReadPEMCertificate("/etc/openuem-agent/certificates/ca.cer") sftpCert, _ := openuem_utils.ReadPEMCertificate("/etc/openuem-agent/certificates/sftp.cer") db, _ := badger.Open(badger.DefaultOptions("/etc/openuem-agent/badgerdb")) deffer db.Close() // Blocks; run in a goroutine go func() { if err := sftpServer.Serve(":2022", sftpCert, caCert, db); err != nil { log.Printf("[ERROR]: SFTP server error: %v", err) } }() ``` -------------------------------- ### Install Package with deploy.InstallPackage() Source: https://context7.com/open-uem/openuem-agent/llms.txt Used internally when the agent receives an install package command. Handles package installation and sends deployment results back. ```go action := openuem_nats.DeployAction{ AgentId: "550e8400-e29b-41d4-a716-446655440000", PackageId: "Mozilla.Firefox", PackageVersion: "", // empty = latest PackageName: "Mozilla Firefox", Action: "install", } stdout, stderr, err := deploy.InstallPackage(action, false /*keepUpdated*/, true /*debug*/) if err != nil { log.Printf("[ERROR]: install failed: %v", err) } else if stderr != "" { log.Printf("[WARN]: winget stderr: %s", stderr) } else { log.Printf("[INFO]: installed successfully\n%s", stdout) } // Send result back to the worker action.When = time.Now() action.Failed = stderr != "" action.Info = stderr if err := a.SendDeployResult(&action); err != nil { // Persist for retry _ = SaveDeploymentNotACK(action) } ``` -------------------------------- ### Start VNC Proxy with remotedesktop.New() Source: https://context7.com/open-uem/openuem-agent/llms.txt Creates a VNC proxy service that bridges a noVNC client to a local VNC server. It selects the appropriate VNC backend based on the OS and starts when the agent receives a start command. ```go import rd "github.com/open-uem/openuem-agent/internal/commands/remote-desktop" // Instantiate the remote desktop service service, err := rd.New( "/etc/openuem-agent/certificates/server.cer", // TLS cert for the proxy "/etc/openuem-agent/certificates/server.key", // TLS key "", // SID (Windows only; empty on Linux/macOS) "8443", // VNC proxy WebSocket port ) if err != nil { log.Fatalf("could not create remote desktop service: %v", err) } // Start the VNC server and proxy (non-blocking in practice; called from NATS handler) pin := []byte("123456") notifyUser := true service.Start(pin, notifyUser) // Now a noVNC client can connect to wss://endpoint:8443/ws // Stop when the console sends agent.stopvnc. service.Stop() ``` -------------------------------- ### Initialize, Start, and Stop OpenUEM Agent Source: https://context7.com/open-uem/openuem-agent/llms.txt This snippet shows the main entry point for the OpenUEM agent. It initializes the agent, starts its services in a separate goroutine, and sets up graceful shutdown handling for SIGTERM and SIGINT signals. ```go package main import ( "log" "os" "os/signal" "syscall" "github.com/open-uem/openuem-agent/internal/agent" ) func main() { // Create and initialise the agent (reads openuem.ini, loads certificates) a := agent.New() // Start all services: SFTP, NATS connection, report scheduler // This call blocks until the agent's goroutines are running go a.Start() // Graceful shutdown on SIGTERM / SIGINT quit := make(chan os.Signal, 1) signal.Notify(quit, syscall.SIGTERM, syscall.SIGINT) <-quit a.Stop() log.Println("agent stopped") } ``` -------------------------------- ### SFTP Server Initialization and Serving Source: https://context7.com/open-uem/openuem-agent/llms.txt Initializes and starts an embedded SFTP server that validates clients against a console's SFTP certificate. ```APIDOC ## SFTP Server ### Description Initializes and starts an embedded SFTP server. ### Functions - `sftp.New() *sftp.SFTP` - `sftp.SFTP.Serve(addr string, sftpCert, caCert *x509.Certificate, db *badger.DB) error` ### Parameters - `addr` (string): The network address to listen on (e.g., ":2022"). - `sftpCert` (*x509.Certificate): The SFTP server certificate. - `caCert` (*x509.Certificate): The CA certificate for validation. - `db` (*badger.DB): The BadgerDB instance for caching OCSP results. ### Initialization Example ```go sftpServer := sftp.New() caCert, _ := openuem_utils.ReadPEMCertificate("/etc/openuem-agent/certificates/ca.cer") sftpCert, _ := openuem_utils.ReadPEMCertificate("/etc/openuem-agent/certificates/sftp.cer") db, _ := badger.Open(badger.DefaultOptions("/etc/openuem-agent/badgerdb")) defer db.Close() // Run in a goroutine go func() { if err := sftpServer.Serve(":2022", sftpCert, caCert, db); err != nil { log.Printf("[ERROR]: SFTP server error: %v", err) } }() ``` ### Response - `sftp.New()` returns a pointer to an `sftp.SFTP` server instance. - `sftp.SFTP.Serve()` returns an error if the server fails to start. ``` -------------------------------- ### OpenUEM Agent Configuration File Source: https://context7.com/open-uem/openuem-agent/llms.txt This is an example of the `openuem.ini` configuration file, detailing settings for the agent, NATS connection, and certificates. It serves as the primary configuration source for the agent. ```ini # openuem.ini — minimal working configuration [Agent] UUID = 550e8400-e29b-41d4-a716-446655440000 Enabled = true Debug = false DefaultFrequency = 60 ; minutes between reports ExecuteTaskEveryXMinutes = 5 WingetConfigureFrequency = 30 SFTPPort = 2022 VNCProxyPort = 8443 SFTPDisabled = false RemoteAssistanceDisabled = false TenantID = tenant-01 SiteID = site-hq [NATS] NATSServers = nats://nats.corp.example.com:4222 WebSocketPort = 443 [Certificates] AgentCert = /etc/openuem-agent/certificates/agent.cer AgentKey = /etc/openuem-agent/certificates/agent.key CACert = /etc/openuem-agent/certificates/ca.cer SFTPCert = /etc/openuem-agent/certificates/sftp.cer ``` -------------------------------- ### Manage NetBird VPN Agent Source: https://context7.com/open-uem/openuem-agent/llms.txt Installs, registers, uninstalls, and controls the NetBird WireGuard overlay agent. A new inventory report is triggered after successful install or registration. ```go import ( "encoding/json" "github.com/open-uem/openuem-agent/internal/commands/netbird" openuem_nats "github.com/open-uem/nats" ) // Install NetBird binary data, err := netbird.Install() if err != nil { log.Printf("[ERROR]: netbird install failed: %v", err) } // Register with a management server settings := openuem_nats.NetbirdSettings{ ManagementURL: "https://netbird.corp.example.com", SetupKey: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", } payload, _ := json.Marshal(settings) data, err = netbird.Register(payload) if err != nil { log.Printf("[ERROR]: netbird register failed: %v", err) } log.Printf("[INFO]: NetBird registered: %+v", data) // Bring the tunnel up data, err = netbird.NetbirdUp(payload) if err != nil { log.Printf("[ERROR]: netbird up failed: %v", err) } // Uninstall completely if err := netbird.Uninstall(); err != nil { log.Printf("[ERROR]: netbird uninstall failed: %v", err) } ``` -------------------------------- ### Package Deployment Functions Source: https://context7.com/open-uem/openuem-agent/llms.txt Functions to install, update, and uninstall packages. These functions abstract the underlying OS-specific package managers (winget, Flatpak, Homebrew) and report results back to the central server. ```APIDOC ## Package Deployment ### Description Functions to trigger package installations, updates, and uninstalls. ### Functions - `deploy.InstallPackage(action DeployAction, keepUpdated bool, debug bool) (stdout string, stderr string, err error)` - `deploy.UpdatePackage(action DeployAction, keepUpdated bool, debug bool) (stdout string, stderr string, err error)` - `deploy.UninstallPackage(action DeployAction, keepUpdated bool, debug bool) (stdout string, stderr string, err error)` ### Parameters - `action` (DeployAction): A struct containing deployment details like AgentId, PackageId, PackageVersion, PackageName, and Action. - `keepUpdated` (bool): If true, the package will be kept updated. - `debug` (bool): If true, enables debug logging. ### Request Example (Install) ```go action := openuem_nats.DeployAction{ AgentId: "550e8400-e29b-41d4-a716-446655440000", PackageId: "Mozilla.Firefox", PackageVersion: "", // empty = latest PackageName: "Mozilla Firefox", Action: "install", } stdout, stderr, err := deploy.InstallPackage(action, false, true) ``` ### Response - `stdout` (string): Standard output from the package manager. - `stderr` (string): Standard error from the package manager. - `err` (error): An error object if the operation failed. ``` -------------------------------- ### NetBird VPN Management Source: https://context7.com/open-uem/openuem-agent/llms.txt Manages the NetBird WireGuard overlay agent, including installation, registration, and uninstallation. Triggers inventory reports after successful operations. ```APIDOC ## NetBird VPN Management Manages the NetBird WireGuard overlay agent, including installation, registration, and uninstallation. Triggers inventory reports after successful operations. ### Install NetBird ```go import ( "encoding/json" "github.com/open-uem/openuem-agent/internal/commands/netbird" openuem_nats "github.com/open-uem/nats" ) // Install NetBird binary data, err := netbird.Install() if err != nil { log.Printf("[ERROR]: netbird install failed: %v", err) } ``` ### Register NetBird ```go // Register with a management server settings := openuem_nats.NetbirdSettings{ ManagementURL: "https://netbird.corp.example.com", SetupKey: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", } payload, _ := json.Marshal(settings) data, err = netbird.Register(payload) if err != nil { log.Printf("[ERROR]: netbird register failed: %v", err) } log.Printf("[INFO]: NetBird registered: %+v", data) ``` ### Bring NetBird Tunnel Up ```go // Bring the tunnel up data, err = netbird.NetbirdUp(payload) if err != nil { log.Printf("[ERROR]: netbird up failed: %v", err) } ``` ### Uninstall NetBird ```go // Uninstall completely if err := netbird.Uninstall(); err != nil { log.Printf("[ERROR]: netbird uninstall failed: %v", err) } ``` ``` -------------------------------- ### Publish On-Demand Report Trigger via NATS JetStream Source: https://context7.com/open-uem/openuem-agent/llms.txt Publishes an on-demand report trigger to a specific NATS subject. Requires NATS connection setup with client certificates and root CAs. ```go // NATS subject catalogue (UUID = agent's unique identifier) // // JetStream (guaranteed delivery, durable consumer "AgentConsumer"): // agent.certificate. — receive and save the server TLS certificate // agent.enable. — enable reporting // agent.disable. — disable reporting // agent.report. — on-demand inventory report // agent.update.updater. — updater binary push // agent.rollback.updater. — updater rollback // // Core NATS (fire-and-forget / request-reply): // agent.startvnc. — start VNC / RDP session // agent.stopvnc. — stop VNC / RDP session // agent.rustdesk.start. — start RustDesk session // agent.rustdesk.stop. — stop RustDesk session // agent.installpackage. — install software package // agent.updatepackage. — update software package // agent.uninstallpackage. — uninstall software package // agent.settings. — update agent settings // agent.newconfig — broadcast new config to all agents // agent.reboot. — reboot endpoint // agent.poweroff. — power off endpoint // agent.defaultprinter. — set default printer // agent.removeprinter. — remove printer // agent.netbird.install. — install NetBird // agent.netbird.register. — register NetBird // agent.netbird.uninstall. — uninstall NetBird // agent.netbird.switchprofile. // agent.netbird.up. — netbird up // agent.netbird.down. — netbird down // agent.netbird.refresh. — refresh NetBird status // agent.ping. — connectivity check // agent.ansible. — run Ansible task (Linux/macOS) // agent.windowstask. — run WinGet DSC task (Windows) // agent.runprofile. — run full DSC profile // Example: publish an on-demand report trigger from outside the agent nc, _ := nats.Connect("nats://nats.corp.example.com:4222", nats.ClientCert("console.cer", "console.key"), nats.RootCAs("ca.cer"), ) js, _ := jetstream.New(nc) stream, _ := js.Stream(context.Background(), "AGENTS_STREAM") stream.Publish(context.Background(), "agent.report.550e8400-e29b-41d4-a716-446655440000", nil) ``` -------------------------------- ### Reload and Write Agent Configuration Source: https://context7.com/open-uem/openuem-agent/llms.txt This Go snippet demonstrates how to reload the agent's configuration at runtime, modify a specific setting (SFTP port), persist the changes back to the configuration file, and signal the platform watchdog that a restart is required. ```go // Reload config at runtime (called e.g. on agent.settings.UUID message) if err := a.ReadConfig(); err != nil { log.Printf("[ERROR]: could not reload config: %v", err) } // Persist a new SFTP port received from the console a.Config.SFTPPort = "2023" if err := a.Config.WriteConfig(); err != nil { log.Fatalf("[FATAL]: %v", err) } // Tell the watchdog that a restart is needed to apply the new port if err := a.Config.SetRestartRequiredFlag(); err != nil { log.Printf("[ERROR]: %v", err) } ``` -------------------------------- ### Run and Send Inventory Report with OpenUEM Agent Source: https://context7.com/open-uem/openuem-agent/llms.txt Collects endpoint telemetry and sends it via NATS. Handles no-IP edge cases and logs errors. Use `r.Print()` for a human-readable summary. ```go r := a.RunReport() if r == nil { log.Println("[WARN]: report is nil, skipping send") return } // r.Print() dumps a human-readable summary to stdout r.Print() // Output example: // ** 🕵 Agent **** // Computer Name | DESKTOP-ABC123 // IP address | 192.168.1.42 // Operating System | windows // ... // Send over NATS (blocks up to 4 minutes) if err := a.SendReport(r); err != nil { log.Printf("[ERROR]: send failed: %v", err) } ``` -------------------------------- ### Remote Desktop Service Initialization and Control Source: https://context7.com/open-uem/openuem-agent/llms.txt Manages the VNC/Remote Desktop proxy, allowing browser-based clients to connect to local VNC servers. ```APIDOC ## VNC / Remote Desktop Proxy ### Description Manages a VNC/Remote Desktop proxy service that bridges noVNC clients to local VNC servers. ### Functions - `remotedesktop.New(tlsCertPath, tlsKeyPath, sid, wsPort string) (*RemoteDesktopService, error)` - `RemoteDesktopService.Start(pin []byte, notifyUser bool)` - `RemoteDesktopService.Stop()` ### Parameters - `tlsCertPath` (string): Path to the TLS certificate for the proxy. - `tlsKeyPath` (string): Path to the TLS key for the proxy. - `sid` (string): Session ID (Windows only). - `wsPort` (string): The WebSocket port for the VNC proxy. - `pin` ([]byte): The PIN for VNC connection. - `notifyUser` (bool): Whether to notify the user about the connection. ### Initialization and Start Example ```go service, err := rd.New( "/etc/openuem-agent/certificates/server.cer", "/etc/openuem-agent/certificates/server.key", "", "8443", ) if err != nil { log.Fatalf("could not create remote desktop service: %v", err) } pin := []byte("123456") notifyUser := true service.Start(pin, notifyUser) ``` ### Stop Example ```go service.Stop() ``` ### Response - `remotedesktop.New()` returns a pointer to a `RemoteDesktopService` instance or an error. - `Start()` and `Stop()` do not return values but control the service's lifecycle. ``` -------------------------------- ### Apply Linux/macOS DSC Profiles with Ansible Source: https://context7.com/open-uem/openuem-agent/llms.txt Applies Ansible playbooks on Linux and macOS. The agent auto-installs the 'community.general' collection if missing. Task results are parsed from Ansible's JSON callback output. ```go // Ansible playbook YAML received via ansiblecfg.profiles ansibleYAML := ` - name: Ensure git is installed hosts: 127.0.0.1 become: true tasks: - name: Install git community.general.pacman: name: git state: present ` // Internally invoked by GetUnixConfigureProfiles → ProcessProfileResponse tasks, err := a.ApplyConfiguration( 7, // profileID []byte(ansibleYAML), taskControl, "/etc/openuem-agent/ansible/tasks.json", ) // Expected output structure: // tasks[0].Name = "Install git" // tasks[0].Failed = false // tasks[0].StdOut = "changed=0 ..." // tasks[0].EndTime = "2024-05-01T10:00:00Z" ``` -------------------------------- ### Apply DSC Configuration (Windows/Linux/macOS) Source: https://context7.com/open-uem/openuem-agent/llms.txt Applies desired state configurations using WinGet DSC on Windows or Ansible playbooks on Linux/macOS. The agent handles task idempotency and reports completion status. ```APIDOC ## Apply DSC Configuration (Windows/Linux/macOS) Applies desired state configurations using WinGet DSC on Windows or Ansible playbooks on Linux/macOS. The agent handles task idempotency and reports completion status. ### Windows (WinGet DSC) ```go // Profile YAML sent from the server (wingetcfg.profiles response) profileYAML := ` properties: resources: - resource: Microsoft.WinGet.DSC/WinGetPackage id: install-vscode directives: description: Visual Studio Code settings: id: Microsoft.VisualStudioCode Ensure: Present uselatest: false - resource: PSDscResources/Registry id: disable-telemetry directives: description: Disable Windows telemetry settings: Key: HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\DataCollection ValueName: AllowTelemetry ValueType: Dword ValueData: "0" Ensure: Present - resource: PSDscResources/User id: create-svc-account settings: UserName: svcapp Password: "S3cur3P@ss!" Ensure: Present PasswordNeverExpires: true Disabled: false ` // Internally called by GetWingetConfigureProfiles → ProcessProfileResponse tasks, err := a.ApplyConfiguration( 42, // profileID []byte(profileYAML), []string{}, // exclusions (packages to skip) []string{}, // deployments (packages to track) taskControl, "/path/to/tasks.json", false, // force re-run even if task already succeeded ) for _, t := range tasks { if t.Failed { log.Printf("[ERROR]: task %s failed: %s", t.Name, t.StdErr) } else { log.Printf("[INFO]: task %s succeeded at %s", t.Name, t.EndTime) } } ``` ### Linux/macOS (Ansible) ```go // Ansible playbook YAML received via ansiblecfg.profiles ansibleYAML := ` - name: Ensure git is installed hosts: 127.0.0.1 become: true tasks: - name: Install git community.general.pacman: name: git state: present ` // Internally invoked by GetUnixConfigureProfiles → ProcessProfileResponse tasks, err := a.ApplyConfiguration( 7, // profileID []byte(ansibleYAML), taskControl, "/etc/openuem-agent/ansible/tasks.json", ) // Expected output structure: // tasks[0].Name = "Install git" // tasks[0].Failed = false // tasks[0].StdOut = "changed=0 ..." // tasks[0].EndTime = "2024-05-01T10:00:00Z" ``` ``` -------------------------------- ### Apply Windows DSC Profiles with WinGet Source: https://context7.com/open-uem/openuem-agent/llms.txt Applies YAML DSC profiles using WinGet on Windows. Task completion state is stored in 'powershell/tasks.json' for idempotency. Use 'force=true' to re-run tasks. ```go // Profile YAML sent from the server (wingetcfg.profiles response) profileYAML := ` properties: resources: - resource: Microsoft.WinGet.DSC/WinGetPackage id: install-vscode directives: description: Visual Studio Code settings: id: Microsoft.VisualStudioCode Ensure: Present uselatest: false - resource: PSDscResources/Registry id: disable-telemetry directives: description: Disable Windows telemetry settings: Key: HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\DataCollection ValueName: AllowTelemetry ValueType: Dword ValueData: "0" Ensure: Present - resource: PSDscResources/User id: create-svc-account settings: UserName: svcapp Password: "S3cur3P@ss!" Ensure: Present PasswordNeverExpires: true Disabled: false ` // Internally called by GetWingetConfigureProfiles → ProcessProfileResponse tasks, err := a.ApplyConfiguration( 42, // profileID []byte(profileYAML), []string{}, // exclusions (packages to skip) []string{}, // deployments (packages to track) taskControl, "/path/to/tasks.json", false, // force re-run even if task already succeeded ) for _, t := range tasks { if t.Failed { log.Printf("[ERROR]: task %s failed: %s", t.Name, t.StdErr) } else { log.Printf("[INFO]: task %s succeeded at %s", t.Name, t.EndTime) } } ``` -------------------------------- ### Manage DSC Task Control File in Go Source: https://context7.com/open-uem/openuem-agent/llms.txt Use `ReadTaskControlFile` to load task status, `SetTaskAsSuccessfull` to mark a task as completed, and `SaveTaskControl` to persist changes. This prevents idempotent tasks from re-running. ```go import "github.com/open-uem/openuem-agent/internal/agent/dsc" taskControlPath := "/etc/openuem-agent/ansible/tasks.json" // Read or create the task control file tc, err := dsc.ReadTaskControlFile(taskControlPath) if err != nil { log.Fatalf("cannot read task control: %v", err) } // Check if a specific task ID already succeeded taskID := "install-git-task-01" alreadyDone := false for _, id := range tc.Success { if id == taskID { alreadyDone = true; break } } if !alreadyDone { // ... run the task ... if err := dsc.SetTaskAsSuccessfull(taskID, taskControlPath, tc); err != nil { log.Printf("[ERROR]: could not mark task as done: %v", err) } } // Contents of tasks.json after marking success: // { // "success": ["install-git-task-01"], // "executed": {}, // "profilesRunning": {} // } ``` -------------------------------- ### Handle Pending Deployment Acknowledgments in Go Source: https://context7.com/open-uem/openuem-agent/llms.txt Persist failed deployment results using `SaveDeploymentNotACK` for later retry. `ReadDeploymentNotACK` retrieves pending actions, and `SaveDeploymentsNotACK` updates the list after successful re-sends. ```go import ( "time" openuem_nats "github.com/open-uem/nats" ) // Persist a failed deploy result for later retry action := openuem_nats.DeployAction{ AgentId: "550e8400-e29b-41d4-a716-446655440000", PackageId: "Mozilla.Firefox", PackageName: "Mozilla Firefox", Action: "install", Failed: true, Info: "winget exit code 0x8A15002B", When: time.Now(), } if err := SaveDeploymentNotACK(action); err != nil { log.Printf("[ERROR]: could not persist pending ACK: %v", err) } // Later, in PendingACKTask: pending, err := ReadDeploymentNotACK() if err != nil { log.Printf("[ERROR]: %v", err) return } remaining := []openuem_nats.DeployAction{} for _, act := range pending { if err := a.SendDeployResult(&act); err != nil { remaining = append(remaining, act) // keep for next cycle } } _ = SaveDeploymentsNotACK(remaining) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.