Author SHA1 Message Date
Paulo Truta 9bbe3d9997 Add secure dashboard-managed SSH public-key access
Replace server-generated key escrow with public-key-only enable/disable
tasks. Validate ED25519 keys, atomically reconcile one marked
authorized_keys entry, preserve operator keys, and never handle
private keys. Return real task errors and add lifecycle tests.
2026-09-23 23:17:46 +02:00
Paulo Truta 7996c552f8 Fix runs commands on docker compose (internal) 2025-10-05 20:24:02 +02:00
Paulo Truta dbc831e972 Added readme 2024-12-08 21:18:01 +01:00
Paulo Truta 19acbcbaad Hotfix: Add correct path for internet url option of browser dev environment 2024-12-08 21:16:33 +01:00
dependabot[bot]anddependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> 1e0a5df370 Bump actions/setup-go from 4 to 5 (#36)
Bumps [actions/setup-go](https://github.com/actions/setup-go) from 4 to 5.
- [Release notes](https://github.com/actions/setup-go/releases)
- [Commits](https://github.com/actions/setup-go/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/setup-go
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-12-08 21:04:42 +01:00
Paulo Truta 7913be080d Release 1.3.1 (#41)
* Added password refresh to activate browser dev task

* Added http and https prefixes to broserdevurl

* Added changelog file
2024-12-08 21:03:18 +01:00
Paulo Truta e80aaf7d18 Release/1.3.0 (#40)
* Implemented scaffolding for BrowserDev tasks and implemented taskGetBrowserDevPassword

* Added SetBrowserDevPasswordFile and ReplaceTextInFile funcs

* Added browserDevProxyPath

* Polished code and added missing pieces

* Improved Makefile with info and install + build processes

* Added vscode tasks support

* Added run command and reverted build-all to old logic, added run vscode task

* Added GetBrowserDevStatus task and into schedules

* Fixed check for tasks.GetBrowserStatus()

* Reverted to no result log in Exec command
2024-12-07 01:26:45 +01:00
Paulo Truta b11034dd17 Shell timeout log only every 10 seconds 2024-11-04 13:36:52 +01:00
Paulo Truta 80fc8b40cd Remove postinstall flagged file when removing app 2024-11-03 03:25:59 +01:00
Paulo Truta 01f423ee84 Add support to fetch experimental info from apps, add bulk install edgeapps task 2024-11-02 22:42:56 +01:00
Paulo Truta a8b1da4b7c Added update_system task and accompanying logic (#37) 2024-07-04 16:22:32 +02:00
Paulo Truta 6ccd4a3299 Excluding tiny storage devices 2024-04-21 00:46:30 +02:00
Paulo Truta 42b1a34ca7 Fix runnable file check 2024-04-17 20:48:53 +02:00
Paulo Truta 4bb343769f Faster GetEdgeAppServices by skipping ones that should not be running 2024-04-17 20:40:00 +02:00
Paulo Trutaand= <=> 3bb6200b1c Added args and tasks to start and stop the sshx shell (#35)
Co-authored-by: = <=>
2024-04-17 20:18:13 +02:00
dependabot[bot]anddependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> eae72b0a79 Bump actions/checkout from 3 to 4 (#34)
Bumps [actions/checkout](https://github.com/actions/checkout) from 3 to 4.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-11-20 21:10:09 +01:00
16 changed files with 1656 additions and 279 deletions
+2 -2
View File
@@ -13,11 +13,11 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Set up Go
uses: actions/setup-go@v4
uses: actions/setup-go@v5
with:
go-version: '1.20.2'
- name: Check out code
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: Build
run: make build
- name: Test
+236
View File
@@ -0,0 +1,236 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "Build",
"type": "shell",
"command": "make",
"args": ["build"],
"options": {
"cwd": "${workspaceFolder}"
},
"group": {
"kind": "build",
"isDefault": true
},
"problemMatcher": []
},
{
"label": "Build All",
"type": "shell",
"command": "make",
"args": ["build-all"],
"options": {
"cwd": "${workspaceFolder}"
},
"group": "build",
"problemMatcher": []
},
{
"label": "Build Prod",
"type": "shell",
"command": "make",
"args": ["build-prod"],
"options": {
"cwd": "${workspaceFolder}"
},
"group": "build",
"problemMatcher": []
},
{
"label": "Build Cloud",
"type": "shell",
"command": "make",
"args": ["build-cloud"],
"options": {
"cwd": "${workspaceFolder}"
},
"group": "build",
"problemMatcher": []
},
{
"label": "Build ARM64",
"type": "shell",
"command": "make",
"args": ["build-arm64"],
"options": {
"cwd": "${workspaceFolder}"
},
"group": "build",
"problemMatcher": []
},
{
"label": "Build ARMHF",
"type": "shell",
"command": "make",
"args": ["build-armhf"],
"options": {
"cwd": "${workspaceFolder}"
},
"group": "build",
"problemMatcher": []
},
{
"label": "Build AMD64",
"type": "shell",
"command": "make",
"args": ["build-amd64"],
"options": {
"cwd": "${workspaceFolder}"
},
"group": "build",
"problemMatcher": []
},
{
"label": "Clean",
"type": "shell",
"command": "make",
"args": ["clean"],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": []
},
{
"label": "Test",
"type": "shell",
"command": "make",
"args": ["test"],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": []
},
{
"label": "Test with Coverage",
"type": "shell",
"command": "make",
"args": ["test-with-coverage"],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": []
},
{
"label": "Run",
"type": "shell",
"command": "make",
"args": ["run"],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": []
},
{
"label": "Install",
"type": "shell",
"command": "make",
"args": ["install"],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": []
},
{
"label": "Install Prod",
"type": "shell",
"command": "make",
"args": ["install-prod"],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": []
},
{
"label": "Install Cloud",
"type": "shell",
"command": "make",
"args": ["install-cloud"],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": []
},
{
"label": "Install ARM64",
"type": "shell",
"command": "make",
"args": ["install-arm64"],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": []
},
{
"label": "Install ARMHF",
"type": "shell",
"command": "make",
"args": ["install-armhf"],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": []
},
{
"label": "Install AMD64",
"type": "shell",
"command": "make",
"args": ["install-amd64"],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": []
},
{
"label": "Start",
"type": "shell",
"command": "make",
"args": ["start"],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": []
},
{
"label": "Stop",
"type": "shell",
"command": "make",
"args": ["stop"],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": []
},
{
"label": "Restart",
"type": "shell",
"command": "make",
"args": ["restart"],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": []
},
{
"label": "Status",
"type": "shell",
"command": "make",
"args": ["status"],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": []
},
{
"label": "Logs",
"type": "shell",
"command": "make",
"args": ["log"],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": []
}
]
}
+29
View File
@@ -0,0 +1,29 @@
# Changelog
## [1.4.0] - 23-09-2026
* Added dashboard-managed SSH public-key access.
* Validates ED25519 public keys and reports their SHA256 fingerprints.
* Atomically installs or removes only the marked Edgebox key while preserving all other authorized keys.
* Never generates, reads, stores, logs, or returns SSH private keys.
## [1.3.2] - 08-12-2024
* Fix to Browser Dev feature:
* Checking browser dev url when internet_accessible was checking the incorrect path. This is now fixed.
## [1.3.1] - 08-12-2024
* Fixes to Browser Dev feature:
* Now edgeboxctl also fetches or generates the browser dev environment url and saves it into an option both when starting, and every time the browser dev status is fetched.
## [1.3.0] - 05-12-2024
* Added Edgebox Browser Development Environment Feature Support
* Added tasks for handling browser development environment into tasks.go
* Added executable tasks to ExecuteTask and scheduled ones to ExecuteSchedules
* Other bug fixes and improvements.
### Missing Past Releases
Release notes for past versions are not available in this file. Please refer to the [GitHub releases](https://hithub.com/edgebox-iot/edgeboxctl/releases) for more information. Feel free to contribute to this file by adding missing release notes.
+67 -7
View File
@@ -9,46 +9,106 @@ GOOS := $(shell go env GOOS)
GOARCH := $(shell go env GOARCH)
build-all: clean
build-all:
@echo "\n🏗️ Building all architectures for ${RELEASE} mode"
@echo "🟡 This will build all supported architectures and release combinations. It can take a while...\n"
GOOS=linux GOARCH=amd64 make build
GOOS=linux GOARCH=arm make build
GOOS=linux GOARCH=arm64 make build
@echo "\n🟢 All builds completed and available at ./bin/ \n"
build-prod:
GOOS=linux GOARCH=arm RELEASE=prod make build
build-cloud:
GOOS=linux GOARCH=amd64 RELEASE=cloud make build
build-arm64:
GOOS=linux GOARCH=arm64 RELEASE=prod make build
build-armhf:
GOOS=linux GOARCH=arm RELEASE=prod make build
build-amd64:
GOOS=linux GOARCH=amd64 RELEASE=prod make build
build:
@echo "Building ${GOOS}-${GOARCH}"
@echo "\n🏗️ Building edgeboxctl (${RELEASE} release) on ${GOOS} (${GOARCH})"
@echo "📦 Binary will be saved in ./${BUILD_DIR}/edgeboxctl-${GOOS}-${GOARCH}\n"
GOOS=${GOOS} GOARCH=${GOARCH} go build \
-trimpath -ldflags "-s -w -X ${PROJECT}/internal/diagnostics.Version=${RELEASE} \
-X ${PROJECT}/internal/diagnostics.Commit=${COMMIT} \
-X ${PROJECT}/internal/diagnostics.BuildDate=${BUILD_DATE}" \
-o bin/edgeboxctl-${GOOS}-${GOARCH} ${PROJECT}/cmd/edgeboxctl
@echo "\n🟢 Build task completed\n"
clean:
@echo "🧹 Cleaning build directory and go cache\n"
rm -rf ${BUILD_DIR}
go clean
@echo "\n🟢 Clean task completed\n"
test:
go test -tags=unit -timeout=600s -v ./...
test-with-coverage:
go test -tags=unit -timeout=600s -v ./... -coverprofile=coverage.out
run:
@echo "\n🚀 Running edgeboxctl\n"
./bin/edgeboxctl-${GOOS}-${GOARCH}
install:
@echo "📦 Installing edgeboxctl service (${RELEASE}) for ${GOOS} (${GOARCH})\n"
@echo "🚧 Stopping edgeboxctl service if it is running"
sudo systemctl stop edgeboxctl || true
@echo "\n🗑️ Removing old edgeboxctl binary and service"
sudo rm -rf /usr/local/bin/edgeboxctl /usr/local/sbin/edgeboctl /lib/systemd/system/edgeboxctl.service
@echo "\n🚚 Copying edgeboxctl binary to /usr/local/bin"
sudo cp ./bin/edgeboxctl-${GOOS}-${GOARCH} /usr/local/bin/edgeboxctl
sudo cp ./bin/edgeboxctl-${GOOS}-${GOARCH} /usr/local/sbin/edgeboxctl
@echo "\n🚚 Copying edgeboxctl service to /lib/systemd/system"
sudo cp ./edgeboxctl.service /lib/systemd/system/edgeboxctl.service
sudo systemctl daemon-reload
@echo "Edgeboxctl installed successfully"
@echo "To start edgeboxctl run: systemctl start edgeboxctl"
build-install: build install
@echo "\n 🚀 To start edgeboxctl run: make start"
@echo "🟢 Edgeboxctl installed successfully\n"
install-prod: build-prod install
install-cloud: build-cloud install
install-arm64: build-arm64 install
install-armhf: build-armhf install
install-amd64: build-amd64 install
start:
@echo "\n 🚀 Starting edgeboxctl service\n"
systemctl start edgeboxctl
@echo "\n 🟢 Edgebox service started\n"
stop:
@echo "\n✋ Stopping edgeboxctl service\n"
systemctl stop edgeboxctl
@echo "\n 🟢 Edgebox service stopped\n"
log: start
restart:
@echo "\n💫 Restarting edgeboxctl service\n"
systemctl restart edgeboxctl
@echo "\n 🟢 Edgebox service restarted\n"
status:
@echo "\n️ edgeboxctl Service Info:\n"
systemctl status edgeboxctl
log:
@echo "\n📰 edgeboxctl service logs:\n"
journalctl -fu edgeboxctl
+6 -4
View File
@@ -59,10 +59,12 @@ To get a local copy up and running follow these simple steps.
If you're running for development purposes, a docker container suffices, so make sure you have:
* docker
* docker compose
* docker compose (docker-compose-v2 package)
Check the following links for more info on [Docker](https://www.docker.com/) and [Docker Compose](https://docs.docker.com/compose/).
**Note:** If you don't have `docker compose` available, install it with: `sudo apt-get install docker-compose-v2`
Aditionally, `edgeboxctl` needs the following bash commands available wherever it runs:
* `arm-linux-gnueabi-gcc` (`sudo apt-get install gcc-arm*`)
@@ -79,10 +81,10 @@ Aditionally, `edgeboxctl` needs the following bash commands available wherever i
```sh
git clone https://github.com/edgebox-iot/edgeboxctl.git
```
2. Run Docker-Compose
```sh
docker-compose up
2. Run Docker Compose
```
docker compose up
+1
View File
@@ -8,6 +8,7 @@ require (
github.com/dustin/go-humanize v1.0.0 // indirect
github.com/go-ole/go-ole v1.2.5 // indirect
github.com/go-sql-driver/mysql v1.5.0
github.com/go-yaml/yaml v2.1.0+incompatible // indirect
github.com/joho/godotenv v1.3.0
github.com/mattn/go-sqlite3 v1.14.7 // indirect
github.com/shirou/gopsutil v3.21.4+incompatible // indirect
+2
View File
@@ -11,6 +11,8 @@ github.com/go-ole/go-ole v1.2.5 h1:t4MGB5xEDZvXI+0rMjjsfBsD7yAgp/s9ZDkL1JndXwY=
github.com/go-ole/go-ole v1.2.5/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs=
github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/go-yaml/yaml v2.1.0+incompatible h1:RYi2hDdss1u4YE7GwixGzWwVo47T8UQwnTLB6vQiq+o=
github.com/go-yaml/yaml v2.1.0+incompatible/go.mod h1:w2MrLa16VYP0jy6N7M5kHaCkaLENm+P+Tv+MfurjSw0=
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
github.com/joho/godotenv v1.3.0 h1:Zjp+RcGpHhGlrMbJzXTrZZPrWj+1vfm90La1wgB6Bhc=
github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg=
+13
View File
@@ -1,5 +1,18 @@
package diagnostics
type ReleaseVersion string
var Version string
var Commit string
var BuildDate string
const (
DEV_VERSION ReleaseVersion = "dev"
PROD_VERSION ReleaseVersion = "prod"
CLOUD_VERSION ReleaseVersion = "cloud"
OTHER_VERSION ReleaseVersion = "other"
)
func GetReleaseVersion() ReleaseVersion {
return ReleaseVersion(Version)
}
+91 -18
View File
@@ -11,6 +11,7 @@ import (
"github.com/edgebox-iot/edgeboxctl/internal/system"
"github.com/edgebox-iot/edgeboxctl/internal/utils"
"github.com/edgebox-iot/edgeboxctl/internal/diagnostics"
)
// EdgeApp : Struct representing an EdgeApp in the system
@@ -18,6 +19,7 @@ type EdgeApp struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Experimental bool `json:"experimental"`
Status EdgeAppStatus `json:"status"`
Services []EdgeAppService `json:"services"`
InternetAccessible bool `json:"internet_accessible"`
@@ -69,6 +71,7 @@ const optionsEnvFilename = "/edgeapp.env"
const authEnvFilename = "/auth.env"
const runnableFilename = "/.run"
const appdataFoldername = "/appdata"
const postInstallFilename = "/edgebox-postinstall.done"
const myEdgeAppServiceEnvFilename = "/myedgeapp.env"
const defaultContainerOperationSleepTime time.Duration = time.Second * 10
@@ -86,6 +89,7 @@ func GetEdgeApp(ID string) MaybeEdgeApp {
edgeAppName := ID
edgeAppDescription := ""
edgeAppExperimental := false
edgeAppOptions := []EdgeAppOption{}
edgeAppEnv, err := godotenv.Read(utils.GetPath(utils.EdgeAppsPath) + ID + envFilename)
@@ -99,6 +103,9 @@ func GetEdgeApp(ID string) MaybeEdgeApp {
if edgeAppEnv["EDGEAPP_DESCRIPTION"] != "" {
edgeAppDescription = edgeAppEnv["EDGEAPP_DESCRIPTION"]
}
if edgeAppEnv["EDGEAPP_EXPERIMENTAL"] == "true" {
edgeAppExperimental = true
}
}
needsConfig := false
@@ -231,6 +238,7 @@ func GetEdgeApp(ID string) MaybeEdgeApp {
ID: ID,
Name: edgeAppName,
Description: edgeAppDescription,
Experimental: edgeAppExperimental,
Status: GetEdgeAppStatus(ID),
Services: GetEdgeAppServices(ID),
InternetAccessible: edgeAppInternetAccessible,
@@ -263,22 +271,54 @@ func IsEdgeAppInstalled(ID string) bool {
}
func writeAppRunnableFiles(ID string) bool {
edgeAppPath := utils.GetPath(utils.EdgeAppsPath)
_, err := os.Stat(edgeAppPath + ID + runnableFilename)
if os.IsNotExist(err) {
_, err := os.Create(edgeAppPath + ID + runnableFilename)
if err != nil {
log.Fatal("Runnable file for EdgeApp could not be created!")
return false
}
// Check the block default apps option
blockDefaultAppsOption := utils.ReadOption("DASHBOARD_BLOCK_DEFAULT_APPS_PUBLIC_ACCESS")
if blockDefaultAppsOption != "yes" {
// Create myedgeapp.env file with default network URL
envFilePath := edgeAppPath + ID + myEdgeAppServiceEnvFilename
var networkURL string
domainName := utils.ReadOption("DOMAIN_NAME")
if domainName != "" {
networkURL = ID + "." + domainName
} else if diagnostics.GetReleaseVersion() == diagnostics.CLOUD_VERSION {
cluster := utils.ReadOption("CLUSTER")
username := utils.ReadOption("USERNAME")
if cluster != "" && username != "" {
networkURL = username + "-" + ID + "." + cluster
}
} else {
networkURL = ID + "." + system.GetHostname() + ".local" // default
}
env, _ := godotenv.Unmarshal("INTERNET_URL=" + networkURL)
err = godotenv.Write(env, envFilePath)
if err != nil {
log.Printf("Error creating myedgeapp.env file: %s", err)
// result = false
}
}
}
return true
}
func SetEdgeAppInstalled(ID string) bool {
result := true
edgeAppPath := utils.GetPath(utils.EdgeAppsPath)
_, err := os.Stat(edgeAppPath + ID + runnableFilename)
if os.IsNotExist(err) {
_, err := os.Create(edgeAppPath + ID + runnableFilename)
result = true
if err != nil {
log.Fatal("Runnable file for EdgeApp could not be created!")
result = false
}
if writeAppRunnableFiles(ID) {
buildFrameworkContainers()
} else {
@@ -292,6 +332,21 @@ func SetEdgeAppInstalled(ID string) bool {
}
func SetEdgeAppBulkInstalled(IDs []string) bool {
result := true
for _, ID := range IDs {
writeAppRunnableFiles(ID)
}
buildFrameworkContainers()
return result
}
func SetEdgeAppNotInstalled(ID string) bool {
// Stop the app first
@@ -330,6 +385,12 @@ func SetEdgeAppNotInstalled(ID string) bool {
log.Println(err)
}
err = os.Remove(utils.GetPath(utils.EdgeAppsPath) + ID + postInstallFilename)
if err != nil {
result = false
log.Println(err)
}
buildFrameworkContainers()
return result
@@ -416,12 +477,24 @@ func GetEdgeAppServices(ID string) []EdgeAppService {
var edgeAppServices []EdgeAppService
for _, serviceID := range serviceSlices {
cmdArgs = []string{"-f", wsPath + "/docker-compose.yml", "exec", "-T", serviceID, "echo", "'Service Check'"}
cmdResult := utils.Exec(wsPath, "docker-compose", cmdArgs)
shouldBeRunning := false
isRunning := false
if cmdResult != "" {
isRunning = true
// Is service "runnable" when .run lockfile in the app folder
_, err := os.Stat(utils.GetPath(utils.EdgeAppsPath) + ID + runnableFilename)
if !os.IsNotExist(err) {
shouldBeRunning = true
}
// Check if the service is actually running
if shouldBeRunning {
cmdArgs = []string{"-f", wsPath + "/docker-compose.yml", "exec", "-T", serviceID, "echo", "'Service Check'"}
cmdResult := utils.Exec(wsPath, "docker", append([]string{"compose"}, cmdArgs...))
if cmdResult != "" {
isRunning = true
}
}
edgeAppServices = append(edgeAppServices, EdgeAppService{ID: serviceID, IsRunning: isRunning})
}
@@ -438,7 +511,7 @@ func RunEdgeApp(ID string) EdgeAppStatus {
for _, service := range services {
cmdArgs = []string{"-f", wsPath + "/docker-compose.yml", "start", service.ID}
utils.Exec(wsPath, "docker-compose", cmdArgs)
utils.Exec(wsPath, "docker", append([]string{"compose"}, cmdArgs...))
}
// Wait for it to settle up before continuing...
@@ -456,7 +529,7 @@ func StopEdgeApp(ID string) EdgeAppStatus {
for _, service := range services {
cmdArgs = []string{"-f", wsPath + "/docker-compose.yml", "stop", service.ID}
utils.Exec(wsPath, "docker-compose", cmdArgs)
utils.Exec(wsPath, "docker", append([]string{"compose"}, cmdArgs...))
}
// Wait for it to settle up before continuing...
+45 -4
View File
@@ -2,10 +2,12 @@ package storage
import (
"fmt"
"strconv"
"os"
"path/filepath"
"strings"
"github.com/edgebox-iot/edgeboxctl/internal/diagnostics"
"github.com/edgebox-iot/edgeboxctl/internal/utils"
"github.com/shirou/gopsutil/disk"
)
@@ -72,11 +74,23 @@ const (
DISK_TYPE_SDA DeviceIdentifier = "sda"
DISK_TYPE_MCBLK DeviceIdentifier = "mmcblk0"
DISK_TYPE_VDA DeviceIdentifier = "vda"
MIN_DISK_SIZE int = 1048576 // 1GB in bytes
)
func GetDeviceIdentifier(release_version diagnostics.ReleaseVersion) DeviceIdentifier {
switch release_version {
case diagnostics.CLOUD_VERSION:
return DISK_TYPE_SDA
case diagnostics.PROD_VERSION:
return DISK_TYPE_MCBLK
}
return DISK_TYPE_SDA
}
// GetDevices : Returns a list of all available sotrage devices in structs filled with information
func GetDevices(release_version diagnostics.ReleaseVersion) []Device {
// GetDevices : Returns a list of all available storage devices in structs filled with information
func GetDevices() []Device {
var devices []Device
cmdArgs := []string{"--raw", "--bytes", "--noheadings"}
@@ -88,6 +102,8 @@ func GetDevices() []Device {
firstDevice := true
currentDeviceInUseFlag := false
mainDiskID := GetDeviceIdentifier(release_version)
for scanner.Scan() {
// 1 Device is represented here. Extract words in order for filling a Device struct
// Example deviceRawInfo: "mmcblk0 179:0 0 29.7G 0 disk"
@@ -120,7 +136,13 @@ func GetDevices() []Device {
currentDevice.InUse = currentDeviceInUseFlag
currentDeviceInUseFlag = false
currentPartitions = []Partition{}
devices = append(devices, currentDevice)
size, err := strconv.Atoi(currentDevice.Size)
if err != nil {
size = 0
}
if size > MIN_DISK_SIZE {
devices = append(devices, currentDevice)
}
} else {
firstDevice = false
}
@@ -139,9 +161,14 @@ func GetDevices() []Device {
Status: DeviceStatus{ID: 1, Description: "healthy"},
}
if device.ID == mainDiskID {
device.MainDevice = true
}
currentDevice = device
} else if isPartition {
mountpoint := ""
if len(deviceRawInfo) >= 7 {
mountpoint = deviceRawInfo[6]
@@ -174,8 +201,22 @@ func GetDevices() []Device {
currentDevice.Status.Description = "Not configured"
}
currentDevice.InUse = currentDeviceInUseFlag
devices = append([]Device{currentDevice}, devices...) // Prepending the first device...
fmt.Println("Secondary Storage Devices Found: ", len(devices))
fmt.Println("Main Storage Device size: ", currentDevice.Size)
// only append device if size > 1GB
if currentDevice.Size != "" && currentDevice.Size != "0" {
// Convert size to int
// Convert string to int
size, err := strconv.Atoi(currentDevice.Size)
if err != nil {
size = 0
}
if size > MIN_DISK_SIZE {
devices = append([]Device{currentDevice}, devices...) // Prepending the first device...
}
}
devices = getDevicesSpaceUsage(devices)
return devices
+8 -1
View File
@@ -7,7 +7,14 @@ import (
)
func TestGetDevices(t *testing.T) {
assertGetDevices(GetDevices(), t)
t.Log("Testing with release version dev")
assertGetDevices(GetDevices("dev"), t)
t.Log("Testing with release version prod")
assertGetDevices(GetDevices("prod"), t)
t.Log("Testing with release version cloud")
assertGetDevices(GetDevices("cloud"), t)
}
func assertGetDevices(devices []Device, t *testing.T) {
+173 -1
View File
@@ -7,6 +7,7 @@ import (
"log"
"os"
"io"
"errors"
"os/exec"
"bufio"
"path/filepath"
@@ -17,6 +18,7 @@ import (
"github.com/joho/godotenv"
"github.com/shirou/gopsutil/host"
"github.com/go-yaml/yaml"
)
type cloudflaredTunnelJson struct {
@@ -82,7 +84,6 @@ func SetupCloudOptions() {
if err != nil {
fmt.Println("Error loading .env file for cloud version setup")
return
}
if cloudEnv["NAME"] != "" {
@@ -426,3 +427,174 @@ func CopyFile(src string, dest string) error {
return nil
}
func CheckUpdates() {
fmt.Println("Checking for Edgebox System Updates.")
// Configure the service and start it
cmd := exec.Command("sh", "/home/system/components/updater/run.sh", "--check")
stdout, err := cmd.StdoutPipe()
if err != nil {
panic(err)
}
scanner := bufio.NewScanner(stdout)
err = cmd.Start()
if err != nil {
panic(err)
}
for scanner.Scan() {
// fmt.Println(scanner.Text())
text := scanner.Text()
fmt.Println(text)
}
if scanner.Err() != nil {
cmd.Process.Kill()
cmd.Wait()
fmt.Println("Error running updates check.")
utils.WriteOption("SYSTEM_UPDATES", "[]")
return
}
// Read targets.env file into JSON list structure
targets := []string{}
targetsFile, err := os.Open("/home/system/components/updater/targets.env")
if err != nil {
fmt.Println("No targets.env file found. Skipping.")
utils.WriteOption("SYSTEM_UPDATES", "[]")
return
}
defer targetsFile.Close()
scanner = bufio.NewScanner(targetsFile)
for scanner.Scan() {
text := scanner.Text()
// text line should look like: {"target": "<target>", "version": "<version>"}
target := strings.Split(text, "=")
newText := "{\"target\": \"" + strings.Replace(target[0], "_VERSION", "", -1) + "\", \"version\": \"" + target[1] + "\"}"
targets = append(targets, newText)
}
if scanner.Err() != nil {
fmt.Println("Error reading update targets file.")
utils.WriteOption("SYSTEM_UPDATES", "[]")
return
}
// convert targets to string
targetsString := strings.Join(targets, ",")
targetsString = "[" + targetsString + "]"
fmt.Println(targetsString)
// Write option with targets
utils.WriteOption("SYSTEM_UPDATES", targetsString)
}
func ApplyUpdates() {
fmt.Println("Applying Edgebox System Updates.")
utils.WriteOption("UPDATING_SYSTEM", "true")
// Configure the service and start it
cmd := exec.Command("sh", "/home/system/components/updater/run.sh", "--update")
stdout, err := cmd.StdoutPipe()
if err != nil {
panic(err)
}
scanner := bufio.NewScanner(stdout)
err = cmd.Start()
if err != nil {
panic(err)
}
for scanner.Scan() {
fmt.Println(scanner.Text())
text := scanner.Text()
fmt.Println(text)
}
if scanner.Err() != nil {
cmd.Process.Kill()
cmd.Wait()
panic(scanner.Err())
}
// If the system did not yet restart, set updating system to false
utils.WriteOption("UPDATING_SYSTEM", "false")
}
func FetchBrowserDevPasswordFromFile() (string, error) {
fmt.Println("Executing FetchBrowserDevPasswordFromFile")
// Read the "password" entry on the yaml file
// Read the yaml file in system.GetPath(BrowserDevPasswordFileLocation)
yamlFile, err := ioutil.ReadFile(utils.GetPath(utils.BrowserDevPasswordFileLocation))
if err != nil {
return "", err
}
// Parse the yaml file and get the "password" entry
var yamlFileMap yaml.MapSlice
err = yaml.Unmarshal(yamlFile, &yamlFileMap)
if err != nil {
return "", err
}
for _, item := range yamlFileMap {
key, value := item.Key, item.Value
if key == "password" {
if pwString, ok := value.(string); ok {
return pwString, nil
} else {
return "", errors.New("password value is not a string")
}
}
}
return "", errors.New("password key not found")
}
func SetBrowserDevPasswordFile(password string) error {
// Get current password from file
currentPassword, err := FetchBrowserDevPasswordFromFile()
if err != nil {
fmt.Println("Error fetching current password from file.")
return err
}
// Write the new password on the file using ReplaceTextInFile
err = ReplaceTextInFile(utils.GetPath(utils.BrowserDevPasswordFileLocation), currentPassword, password)
if err != nil {
fmt.Println("Error writing new password to file.")
return err
}
return nil
}
func ReplaceTextInFile(filePath string, oldText string, newText string) error {
// Open the file for reading
file, err := os.OpenFile(filePath, os.O_RDWR, 0644)
if err != nil {
return err
}
// Read the file contents
data, err := ioutil.ReadAll(file)
if err != nil {
return err
}
// Close the file
err = file.Close()
if err != nil {
return err
}
// Replace the text in the file
newData := strings.Replace(string(data), oldText, newText, -1)
// Write the new data back to the file
err = ioutil.WriteFile(filePath, []byte(newData), 0644)
if err != nil {
return err
}
return nil
}
+217
View File
@@ -0,0 +1,217 @@
package tasks
import (
"crypto/sha256"
"encoding/base64"
"encoding/binary"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/edgebox-iot/edgeboxctl/internal/utils"
)
const (
sshDirectory = "/root/.ssh"
managedSSHComment = "edgebox-dashboard-managed"
)
type sshAccessResult struct {
Status string `json:"status"`
PublicKey string `json:"public_key,omitempty"`
Fingerprint string `json:"fingerprint,omitempty"`
}
func taskEnableSSHAccess(args taskEnableSSHAccessArgs) (string, error) {
if err := verifyRootSSHAccess(); err != nil {
return "", err
}
publicKey, fingerprint, err := parseSSHEd25519PublicKey(args.PublicKey)
if err != nil {
return "", err
}
if err := reconcileManagedSSHKey(sshDirectory, publicKey); err != nil {
return "", err
}
utils.WriteOption("SSH_ACCESS_ENABLED", "true")
utils.WriteOption("SSH_PUBLIC_KEY", publicKey)
utils.WriteOption("SSH_KEY_FINGERPRINT", fingerprint)
result, err := json.Marshal(sshAccessResult{
Status: "enabled",
PublicKey: publicKey,
Fingerprint: fingerprint,
})
if err != nil {
return "", err
}
return string(result), nil
}
func taskDisableSSHAccess() (string, error) {
if err := reconcileManagedSSHKey(sshDirectory, ""); err != nil {
return "", err
}
utils.WriteOption("SSH_ACCESS_ENABLED", "false")
utils.DeleteOption("SSH_PUBLIC_KEY")
utils.DeleteOption("SSH_KEY_FINGERPRINT")
result, err := json.Marshal(sshAccessResult{Status: "disabled"})
if err != nil {
return "", err
}
return string(result), nil
}
func parseSSHEd25519PublicKey(input string) (string, string, error) {
trimmed := strings.TrimSpace(input)
if trimmed == "" || strings.ContainsAny(trimmed, "\r\n") {
return "", "", fmt.Errorf("provide exactly one SSH public key")
}
fields := strings.Fields(trimmed)
if len(fields) < 2 || len(fields) > 3 || fields[0] != "ssh-ed25519" {
return "", "", fmt.Errorf("only one ssh-ed25519 public key is supported")
}
keyBlob, err := base64.StdEncoding.DecodeString(fields[1])
if err != nil || !validEd25519KeyBlob(keyBlob) {
return "", "", fmt.Errorf("invalid ssh-ed25519 public key")
}
digest := sha256.Sum256(keyBlob)
publicKey := "ssh-ed25519 " + base64.StdEncoding.EncodeToString(keyBlob) + " " + managedSSHComment
fingerprint := "SHA256:" + base64.RawStdEncoding.EncodeToString(digest[:])
return publicKey, fingerprint, nil
}
func validEd25519KeyBlob(blob []byte) bool {
if len(blob) < 4 {
return false
}
typeLength := int(binary.BigEndian.Uint32(blob[:4]))
if typeLength != len("ssh-ed25519") || len(blob) < 4+typeLength+4 {
return false
}
if string(blob[4:4+typeLength]) != "ssh-ed25519" {
return false
}
keyLengthOffset := 4 + typeLength
keyLength := int(binary.BigEndian.Uint32(blob[keyLengthOffset : keyLengthOffset+4]))
return keyLength == 32 && len(blob) == keyLengthOffset+4+keyLength
}
func reconcileManagedSSHKey(directory string, publicKey string) error {
if info, err := os.Lstat(directory); err == nil {
if info.Mode()&os.ModeSymlink != 0 || !info.IsDir() {
return fmt.Errorf("SSH directory is not a regular directory")
}
} else if !os.IsNotExist(err) {
return fmt.Errorf("inspect SSH directory: %w", err)
} else if err := os.MkdirAll(directory, 0700); err != nil {
return fmt.Errorf("create SSH directory: %w", err)
}
if err := os.Chmod(directory, 0700); err != nil {
return fmt.Errorf("secure SSH directory: %w", err)
}
authorizedKeysPath := filepath.Join(directory, "authorized_keys")
if info, err := os.Lstat(authorizedKeysPath); err == nil && info.Mode()&os.ModeSymlink != 0 {
return fmt.Errorf("authorized_keys must not be a symbolic link")
} else if err != nil && !os.IsNotExist(err) {
return fmt.Errorf("inspect authorized_keys: %w", err)
}
existing, err := os.ReadFile(authorizedKeysPath)
if err != nil && !os.IsNotExist(err) {
return fmt.Errorf("read authorized_keys: %w", err)
}
lines := strings.Split(string(existing), "\n")
kept := make([]string, 0, len(lines)+1)
for _, line := range lines {
if strings.TrimSpace(line) == "" || isManagedSSHKey(line) {
continue
}
kept = append(kept, line)
}
if publicKey != "" {
kept = append(kept, publicKey)
}
contents := ""
if len(kept) > 0 {
contents = strings.Join(kept, "\n") + "\n"
}
temporary, err := os.CreateTemp(directory, ".authorized_keys-*")
if err != nil {
return fmt.Errorf("create authorized_keys temporary file: %w", err)
}
temporaryPath := temporary.Name()
defer os.Remove(temporaryPath)
if err := temporary.Chmod(0600); err != nil {
temporary.Close()
return fmt.Errorf("secure authorized_keys temporary file: %w", err)
}
if _, err := temporary.WriteString(contents); err != nil {
temporary.Close()
return fmt.Errorf("write authorized_keys: %w", err)
}
if err := temporary.Sync(); err != nil {
temporary.Close()
return fmt.Errorf("sync authorized_keys: %w", err)
}
if err := temporary.Close(); err != nil {
return fmt.Errorf("close authorized_keys: %w", err)
}
if err := os.Rename(temporaryPath, authorizedKeysPath); err != nil {
return fmt.Errorf("replace authorized_keys: %w", err)
}
return nil
}
func isManagedSSHKey(line string) bool {
fields := strings.Fields(line)
return len(fields) == 3 && fields[2] == managedSSHComment
}
func verifyRootSSHAccess() error {
sshdPath, err := exec.LookPath("sshd")
if err != nil {
sshdPath = "/usr/sbin/sshd"
if _, statErr := os.Stat(sshdPath); statErr != nil {
return fmt.Errorf("OpenSSH server is not installed")
}
}
output, err := exec.Command(sshdPath, "-T").Output()
if err != nil {
return fmt.Errorf("could not verify the effective SSH server configuration")
}
settings := string(output)
if !strings.Contains(settings, "pubkeyauthentication yes") {
return fmt.Errorf("SSH public-key authentication is disabled")
}
if strings.Contains(settings, "permitrootlogin no") {
return fmt.Errorf("SSH root login is disabled")
}
return nil
}
+111
View File
@@ -0,0 +1,111 @@
package tasks
import (
"encoding/base64"
"encoding/binary"
"os"
"path/filepath"
"strings"
"testing"
)
func testPublicKey(t *testing.T) string {
t.Helper()
blob := make([]byte, 4+len("ssh-ed25519")+4+32)
binary.BigEndian.PutUint32(blob[:4], uint32(len("ssh-ed25519")))
copy(blob[4:], "ssh-ed25519")
offset := 4 + len("ssh-ed25519")
binary.BigEndian.PutUint32(blob[offset:offset+4], 32)
for index := 0; index < 32; index++ {
blob[offset+4+index] = byte(index + 1)
}
return "ssh-ed25519 " + base64.StdEncoding.EncodeToString(blob) + " workstation"
}
func TestParseSSHEd25519PublicKey(t *testing.T) {
publicKey, fingerprint, err := parseSSHEd25519PublicKey(testPublicKey(t))
if err != nil {
t.Fatal(err)
}
if !strings.HasSuffix(publicKey, " "+managedSSHComment) {
t.Fatalf("public key does not have managed marker: %q", publicKey)
}
if !strings.HasPrefix(fingerprint, "SHA256:") {
t.Fatalf("unexpected fingerprint: %q", fingerprint)
}
}
func TestParseSSHEd25519PublicKeyRejectsUnsafeInput(t *testing.T) {
inputs := []string{
"",
"-----BEGIN OPENSSH PRIVATE KEY-----",
testPublicKey(t) + "\n" + testPublicKey(t),
"command=whoami " + testPublicKey(t),
"ssh-rsa AAAA invalid",
}
for _, input := range inputs {
if _, _, err := parseSSHEd25519PublicKey(input); err == nil {
t.Fatalf("expected input to be rejected: %q", input)
}
}
}
func TestReconcileManagedSSHKeyPreservesUnrelatedKeys(t *testing.T) {
directory := t.TempDir()
authorizedKeysPath := filepath.Join(directory, "authorized_keys")
original := "# operator key\nssh-ed25519 AAAAoperator operator\n"
if err := os.WriteFile(authorizedKeysPath, []byte(original), 0644); err != nil {
t.Fatal(err)
}
publicKey, _, err := parseSSHEd25519PublicKey(testPublicKey(t))
if err != nil {
t.Fatal(err)
}
if err := reconcileManagedSSHKey(directory, publicKey); err != nil {
t.Fatal(err)
}
if err := reconcileManagedSSHKey(directory, publicKey); err != nil {
t.Fatal(err)
}
contents, err := os.ReadFile(authorizedKeysPath)
if err != nil {
t.Fatal(err)
}
if strings.Count(string(contents), managedSSHComment) != 1 {
t.Fatalf("managed key is not idempotent: %s", contents)
}
if !strings.Contains(string(contents), original) {
t.Fatalf("unrelated content was changed: %s", contents)
}
if info, err := os.Stat(authorizedKeysPath); err != nil || info.Mode().Perm() != 0600 {
t.Fatalf("authorized_keys mode is not 0600: %v, %v", info, err)
}
if err := reconcileManagedSSHKey(directory, ""); err != nil {
t.Fatal(err)
}
contents, err = os.ReadFile(authorizedKeysPath)
if err != nil {
t.Fatal(err)
}
if string(contents) != original {
t.Fatalf("disable changed unrelated content: %q", contents)
}
}
func TestReconcileManagedSSHKeyRejectsSymlink(t *testing.T) {
directory := t.TempDir()
target := filepath.Join(directory, "target")
if err := os.WriteFile(target, []byte("preserve me"), 0600); err != nil {
t.Fatal(err)
}
if err := os.Symlink(target, filepath.Join(directory, "authorized_keys")); err != nil {
t.Fatal(err)
}
if err := reconcileManagedSSHKey(directory, ""); err == nil {
t.Fatal("expected symlink to be rejected")
}
}
+630 -242
View File
File diff suppressed because it is too large Load Diff
+25
View File
@@ -111,7 +111,10 @@ const ApiPath string = "apiPath"
const EdgeAppsPath string = "edgeAppsPath"
const EdgeAppsBackupPath string = "edgeAppsBackupPath"
const WsPath string = "wsPath"
const BrowserDevPath string = "browserDevPath"
const LoggerPath string = "loggerPath"
const BrowserDevPasswordFileLocation string = "browserDevPasswordFileLocation"
const BrowserDevProxyPath string = "browserDevProxyPath"
// GetPath : Returns either the hardcoded path, or a overwritten value via .env file at project root. Register paths here for seamless working code between dev and prod environments ;)
@@ -174,6 +177,14 @@ func GetPath(pathKey string) string {
targetPath = "/home/system/components/ws/"
}
case BrowserDevPath:
if env["BROWSERDEV_PATH"] != "" {
targetPath = env["BROWSERDEV_PATH"]
} else {
targetPath = "/home/system/components/dev/"
}
case LoggerPath:
if env["LOGGER_PATH"] != "" {
targetPath = env["LOGGER_PATH"]
@@ -189,6 +200,20 @@ func GetPath(pathKey string) string {
targetPath = "/home/system/components/backups/pw.txt"
}
case BrowserDevPasswordFileLocation:
if env["BROWSERDEV_PASSWORD_FILE_LOCATION"] != "" {
targetPath = env["BROWSERDEV_PASSWORD_FILE_LOCATION"]
} else {
targetPath = "/root/.config/code-server/config.yaml"
}
case BrowserDevProxyPath:
if env["BROWSERDEV_PROXY_PATH"] != "" {
targetPath = env["BROWSERDEV_PROXY_PATH"]
} else {
targetPath = "/home/system/components/dev/"
}
default:
log.Printf("path_key %s nonexistant in GetPath().\n", pathKey)