mirror of
https://github.com/fosrl/newt.git
synced 2026-03-26 20:46:41 +00:00
Compare commits
17 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0f6852b681 | ||
|
|
2b8e280f2e | ||
|
|
3a377d43de | ||
|
|
792057cf6c | ||
|
|
57afe91e85 | ||
|
|
3389088c43 | ||
|
|
e73150c187 | ||
|
|
18556f34b2 | ||
|
|
66c235624a | ||
|
|
b7af49d759 | ||
|
|
00a5fa1f37 | ||
|
|
d256d6c746 | ||
|
|
2cc957d55f | ||
|
|
d98eaa88b3 | ||
|
|
5b884042cd | ||
|
|
2265b61381 | ||
|
|
50fbfdc262 |
@@ -1,5 +1,5 @@
|
|||||||
# Copy this file to .env and fill in your values
|
# Copy this file to .env and fill in your values
|
||||||
# Required for connecting to Pangolin service
|
# Required for connecting to Pangolin service
|
||||||
PANGOLIN_ENDPOINT=https://example.com
|
PANGOLIN_ENDPOINT=https://app.pangolin.net
|
||||||
NEWT_ID=changeme-id
|
NEWT_ID=changeme-id
|
||||||
NEWT_SECRET=changeme-secret
|
NEWT_SECRET=changeme-secret
|
||||||
24
.github/workflows/cicd.yml
vendored
24
.github/workflows/cicd.yml
vendored
@@ -589,15 +589,23 @@ jobs:
|
|||||||
# sarif_file: trivy-ghcr.sarif
|
# sarif_file: trivy-ghcr.sarif
|
||||||
# category: Image Vulnerability Scan
|
# category: Image Vulnerability Scan
|
||||||
|
|
||||||
- name: Build binaries
|
#- name: Build binaries
|
||||||
|
# env:
|
||||||
|
# CGO_ENABLED: "0"
|
||||||
|
# GOFLAGS: "-trimpath"
|
||||||
|
# run: |
|
||||||
|
# set -euo pipefail
|
||||||
|
# TAG_VAR="${TAG}"
|
||||||
|
# make -j 10 go-build-release tag=$TAG_VAR
|
||||||
|
# shell: bash
|
||||||
|
|
||||||
|
- name: Run GoReleaser (binaries + deb/rpm/apk)
|
||||||
|
uses: goreleaser/goreleaser-action@v6
|
||||||
|
with:
|
||||||
|
version: latest
|
||||||
|
args: release --clean
|
||||||
env:
|
env:
|
||||||
CGO_ENABLED: "0"
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
GOFLAGS: "-trimpath"
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
TAG_VAR="${TAG}"
|
|
||||||
make -j 10 go-build-release tag=$TAG_VAR
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Create GitHub Release
|
- name: Create GitHub Release
|
||||||
uses: softprops/action-gh-release@5be0e66d93ac7ed76da52eca8bb058f665c3a5fe # v2.4.2
|
uses: softprops/action-gh-release@5be0e66d93ac7ed76da52eca8bb058f665c3a5fe # v2.4.2
|
||||||
|
|||||||
62
.github/workflows/publish-apt.yml
vendored
Normal file
62
.github/workflows/publish-apt.yml
vendored
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
name: Publish APT repo to S3/CloudFront
|
||||||
|
|
||||||
|
on:
|
||||||
|
release:
|
||||||
|
types: [published]
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
tag:
|
||||||
|
description: "Tag to publish (e.g. v1.9.0). Leave empty to use latest release."
|
||||||
|
required: false
|
||||||
|
type: string
|
||||||
|
backfill_all:
|
||||||
|
description: "Build/publish repo for ALL releases."
|
||||||
|
required: false
|
||||||
|
default: false
|
||||||
|
type: boolean
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
id-token: write
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
publish:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
env:
|
||||||
|
PKG_NAME: newt
|
||||||
|
SUITE: stable
|
||||||
|
COMPONENT: main
|
||||||
|
REPO_BASE_URL: https://repo.dev.fosrl.io/apt
|
||||||
|
|
||||||
|
AWS_REGION: ${{ vars.AWS_REGION }}
|
||||||
|
S3_BUCKET: ${{ vars.S3_BUCKET }}
|
||||||
|
S3_PREFIX: ${{ vars.S3_PREFIX }}
|
||||||
|
CLOUDFRONT_DISTRIBUTION_ID: ${{ vars.CLOUDFRONT_DISTRIBUTION_ID }}
|
||||||
|
|
||||||
|
INPUT_TAG: ${{ inputs.tag }}
|
||||||
|
BACKFILL_ALL: ${{ inputs.backfill_all }}
|
||||||
|
EVENT_TAG: ${{ github.event.release.tag_name }}
|
||||||
|
GH_REPO: ${{ github.repository }}
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Configure AWS credentials (OIDC)
|
||||||
|
uses: aws-actions/configure-aws-credentials@v4
|
||||||
|
with:
|
||||||
|
role-to-assume: ${{ secrets.AWS_ROLE_ARN }}
|
||||||
|
aws-region: ${{ vars.AWS_REGION }}
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: sudo apt-get update && sudo apt-get install -y dpkg-dev apt-utils gnupg curl jq gh
|
||||||
|
|
||||||
|
- name: Install nfpm
|
||||||
|
run: curl -fsSL https://github.com/goreleaser/nfpm/releases/latest/download/nfpm_Linux_x86_64.tar.gz | sudo tar -xz -C /usr/local/bin nfpm
|
||||||
|
|
||||||
|
- name: Publish APT repo
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
APT_GPG_PRIVATE_KEY: ${{ secrets.APT_GPG_PRIVATE_KEY }}
|
||||||
|
APT_GPG_PASSPHRASE: ${{ secrets.APT_GPG_PASSPHRASE }}
|
||||||
|
run: ./scripts/publish-apt.sh
|
||||||
62
.goreleaser.yaml
Normal file
62
.goreleaser.yaml
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
project_name: newt
|
||||||
|
|
||||||
|
release:
|
||||||
|
# du nutzt Tags wie 1.2.3 und 1.2.3-rc.1 (ohne v)
|
||||||
|
draft: true
|
||||||
|
prerelease: auto
|
||||||
|
name_template: "{{ .Tag }}"
|
||||||
|
mode: replace
|
||||||
|
|
||||||
|
builds:
|
||||||
|
- id: newt
|
||||||
|
main: ./main.go # <- falls du cmd/newt hast: ./cmd/newt
|
||||||
|
binary: newt
|
||||||
|
env:
|
||||||
|
- CGO_ENABLED=0
|
||||||
|
goos:
|
||||||
|
- linux
|
||||||
|
- darwin
|
||||||
|
- windows
|
||||||
|
- freebsd
|
||||||
|
goarch:
|
||||||
|
- amd64
|
||||||
|
- arm64
|
||||||
|
goarm:
|
||||||
|
- "6"
|
||||||
|
- "7"
|
||||||
|
flags:
|
||||||
|
- -trimpath
|
||||||
|
ldflags:
|
||||||
|
- -s -w -X main.version={{ .Tag }}
|
||||||
|
|
||||||
|
archives:
|
||||||
|
# Wichtig: format "binary" -> keine tar.gz, sondern raw binary wie bei dir aktuell
|
||||||
|
- id: raw
|
||||||
|
builds:
|
||||||
|
- newt
|
||||||
|
format: binary
|
||||||
|
name_template: >-
|
||||||
|
{{ .ProjectName }}_{{ .Os }}_{{ if eq .Arch "amd64" }}amd64{{ else if eq .Arch "arm64" }}arm64{{ else if eq .Arch "386" }}386{{ else }}{{ .Arch }}{{ end }}{{ if .Arm }}v{{ .Arm }}{{ end }}{{ if .Mips }}_{{ .Mips }}{{ end }}{{ if .Amd64 }}_{{ .Amd64 }}{{ end }}{{ if .Riscv64 }}_{{ .Riscv64 }}{{ end }}{{ if .Os | eq "windows" }}.exe{{ end }}
|
||||||
|
|
||||||
|
checksum:
|
||||||
|
name_template: "checksums.txt"
|
||||||
|
|
||||||
|
nfpms:
|
||||||
|
- id: packages
|
||||||
|
package_name: newt
|
||||||
|
builds:
|
||||||
|
- newt
|
||||||
|
vendor: fosrl
|
||||||
|
maintainer: fosrl <repo@fosrl.io>
|
||||||
|
description: Newt - userspace tunnel client and TCP/UDP proxy
|
||||||
|
license: AGPL-3.0
|
||||||
|
formats:
|
||||||
|
- deb
|
||||||
|
- rpm
|
||||||
|
- apk
|
||||||
|
bindir: /usr/bin
|
||||||
|
# sorgt dafür, dass die Paketnamen gut pattern-matchbar sind
|
||||||
|
file_name_template: "{{ .PackageName }}_{{ .Version }}_{{ .Arch }}"
|
||||||
|
contents:
|
||||||
|
- src: LICENSE
|
||||||
|
dst: /usr/share/doc/newt/LICENSE
|
||||||
151
authdaemon.go
Normal file
151
authdaemon.go
Normal file
@@ -0,0 +1,151 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"runtime"
|
||||||
|
|
||||||
|
"github.com/fosrl/newt/authdaemon"
|
||||||
|
"github.com/fosrl/newt/logger"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
defaultPrincipalsPath = "/var/run/auth-daemon/principals"
|
||||||
|
defaultCACertPath = "/etc/ssh/ca.pem"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
errPresharedKeyRequired = errors.New("auth-daemon-key is required when --auth-daemon is enabled")
|
||||||
|
errRootRequired = errors.New("auth-daemon must be run as root (use sudo)")
|
||||||
|
authDaemonServer *authdaemon.Server // Global auth daemon server instance
|
||||||
|
)
|
||||||
|
|
||||||
|
// startAuthDaemon initializes and starts the auth daemon in the background.
|
||||||
|
// It validates requirements (Linux, root, preshared key) and starts the server
|
||||||
|
// in a goroutine so it runs alongside normal newt operation.
|
||||||
|
func startAuthDaemon(ctx context.Context) error {
|
||||||
|
// Validation
|
||||||
|
if runtime.GOOS != "linux" {
|
||||||
|
return fmt.Errorf("auth-daemon is only supported on Linux, not %s", runtime.GOOS)
|
||||||
|
}
|
||||||
|
if os.Geteuid() != 0 {
|
||||||
|
return errRootRequired
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use defaults if not set
|
||||||
|
principalsFile := authDaemonPrincipalsFile
|
||||||
|
if principalsFile == "" {
|
||||||
|
principalsFile = defaultPrincipalsPath
|
||||||
|
}
|
||||||
|
caCertPath := authDaemonCACertPath
|
||||||
|
if caCertPath == "" {
|
||||||
|
caCertPath = defaultCACertPath
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create auth daemon server
|
||||||
|
cfg := authdaemon.Config{
|
||||||
|
DisableHTTPS: true, // We run without HTTP server in newt
|
||||||
|
PresharedKey: "this-key-is-not-used", // Not used in embedded mode, but set to non-empty to satisfy validation
|
||||||
|
PrincipalsFilePath: principalsFile,
|
||||||
|
CACertPath: caCertPath,
|
||||||
|
Force: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
srv, err := authdaemon.NewServer(cfg)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("create auth daemon server: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
authDaemonServer = srv
|
||||||
|
|
||||||
|
// Start the auth daemon in a goroutine so it runs alongside newt
|
||||||
|
go func() {
|
||||||
|
logger.Info("Auth daemon starting (native mode, no HTTP server)")
|
||||||
|
if err := srv.Run(ctx); err != nil {
|
||||||
|
logger.Error("Auth daemon error: %v", err)
|
||||||
|
}
|
||||||
|
logger.Info("Auth daemon stopped")
|
||||||
|
}()
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// runPrincipalsCmd executes the principals subcommand logic
|
||||||
|
func runPrincipalsCmd(args []string) {
|
||||||
|
opts := struct {
|
||||||
|
PrincipalsFile string
|
||||||
|
Username string
|
||||||
|
}{
|
||||||
|
PrincipalsFile: defaultPrincipalsPath,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse flags manually
|
||||||
|
for i := 0; i < len(args); i++ {
|
||||||
|
switch args[i] {
|
||||||
|
case "--principals-file":
|
||||||
|
if i+1 >= len(args) {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: --principals-file requires a value\n")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
opts.PrincipalsFile = args[i+1]
|
||||||
|
i++
|
||||||
|
case "--username":
|
||||||
|
if i+1 >= len(args) {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: --username requires a value\n")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
opts.Username = args[i+1]
|
||||||
|
i++
|
||||||
|
case "--help", "-h":
|
||||||
|
printPrincipalsHelp()
|
||||||
|
os.Exit(0)
|
||||||
|
default:
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: unknown flag: %s\n", args[i])
|
||||||
|
printPrincipalsHelp()
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validation
|
||||||
|
if opts.Username == "" {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: username is required\n")
|
||||||
|
printPrincipalsHelp()
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get principals
|
||||||
|
list, err := authdaemon.GetPrincipals(opts.PrincipalsFile, opts.Username)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
if len(list) == 0 {
|
||||||
|
fmt.Println("")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, principal := range list {
|
||||||
|
fmt.Println(principal)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func printPrincipalsHelp() {
|
||||||
|
fmt.Fprintf(os.Stderr, `Usage: newt principals [flags]
|
||||||
|
|
||||||
|
Output principals for a username (for AuthorizedPrincipalsCommand in sshd_config).
|
||||||
|
Read the principals file and print principals that match the given username, one per line.
|
||||||
|
Configure in sshd_config with AuthorizedPrincipalsCommand and %%u for the username.
|
||||||
|
|
||||||
|
Flags:
|
||||||
|
--principals-file string Path to the principals file (default "%s")
|
||||||
|
--username string Username to look up (required)
|
||||||
|
--help, -h Show this help message
|
||||||
|
|
||||||
|
Example:
|
||||||
|
newt principals --username alice
|
||||||
|
|
||||||
|
`, defaultPrincipalsPath)
|
||||||
|
}
|
||||||
27
authdaemon/connection.go
Normal file
27
authdaemon/connection.go
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
package authdaemon
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/fosrl/newt/logger"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ProcessConnection runs the same logic as POST /connection: CA cert, user create/reconcile, principals.
|
||||||
|
// Use this when DisableHTTPS is true (e.g. embedded in Newt) instead of calling the API.
|
||||||
|
func (s *Server) ProcessConnection(req ConnectionRequest) {
|
||||||
|
logger.Info("connection: niceId=%q username=%q metadata.sudo=%v metadata.homedir=%v",
|
||||||
|
req.NiceId, req.Username, req.Metadata.Sudo, req.Metadata.Homedir)
|
||||||
|
|
||||||
|
cfg := &s.cfg
|
||||||
|
if cfg.CACertPath != "" {
|
||||||
|
if err := writeCACertIfNotExists(cfg.CACertPath, req.CaCert, cfg.Force); err != nil {
|
||||||
|
logger.Warn("auth-daemon: write CA cert: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := ensureUser(req.Username, req.Metadata); err != nil {
|
||||||
|
logger.Warn("auth-daemon: ensure user: %v", err)
|
||||||
|
}
|
||||||
|
if cfg.PrincipalsFilePath != "" {
|
||||||
|
if err := writePrincipals(cfg.PrincipalsFilePath, req.Username, req.NiceId); err != nil {
|
||||||
|
logger.Warn("auth-daemon: write principals: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
224
authdaemon/host_linux.go
Normal file
224
authdaemon/host_linux.go
Normal file
@@ -0,0 +1,224 @@
|
|||||||
|
//go:build linux
|
||||||
|
|
||||||
|
package authdaemon
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"os/user"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/fosrl/newt/logger"
|
||||||
|
)
|
||||||
|
|
||||||
|
// writeCACertIfNotExists writes contents to path. If the file already exists: when force is false, skip; when force is true, overwrite only if content differs.
|
||||||
|
func writeCACertIfNotExists(path, contents string, force bool) error {
|
||||||
|
contents = strings.TrimSpace(contents)
|
||||||
|
if contents != "" && !strings.HasSuffix(contents, "\n") {
|
||||||
|
contents += "\n"
|
||||||
|
}
|
||||||
|
existing, err := os.ReadFile(path)
|
||||||
|
if err == nil {
|
||||||
|
existingStr := strings.TrimSpace(string(existing))
|
||||||
|
if existingStr != "" && !strings.HasSuffix(existingStr, "\n") {
|
||||||
|
existingStr += "\n"
|
||||||
|
}
|
||||||
|
if existingStr == contents {
|
||||||
|
logger.Debug("auth-daemon: CA cert unchanged at %s, skipping write", path)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if !force {
|
||||||
|
logger.Debug("auth-daemon: CA cert already exists at %s, skipping write (Force disabled)", path)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
} else if !os.IsNotExist(err) {
|
||||||
|
return fmt.Errorf("read %s: %w", path, err)
|
||||||
|
}
|
||||||
|
dir := filepath.Dir(path)
|
||||||
|
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||||
|
return fmt.Errorf("mkdir %s: %w", dir, err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(path, []byte(contents), 0644); err != nil {
|
||||||
|
return fmt.Errorf("write CA cert: %w", err)
|
||||||
|
}
|
||||||
|
logger.Info("auth-daemon: wrote CA cert to %s", path)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// writePrincipals updates the principals file at path: JSON object keyed by username, value is array of principals. Adds username and niceId to that user's list (deduped).
|
||||||
|
func writePrincipals(path, username, niceId string) error {
|
||||||
|
if path == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
username = strings.TrimSpace(username)
|
||||||
|
niceId = strings.TrimSpace(niceId)
|
||||||
|
if username == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
data := make(map[string][]string)
|
||||||
|
if raw, err := os.ReadFile(path); err == nil {
|
||||||
|
_ = json.Unmarshal(raw, &data)
|
||||||
|
}
|
||||||
|
list := data[username]
|
||||||
|
seen := make(map[string]struct{}, len(list)+2)
|
||||||
|
for _, p := range list {
|
||||||
|
seen[p] = struct{}{}
|
||||||
|
}
|
||||||
|
for _, p := range []string{username, niceId} {
|
||||||
|
if p == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, ok := seen[p]; !ok {
|
||||||
|
seen[p] = struct{}{}
|
||||||
|
list = append(list, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
data[username] = list
|
||||||
|
body, err := json.Marshal(data)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("marshal principals: %w", err)
|
||||||
|
}
|
||||||
|
dir := filepath.Dir(path)
|
||||||
|
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||||
|
return fmt.Errorf("mkdir %s: %w", dir, err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(path, body, 0644); err != nil {
|
||||||
|
return fmt.Errorf("write principals: %w", err)
|
||||||
|
}
|
||||||
|
logger.Debug("auth-daemon: wrote principals to %s", path)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// sudoGroup returns the name of the sudo group (wheel or sudo) that exists on the system. Prefers wheel.
|
||||||
|
func sudoGroup() string {
|
||||||
|
f, err := os.Open("/etc/group")
|
||||||
|
if err != nil {
|
||||||
|
return "sudo"
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
sc := bufio.NewScanner(f)
|
||||||
|
hasWheel := false
|
||||||
|
hasSudo := false
|
||||||
|
for sc.Scan() {
|
||||||
|
line := sc.Text()
|
||||||
|
if strings.HasPrefix(line, "wheel:") {
|
||||||
|
hasWheel = true
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(line, "sudo:") {
|
||||||
|
hasSudo = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if hasWheel {
|
||||||
|
return "wheel"
|
||||||
|
}
|
||||||
|
if hasSudo {
|
||||||
|
return "sudo"
|
||||||
|
}
|
||||||
|
return "sudo"
|
||||||
|
}
|
||||||
|
|
||||||
|
// ensureUser creates the system user if missing, or reconciles sudo and homedir to match meta.
|
||||||
|
func ensureUser(username string, meta ConnectionMetadata) error {
|
||||||
|
if username == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
u, err := user.Lookup(username)
|
||||||
|
if err != nil {
|
||||||
|
if _, ok := err.(user.UnknownUserError); !ok {
|
||||||
|
return fmt.Errorf("lookup user %s: %w", username, err)
|
||||||
|
}
|
||||||
|
return createUser(username, meta)
|
||||||
|
}
|
||||||
|
return reconcileUser(u, meta)
|
||||||
|
}
|
||||||
|
|
||||||
|
func createUser(username string, meta ConnectionMetadata) error {
|
||||||
|
args := []string{"-s", "/bin/bash"}
|
||||||
|
if meta.Homedir {
|
||||||
|
args = append(args, "-m")
|
||||||
|
} else {
|
||||||
|
args = append(args, "-M")
|
||||||
|
}
|
||||||
|
args = append(args, username)
|
||||||
|
cmd := exec.Command("useradd", args...)
|
||||||
|
if out, err := cmd.CombinedOutput(); err != nil {
|
||||||
|
return fmt.Errorf("useradd %s: %w (output: %s)", username, err, string(out))
|
||||||
|
}
|
||||||
|
logger.Info("auth-daemon: created user %s (homedir=%v)", username, meta.Homedir)
|
||||||
|
if meta.Sudo {
|
||||||
|
group := sudoGroup()
|
||||||
|
cmd := exec.Command("usermod", "-aG", group, username)
|
||||||
|
if out, err := cmd.CombinedOutput(); err != nil {
|
||||||
|
logger.Warn("auth-daemon: usermod -aG %s %s: %v (output: %s)", group, username, err, string(out))
|
||||||
|
} else {
|
||||||
|
logger.Info("auth-daemon: added %s to %s", username, group)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func mustAtoi(s string) int {
|
||||||
|
n, _ := strconv.Atoi(s)
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
func reconcileUser(u *user.User, meta ConnectionMetadata) error {
|
||||||
|
group := sudoGroup()
|
||||||
|
inGroup, err := userInGroup(u.Username, group)
|
||||||
|
if err != nil {
|
||||||
|
logger.Warn("auth-daemon: check group %s: %v", group, err)
|
||||||
|
inGroup = false
|
||||||
|
}
|
||||||
|
if meta.Sudo && !inGroup {
|
||||||
|
cmd := exec.Command("usermod", "-aG", group, u.Username)
|
||||||
|
if out, err := cmd.CombinedOutput(); err != nil {
|
||||||
|
logger.Warn("auth-daemon: usermod -aG %s %s: %v (output: %s)", group, u.Username, err, string(out))
|
||||||
|
} else {
|
||||||
|
logger.Info("auth-daemon: added %s to %s", u.Username, group)
|
||||||
|
}
|
||||||
|
} else if !meta.Sudo && inGroup {
|
||||||
|
cmd := exec.Command("gpasswd", "-d", u.Username, group)
|
||||||
|
if out, err := cmd.CombinedOutput(); err != nil {
|
||||||
|
logger.Warn("auth-daemon: gpasswd -d %s %s: %v (output: %s)", u.Username, group, err, string(out))
|
||||||
|
} else {
|
||||||
|
logger.Info("auth-daemon: removed %s from %s", u.Username, group)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if meta.Homedir && u.HomeDir != "" {
|
||||||
|
if st, err := os.Stat(u.HomeDir); err != nil || !st.IsDir() {
|
||||||
|
if err := os.MkdirAll(u.HomeDir, 0755); err != nil {
|
||||||
|
logger.Warn("auth-daemon: mkdir %s: %v", u.HomeDir, err)
|
||||||
|
} else {
|
||||||
|
uid, gid := mustAtoi(u.Uid), mustAtoi(u.Gid)
|
||||||
|
_ = os.Chown(u.HomeDir, uid, gid)
|
||||||
|
logger.Info("auth-daemon: created home %s for %s", u.HomeDir, u.Username)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func userInGroup(username, groupName string) (bool, error) {
|
||||||
|
// getent group wheel returns "wheel:x:10:user1,user2"
|
||||||
|
cmd := exec.Command("getent", "group", groupName)
|
||||||
|
out, err := cmd.Output()
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
parts := strings.SplitN(strings.TrimSpace(string(out)), ":", 4)
|
||||||
|
if len(parts) < 4 {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
members := strings.Split(parts[3], ",")
|
||||||
|
for _, m := range members {
|
||||||
|
if strings.TrimSpace(m) == username {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
22
authdaemon/host_stub.go
Normal file
22
authdaemon/host_stub.go
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
//go:build !linux
|
||||||
|
|
||||||
|
package authdaemon
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
var errLinuxOnly = fmt.Errorf("auth-daemon PAM agent is only supported on Linux")
|
||||||
|
|
||||||
|
// writeCACertIfNotExists returns an error on non-Linux.
|
||||||
|
func writeCACertIfNotExists(path, contents string, force bool) error {
|
||||||
|
return errLinuxOnly
|
||||||
|
}
|
||||||
|
|
||||||
|
// ensureUser returns an error on non-Linux.
|
||||||
|
func ensureUser(username string, meta ConnectionMetadata) error {
|
||||||
|
return errLinuxOnly
|
||||||
|
}
|
||||||
|
|
||||||
|
// writePrincipals returns an error on non-Linux.
|
||||||
|
func writePrincipals(path, username, niceId string) error {
|
||||||
|
return errLinuxOnly
|
||||||
|
}
|
||||||
28
authdaemon/principals.go
Normal file
28
authdaemon/principals.go
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
package authdaemon
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GetPrincipals reads the principals data file at path, looks up the given user, and returns that user's principals as a string slice.
|
||||||
|
// The file format is JSON: object with username keys and array-of-principals values, e.g. {"alice":["alice","usr-123"],"bob":["bob","usr-456"]}.
|
||||||
|
// If the user is not found or the file is missing, returns nil and nil.
|
||||||
|
func GetPrincipals(path, user string) ([]string, error) {
|
||||||
|
if path == "" {
|
||||||
|
return nil, fmt.Errorf("principals file path is required")
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("read principals file: %w", err)
|
||||||
|
}
|
||||||
|
var m map[string][]string
|
||||||
|
if err := json.Unmarshal(data, &m); err != nil {
|
||||||
|
return nil, fmt.Errorf("parse principals file: %w", err)
|
||||||
|
}
|
||||||
|
return m[user], nil
|
||||||
|
}
|
||||||
56
authdaemon/routes.go
Normal file
56
authdaemon/routes.go
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
package authdaemon
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
// registerRoutes registers all API routes. Add new endpoints here.
|
||||||
|
func (s *Server) registerRoutes() {
|
||||||
|
s.mux.HandleFunc("/health", s.handleHealth)
|
||||||
|
s.mux.HandleFunc("/connection", s.handleConnection)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConnectionMetadata is the metadata object in POST /connection.
|
||||||
|
type ConnectionMetadata struct {
|
||||||
|
Sudo bool `json:"sudo"`
|
||||||
|
Homedir bool `json:"homedir"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConnectionRequest is the JSON body for POST /connection.
|
||||||
|
type ConnectionRequest struct {
|
||||||
|
CaCert string `json:"caCert"`
|
||||||
|
NiceId string `json:"niceId"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
Metadata ConnectionMetadata `json:"metadata"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// healthResponse is the JSON body for GET /health.
|
||||||
|
type healthResponse struct {
|
||||||
|
Status string `json:"status"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleHealth responds with 200 and {"status":"ok"}.
|
||||||
|
func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodGet {
|
||||||
|
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_ = json.NewEncoder(w).Encode(healthResponse{Status: "ok"})
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleConnection accepts POST with connection payload and delegates to ProcessConnection.
|
||||||
|
func (s *Server) handleConnection(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodPost {
|
||||||
|
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var req ConnectionRequest
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
http.Error(w, "Bad Request", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.ProcessConnection(req)
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
}
|
||||||
179
authdaemon/server.go
Normal file
179
authdaemon/server.go
Normal file
@@ -0,0 +1,179 @@
|
|||||||
|
package authdaemon
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/ecdsa"
|
||||||
|
"crypto/elliptic"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/subtle"
|
||||||
|
"crypto/tls"
|
||||||
|
"crypto/x509"
|
||||||
|
"crypto/x509/pkix"
|
||||||
|
"encoding/pem"
|
||||||
|
"fmt"
|
||||||
|
"math/big"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/fosrl/newt/logger"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Config struct {
|
||||||
|
// DisableHTTPS: when true, Run() does not start the HTTPS server (for embedded use inside Newt). Call ProcessConnection directly for connection events.
|
||||||
|
DisableHTTPS bool
|
||||||
|
Port int // Required when DisableHTTPS is false. Listen port for the HTTPS server. No default.
|
||||||
|
PresharedKey string // Required when DisableHTTPS is false. HTTP auth (Authorization: Bearer <key> or X-Preshared-Key: <key>). No default.
|
||||||
|
CACertPath string // Required. Where to write the CA cert (e.g. /etc/ssh/ca.pem). No default.
|
||||||
|
Force bool // If true, overwrite existing CA cert (and other items) when content differs. Default false.
|
||||||
|
PrincipalsFilePath string // Required. Path to the principals data file (JSON: username -> array of principals). No default.
|
||||||
|
}
|
||||||
|
|
||||||
|
type Server struct {
|
||||||
|
cfg Config
|
||||||
|
addr string
|
||||||
|
presharedKey string
|
||||||
|
mux *http.ServeMux
|
||||||
|
tlsCert tls.Certificate
|
||||||
|
}
|
||||||
|
|
||||||
|
// generateTLSCert creates a self-signed certificate and key in memory (no disk).
|
||||||
|
func generateTLSCert() (tls.Certificate, error) {
|
||||||
|
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
return tls.Certificate{}, fmt.Errorf("generate key: %w", err)
|
||||||
|
}
|
||||||
|
serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
|
||||||
|
if err != nil {
|
||||||
|
return tls.Certificate{}, fmt.Errorf("serial: %w", err)
|
||||||
|
}
|
||||||
|
tmpl := &x509.Certificate{
|
||||||
|
SerialNumber: serial,
|
||||||
|
Subject: pkix.Name{
|
||||||
|
CommonName: "localhost",
|
||||||
|
},
|
||||||
|
NotBefore: time.Now(),
|
||||||
|
NotAfter: time.Now().Add(365 * 24 * time.Hour),
|
||||||
|
KeyUsage: x509.KeyUsageDigitalSignature,
|
||||||
|
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||||
|
BasicConstraintsValid: true,
|
||||||
|
DNSNames: []string{"localhost", "127.0.0.1"},
|
||||||
|
}
|
||||||
|
certDER, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, key.Public(), key)
|
||||||
|
if err != nil {
|
||||||
|
return tls.Certificate{}, fmt.Errorf("create certificate: %w", err)
|
||||||
|
}
|
||||||
|
keyDER, err := x509.MarshalECPrivateKey(key)
|
||||||
|
if err != nil {
|
||||||
|
return tls.Certificate{}, fmt.Errorf("marshal key: %w", err)
|
||||||
|
}
|
||||||
|
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
|
||||||
|
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER})
|
||||||
|
cert, err := tls.X509KeyPair(certPEM, keyPEM)
|
||||||
|
if err != nil {
|
||||||
|
return tls.Certificate{}, fmt.Errorf("x509 key pair: %w", err)
|
||||||
|
}
|
||||||
|
return cert, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// authMiddleware wraps next and requires a valid preshared key on every request.
|
||||||
|
// Accepts Authorization: Bearer <key> or X-Preshared-Key: <key>.
|
||||||
|
func (s *Server) authMiddleware(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
key := ""
|
||||||
|
if v := r.Header.Get("Authorization"); strings.HasPrefix(v, "Bearer ") {
|
||||||
|
key = strings.TrimSpace(strings.TrimPrefix(v, "Bearer "))
|
||||||
|
}
|
||||||
|
if key == "" {
|
||||||
|
key = strings.TrimSpace(r.Header.Get("X-Preshared-Key"))
|
||||||
|
}
|
||||||
|
if key == "" || subtle.ConstantTimeCompare([]byte(key), []byte(s.presharedKey)) != 1 {
|
||||||
|
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewServer builds a new auth-daemon server from cfg. Port, PresharedKey, CACertPath, and PrincipalsFilePath are required (no defaults).
|
||||||
|
func NewServer(cfg Config) (*Server, error) {
|
||||||
|
if runtime.GOOS != "linux" {
|
||||||
|
return nil, fmt.Errorf("auth-daemon is only supported on Linux, not %s", runtime.GOOS)
|
||||||
|
}
|
||||||
|
if !cfg.DisableHTTPS {
|
||||||
|
if cfg.Port <= 0 {
|
||||||
|
return nil, fmt.Errorf("port is required and must be positive")
|
||||||
|
}
|
||||||
|
if cfg.PresharedKey == "" {
|
||||||
|
return nil, fmt.Errorf("preshared key is required")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if cfg.CACertPath == "" {
|
||||||
|
return nil, fmt.Errorf("CACertPath is required")
|
||||||
|
}
|
||||||
|
if cfg.PrincipalsFilePath == "" {
|
||||||
|
return nil, fmt.Errorf("PrincipalsFilePath is required")
|
||||||
|
}
|
||||||
|
s := &Server{cfg: cfg}
|
||||||
|
if !cfg.DisableHTTPS {
|
||||||
|
cert, err := generateTLSCert()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
s.addr = fmt.Sprintf(":%d", cfg.Port)
|
||||||
|
s.presharedKey = cfg.PresharedKey
|
||||||
|
s.mux = http.NewServeMux()
|
||||||
|
s.tlsCert = cert
|
||||||
|
s.registerRoutes()
|
||||||
|
}
|
||||||
|
return s, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run starts the HTTPS server (unless DisableHTTPS) and blocks until ctx is cancelled or the server errors.
|
||||||
|
// When DisableHTTPS is true, Run() blocks on ctx only and does not listen; use ProcessConnection for connection events.
|
||||||
|
func (s *Server) Run(ctx context.Context) error {
|
||||||
|
if s.cfg.DisableHTTPS {
|
||||||
|
logger.Info("auth-daemon running (HTTPS disabled)")
|
||||||
|
<-ctx.Done()
|
||||||
|
s.cleanupPrincipalsFile()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
tcfg := &tls.Config{
|
||||||
|
Certificates: []tls.Certificate{s.tlsCert},
|
||||||
|
MinVersion: tls.VersionTLS12,
|
||||||
|
}
|
||||||
|
handler := s.authMiddleware(s.mux)
|
||||||
|
srv := &http.Server{
|
||||||
|
Addr: s.addr,
|
||||||
|
Handler: handler,
|
||||||
|
TLSConfig: tcfg,
|
||||||
|
ReadTimeout: 10 * time.Second,
|
||||||
|
WriteTimeout: 10 * time.Second,
|
||||||
|
ReadHeaderTimeout: 5 * time.Second,
|
||||||
|
IdleTimeout: 60 * time.Second,
|
||||||
|
}
|
||||||
|
go func() {
|
||||||
|
<-ctx.Done()
|
||||||
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if err := srv.Shutdown(shutdownCtx); err != nil {
|
||||||
|
logger.Warn("auth-daemon shutdown: %v", err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
logger.Info("auth-daemon listening on https://127.0.0.1%s", s.addr)
|
||||||
|
if err := srv.ListenAndServeTLS("", ""); err != nil && err != http.ErrServerClosed {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
s.cleanupPrincipalsFile()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) cleanupPrincipalsFile() {
|
||||||
|
if s.cfg.PrincipalsFilePath != "" {
|
||||||
|
if err := os.Remove(s.cfg.PrincipalsFilePath); err != nil && !os.IsNotExist(err) {
|
||||||
|
logger.Warn("auth-daemon: remove principals file: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,7 +4,7 @@ services:
|
|||||||
container_name: newt
|
container_name: newt
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
environment:
|
environment:
|
||||||
- PANGOLIN_ENDPOINT=https://example.com
|
- PANGOLIN_ENDPOINT=https://app.pangolin.net
|
||||||
- NEWT_ID=2ix2t8xk22ubpfy
|
- NEWT_ID=2ix2t8xk22ubpfy
|
||||||
- NEWT_SECRET=nnisrfsdfc7prqsp9ewo1dvtvci50j5uiqotez00dgap0ii2
|
- NEWT_SECRET=nnisrfsdfc7prqsp9ewo1dvtvci50j5uiqotez00dgap0ii2
|
||||||
- LOG_LEVEL=DEBUG
|
- LOG_LEVEL=DEBUG
|
||||||
321
main.go
321
main.go
@@ -1,7 +1,9 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"flag"
|
"flag"
|
||||||
@@ -11,12 +13,12 @@ import (
|
|||||||
"net/netip"
|
"net/netip"
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
"path/filepath"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"syscall"
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/fosrl/newt/authdaemon"
|
||||||
"github.com/fosrl/newt/docker"
|
"github.com/fosrl/newt/docker"
|
||||||
"github.com/fosrl/newt/healthcheck"
|
"github.com/fosrl/newt/healthcheck"
|
||||||
"github.com/fosrl/newt/logger"
|
"github.com/fosrl/newt/logger"
|
||||||
@@ -58,10 +60,6 @@ type ExitNodeData struct {
|
|||||||
ExitNodes []ExitNode `json:"exitNodes"`
|
ExitNodes []ExitNode `json:"exitNodes"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type SSHPublicKeyData struct {
|
|
||||||
PublicKey string `json:"publicKey"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// ExitNode represents an exit node with an ID, endpoint, and weight.
|
// ExitNode represents an exit node with an ID, endpoint, and weight.
|
||||||
type ExitNode struct {
|
type ExitNode struct {
|
||||||
ID int `json:"exitNodeId"`
|
ID int `json:"exitNodeId"`
|
||||||
@@ -134,6 +132,10 @@ var (
|
|||||||
preferEndpoint string
|
preferEndpoint string
|
||||||
healthMonitor *healthcheck.Monitor
|
healthMonitor *healthcheck.Monitor
|
||||||
enforceHealthcheckCert bool
|
enforceHealthcheckCert bool
|
||||||
|
authDaemonKey string
|
||||||
|
authDaemonPrincipalsFile string
|
||||||
|
authDaemonCACertPath string
|
||||||
|
authDaemonEnabled bool
|
||||||
// Build/version (can be overridden via -ldflags "-X main.newtVersion=...")
|
// Build/version (can be overridden via -ldflags "-X main.newtVersion=...")
|
||||||
newtVersion = "version_replaceme"
|
newtVersion = "version_replaceme"
|
||||||
|
|
||||||
@@ -156,6 +158,28 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
// Check for subcommands first (only principals exits early)
|
||||||
|
if len(os.Args) > 1 {
|
||||||
|
switch os.Args[1] {
|
||||||
|
case "auth-daemon":
|
||||||
|
// Run principals subcommand only if the next argument is "principals"
|
||||||
|
if len(os.Args) > 2 && os.Args[2] == "principals" {
|
||||||
|
runPrincipalsCmd(os.Args[3:])
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// auth-daemon subcommand without "principals" - show help
|
||||||
|
fmt.Println("Error: auth-daemon subcommand requires 'principals' argument")
|
||||||
|
fmt.Println()
|
||||||
|
fmt.Println("Usage:")
|
||||||
|
fmt.Println(" newt auth-daemon principals [options]")
|
||||||
|
fmt.Println()
|
||||||
|
|
||||||
|
// If not "principals", exit the switch to continue with normal execution
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Check if we're running as a Windows service
|
// Check if we're running as a Windows service
|
||||||
if isWindowsService() {
|
if isWindowsService() {
|
||||||
runService("NewtWireguardService", false, os.Args[1:])
|
runService("NewtWireguardService", false, os.Args[1:])
|
||||||
@@ -187,6 +211,10 @@ func runNewtMain(ctx context.Context) {
|
|||||||
updownScript = os.Getenv("UPDOWN_SCRIPT")
|
updownScript = os.Getenv("UPDOWN_SCRIPT")
|
||||||
interfaceName = os.Getenv("INTERFACE")
|
interfaceName = os.Getenv("INTERFACE")
|
||||||
portStr := os.Getenv("PORT")
|
portStr := os.Getenv("PORT")
|
||||||
|
authDaemonKey = os.Getenv("AD_KEY")
|
||||||
|
authDaemonPrincipalsFile = os.Getenv("AD_PRINCIPALS_FILE")
|
||||||
|
authDaemonCACertPath = os.Getenv("AD_CA_CERT_PATH")
|
||||||
|
authDaemonEnabledEnv := os.Getenv("AUTH_DAEMON_ENABLED")
|
||||||
|
|
||||||
// Metrics/observability env mirrors
|
// Metrics/observability env mirrors
|
||||||
metricsEnabledEnv := os.Getenv("NEWT_METRICS_PROMETHEUS_ENABLED")
|
metricsEnabledEnv := os.Getenv("NEWT_METRICS_PROMETHEUS_ENABLED")
|
||||||
@@ -279,10 +307,6 @@ func runNewtMain(ctx context.Context) {
|
|||||||
// load the prefer endpoint just as a flag
|
// load the prefer endpoint just as a flag
|
||||||
flag.StringVar(&preferEndpoint, "prefer-endpoint", "", "Prefer this endpoint for the connection (if set, will override the endpoint from the server)")
|
flag.StringVar(&preferEndpoint, "prefer-endpoint", "", "Prefer this endpoint for the connection (if set, will override the endpoint from the server)")
|
||||||
|
|
||||||
// if authorizedKeysFile == "" {
|
|
||||||
// flag.StringVar(&authorizedKeysFile, "authorized-keys-file", "~/.ssh/authorized_keys", "Path to authorized keys file (if unset, no keys will be authorized)")
|
|
||||||
// }
|
|
||||||
|
|
||||||
// Add new mTLS flags
|
// Add new mTLS flags
|
||||||
if tlsClientCert == "" {
|
if tlsClientCert == "" {
|
||||||
flag.StringVar(&tlsClientCert, "tls-client-cert-file", "", "Path to client certificate file (PEM/DER format)")
|
flag.StringVar(&tlsClientCert, "tls-client-cert-file", "", "Path to client certificate file (PEM/DER format)")
|
||||||
@@ -379,6 +403,24 @@ func runNewtMain(ctx context.Context) {
|
|||||||
region = regionEnv
|
region = regionEnv
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Auth daemon flags
|
||||||
|
if authDaemonKey == "" {
|
||||||
|
flag.StringVar(&authDaemonKey, "ad-pre-shared-key", "", "Pre-shared key for auth daemon authentication")
|
||||||
|
}
|
||||||
|
if authDaemonPrincipalsFile == "" {
|
||||||
|
flag.StringVar(&authDaemonPrincipalsFile, "ad-principals-file", "/var/run/auth-daemon/principals", "Path to the principals file for auth daemon")
|
||||||
|
}
|
||||||
|
if authDaemonCACertPath == "" {
|
||||||
|
flag.StringVar(&authDaemonCACertPath, "ad-ca-cert-path", "/etc/ssh/ca.pem", "Path to the CA certificate file for auth daemon")
|
||||||
|
}
|
||||||
|
if authDaemonEnabledEnv == "" {
|
||||||
|
flag.BoolVar(&authDaemonEnabled, "auth-daemon", false, "Enable auth daemon mode (runs alongside normal newt operation)")
|
||||||
|
} else {
|
||||||
|
if v, err := strconv.ParseBool(authDaemonEnabledEnv); err == nil {
|
||||||
|
authDaemonEnabled = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// do a --version check
|
// do a --version check
|
||||||
version := flag.Bool("version", false, "Print the version")
|
version := flag.Bool("version", false, "Print the version")
|
||||||
|
|
||||||
@@ -398,6 +440,13 @@ func runNewtMain(ctx context.Context) {
|
|||||||
|
|
||||||
logger.Init(nil)
|
logger.Init(nil)
|
||||||
loggerLevel := util.ParseLogLevel(logLevel)
|
loggerLevel := util.ParseLogLevel(logLevel)
|
||||||
|
|
||||||
|
// Start auth daemon if enabled
|
||||||
|
if authDaemonEnabled {
|
||||||
|
if err := startAuthDaemon(ctx); err != nil {
|
||||||
|
logger.Fatal("Failed to start auth daemon: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
logger.GetLogger().SetLevel(loggerLevel)
|
logger.GetLogger().SetLevel(loggerLevel)
|
||||||
|
|
||||||
// Initialize telemetry after flags are parsed (so flags override env)
|
// Initialize telemetry after flags are parsed (so flags override env)
|
||||||
@@ -694,8 +743,8 @@ func runNewtMain(ctx context.Context) {
|
|||||||
|
|
||||||
relayPort := wgData.RelayPort
|
relayPort := wgData.RelayPort
|
||||||
if relayPort == 0 {
|
if relayPort == 0 {
|
||||||
relayPort = 21820
|
relayPort = 21820
|
||||||
}
|
}
|
||||||
|
|
||||||
clientsHandleNewtConnection(wgData.PublicKey, endpoint, relayPort)
|
clientsHandleNewtConnection(wgData.PublicKey, endpoint, relayPort)
|
||||||
|
|
||||||
@@ -1168,94 +1217,6 @@ persistent_keepalive_interval=5`, util.FixKey(privateKey.String()), util.FixKey(
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
// EXPERIMENTAL: WHAT SHOULD WE DO ABOUT SECURITY?
|
|
||||||
client.RegisterHandler("newt/send/ssh/publicKey", func(msg websocket.WSMessage) {
|
|
||||||
logger.Debug("Received SSH public key request")
|
|
||||||
|
|
||||||
var sshPublicKeyData SSHPublicKeyData
|
|
||||||
|
|
||||||
jsonData, err := json.Marshal(msg.Data)
|
|
||||||
if err != nil {
|
|
||||||
logger.Info(fmtErrMarshaling, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err := json.Unmarshal(jsonData, &sshPublicKeyData); err != nil {
|
|
||||||
logger.Info("Error unmarshaling SSH public key data: %v", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
sshPublicKey := sshPublicKeyData.PublicKey
|
|
||||||
|
|
||||||
if authorizedKeysFile == "" {
|
|
||||||
logger.Debug("No authorized keys file set, skipping public key response")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Expand tilde to home directory if present
|
|
||||||
expandedPath := authorizedKeysFile
|
|
||||||
if strings.HasPrefix(authorizedKeysFile, "~/") {
|
|
||||||
homeDir, err := os.UserHomeDir()
|
|
||||||
if err != nil {
|
|
||||||
logger.Error("Failed to get user home directory: %v", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
expandedPath = filepath.Join(homeDir, authorizedKeysFile[2:])
|
|
||||||
}
|
|
||||||
|
|
||||||
// if it is set but the file does not exist, create it
|
|
||||||
if _, err := os.Stat(expandedPath); os.IsNotExist(err) {
|
|
||||||
logger.Debug("Authorized keys file does not exist, creating it: %s", expandedPath)
|
|
||||||
if err := os.MkdirAll(filepath.Dir(expandedPath), 0755); err != nil {
|
|
||||||
logger.Error("Failed to create directory for authorized keys file: %v", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if _, err := os.Create(expandedPath); err != nil {
|
|
||||||
logger.Error("Failed to create authorized keys file: %v", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if the public key already exists in the file
|
|
||||||
fileContent, err := os.ReadFile(expandedPath)
|
|
||||||
if err != nil {
|
|
||||||
logger.Error("Failed to read authorized keys file: %v", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if the key already exists (trim whitespace for comparison)
|
|
||||||
existingKeys := strings.Split(string(fileContent), "\n")
|
|
||||||
keyAlreadyExists := false
|
|
||||||
trimmedNewKey := strings.TrimSpace(sshPublicKey)
|
|
||||||
|
|
||||||
for _, existingKey := range existingKeys {
|
|
||||||
if strings.TrimSpace(existingKey) == trimmedNewKey && trimmedNewKey != "" {
|
|
||||||
keyAlreadyExists = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if keyAlreadyExists {
|
|
||||||
logger.Info("SSH public key already exists in authorized keys file, skipping")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// append the public key to the authorized keys file
|
|
||||||
logger.Debug("Appending public key to authorized keys file: %s", sshPublicKey)
|
|
||||||
file, err := os.OpenFile(expandedPath, os.O_APPEND|os.O_WRONLY, 0644)
|
|
||||||
if err != nil {
|
|
||||||
logger.Error("Failed to open authorized keys file: %v", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer file.Close()
|
|
||||||
|
|
||||||
if _, err := file.WriteString(sshPublicKey + "\n"); err != nil {
|
|
||||||
logger.Error("Failed to write public key to authorized keys file: %v", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.Info("SSH public key appended to authorized keys file")
|
|
||||||
})
|
|
||||||
|
|
||||||
// Register handler for adding health check targets
|
// Register handler for adding health check targets
|
||||||
client.RegisterHandler("newt/healthcheck/add", func(msg websocket.WSMessage) {
|
client.RegisterHandler("newt/healthcheck/add", func(msg websocket.WSMessage) {
|
||||||
logger.Debug("Received health check add request: %+v", msg)
|
logger.Debug("Received health check add request: %+v", msg)
|
||||||
@@ -1411,6 +1372,168 @@ persistent_keepalive_interval=5`, util.FixKey(privateKey.String()), util.FixKey(
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// Register handler for SSH certificate issued events
|
||||||
|
client.RegisterHandler("newt/pam/connection", func(msg websocket.WSMessage) {
|
||||||
|
logger.Debug("Received SSH certificate issued message")
|
||||||
|
|
||||||
|
// Define the structure of the incoming message
|
||||||
|
type SSHCertData struct {
|
||||||
|
MessageId int `json:"messageId"`
|
||||||
|
AgentPort int `json:"agentPort"`
|
||||||
|
AgentHost string `json:"agentHost"`
|
||||||
|
CACert string `json:"caCert"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
NiceID string `json:"niceId"`
|
||||||
|
Metadata struct {
|
||||||
|
Sudo bool `json:"sudo"`
|
||||||
|
Homedir bool `json:"homedir"`
|
||||||
|
} `json:"metadata"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var certData SSHCertData
|
||||||
|
jsonData, err := json.Marshal(msg.Data)
|
||||||
|
if err != nil {
|
||||||
|
logger.Error("Error marshaling SSH cert data: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// print the received data for debugging
|
||||||
|
logger.Debug("Received SSH cert data: %s", string(jsonData))
|
||||||
|
|
||||||
|
if err := json.Unmarshal(jsonData, &certData); err != nil {
|
||||||
|
logger.Error("Error unmarshaling SSH cert data: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if we're running the auth daemon internally
|
||||||
|
if authDaemonServer != nil {
|
||||||
|
// Call ProcessConnection directly when running internally
|
||||||
|
logger.Debug("Calling internal auth daemon ProcessConnection for user %s", certData.Username)
|
||||||
|
|
||||||
|
authDaemonServer.ProcessConnection(authdaemon.ConnectionRequest{
|
||||||
|
CaCert: certData.CACert,
|
||||||
|
NiceId: certData.NiceID,
|
||||||
|
Username: certData.Username,
|
||||||
|
Metadata: authdaemon.ConnectionMetadata{
|
||||||
|
Sudo: certData.Metadata.Sudo,
|
||||||
|
Homedir: certData.Metadata.Homedir,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// Send success response back to cloud
|
||||||
|
err = client.SendMessage("ws/round-trip/complete", map[string]interface{}{
|
||||||
|
"messageId": certData.MessageId,
|
||||||
|
"complete": true,
|
||||||
|
})
|
||||||
|
|
||||||
|
logger.Info("Successfully processed connection via internal auth daemon for user %s", certData.Username)
|
||||||
|
} else {
|
||||||
|
// External auth daemon mode - make HTTP request
|
||||||
|
// Check if auth daemon key is configured
|
||||||
|
if authDaemonKey == "" {
|
||||||
|
logger.Error("Auth daemon key not configured, cannot communicate with daemon")
|
||||||
|
// Send failure response back to cloud
|
||||||
|
err := client.SendMessage("ws/round-trip/complete", map[string]interface{}{
|
||||||
|
"messageId": certData.MessageId,
|
||||||
|
"complete": true,
|
||||||
|
"error": "auth daemon key not configured",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
logger.Error("Failed to send SSH cert failure response: %v", err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prepare the request body for the auth daemon
|
||||||
|
requestBody := map[string]interface{}{
|
||||||
|
"caCert": certData.CACert,
|
||||||
|
"niceId": certData.NiceID,
|
||||||
|
"username": certData.Username,
|
||||||
|
"metadata": map[string]interface{}{
|
||||||
|
"sudo": certData.Metadata.Sudo,
|
||||||
|
"homedir": certData.Metadata.Homedir,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
requestJSON, err := json.Marshal(requestBody)
|
||||||
|
if err != nil {
|
||||||
|
logger.Error("Failed to marshal auth daemon request: %v", err)
|
||||||
|
// Send failure response
|
||||||
|
client.SendMessage("ws/round-trip/complete", map[string]interface{}{
|
||||||
|
"messageId": certData.MessageId,
|
||||||
|
"complete": true,
|
||||||
|
"error": fmt.Sprintf("failed to marshal request: %v", err),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create HTTPS client that skips certificate verification
|
||||||
|
// (auth daemon uses self-signed cert)
|
||||||
|
httpClient := &http.Client{
|
||||||
|
Transport: &http.Transport{
|
||||||
|
TLSClientConfig: &tls.Config{
|
||||||
|
InsecureSkipVerify: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Timeout: 10 * time.Second,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Make the request to the auth daemon
|
||||||
|
url := fmt.Sprintf("https://%s:%d/connection", certData.AgentHost, certData.AgentPort)
|
||||||
|
req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestJSON))
|
||||||
|
if err != nil {
|
||||||
|
logger.Error("Failed to create auth daemon request: %v", err)
|
||||||
|
client.SendMessage("ws/round-trip/complete", map[string]interface{}{
|
||||||
|
"messageId": certData.MessageId,
|
||||||
|
"complete": true,
|
||||||
|
"error": fmt.Sprintf("failed to create request: %v", err),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set headers
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
req.Header.Set("Authorization", "Bearer "+authDaemonKey)
|
||||||
|
|
||||||
|
logger.Debug("Sending SSH cert to auth daemon at %s", url)
|
||||||
|
|
||||||
|
// Send the request
|
||||||
|
resp, err := httpClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
logger.Error("Failed to connect to auth daemon: %v", err)
|
||||||
|
client.SendMessage("ws/round-trip/complete", map[string]interface{}{
|
||||||
|
"messageId": certData.MessageId,
|
||||||
|
"complete": true,
|
||||||
|
"error": fmt.Sprintf("failed to connect to auth daemon: %v", err),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
// Check response status
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
logger.Error("Auth daemon returned non-OK status: %d", resp.StatusCode)
|
||||||
|
client.SendMessage("ws/round-trip/complete", map[string]interface{}{
|
||||||
|
"messageId": certData.MessageId,
|
||||||
|
"complete": true,
|
||||||
|
"error": fmt.Sprintf("auth daemon returned status %d", resp.StatusCode),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.Info("Successfully registered SSH certificate with external auth daemon for user %s", certData.Username)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send success response back to cloud
|
||||||
|
err = client.SendMessage("ws/round-trip/complete", map[string]interface{}{
|
||||||
|
"messageId": certData.MessageId,
|
||||||
|
"complete": true,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
logger.Error("Failed to send SSH cert success response: %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
client.OnConnect(func() error {
|
client.OnConnect(func() error {
|
||||||
publicKey = privateKey.PublicKey()
|
publicKey = privateKey.PublicKey()
|
||||||
logger.Debug("Public key: %s", publicKey)
|
logger.Debug("Public key: %s", publicKey)
|
||||||
|
|||||||
11
scripts/nfpm.yaml.tmpl
Normal file
11
scripts/nfpm.yaml.tmpl
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
name: __PKG_NAME__
|
||||||
|
arch: __ARCH__
|
||||||
|
platform: linux
|
||||||
|
version: __VERSION__
|
||||||
|
section: net
|
||||||
|
priority: optional
|
||||||
|
maintainer: fosrl
|
||||||
|
description: Newt - userspace tunnel client and TCP/UDP proxy
|
||||||
|
contents:
|
||||||
|
- src: build/newt
|
||||||
|
dst: /usr/bin/newt
|
||||||
139
scripts/publish-apt.sh
Normal file
139
scripts/publish-apt.sh
Normal file
@@ -0,0 +1,139 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
# ---- required env ----
|
||||||
|
: "${GH_REPO:?}"
|
||||||
|
: "${S3_BUCKET:?}"
|
||||||
|
: "${AWS_REGION:?}"
|
||||||
|
: "${CLOUDFRONT_DISTRIBUTION_ID:?}"
|
||||||
|
: "${PKG_NAME:?}"
|
||||||
|
: "${SUITE:?}"
|
||||||
|
: "${COMPONENT:?}"
|
||||||
|
: "${APT_GPG_PRIVATE_KEY:?}"
|
||||||
|
|
||||||
|
S3_PREFIX="${S3_PREFIX:-}"
|
||||||
|
if [[ -n "${S3_PREFIX}" && "${S3_PREFIX}" != */ ]]; then
|
||||||
|
S3_PREFIX="${S3_PREFIX}/"
|
||||||
|
fi
|
||||||
|
|
||||||
|
WORKDIR="$(pwd)"
|
||||||
|
mkdir -p repo/apt assets build
|
||||||
|
|
||||||
|
echo "${APT_GPG_PRIVATE_KEY}" | gpg --batch --import >/dev/null 2>&1 || true
|
||||||
|
|
||||||
|
KEYID="$(gpg --list-secret-keys --with-colons | awk -F: '$1=="sec"{print $5; exit}')"
|
||||||
|
if [[ -z "${KEYID}" ]]; then
|
||||||
|
echo "ERROR: No GPG secret key available after import."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Determine which tags to process
|
||||||
|
TAGS=""
|
||||||
|
if [[ "${BACKFILL_ALL:-false}" == "true" ]]; then
|
||||||
|
echo "Backfill mode: collecting all release tags..."
|
||||||
|
TAGS="$(gh release list -R "${GH_REPO}" --limit 200 --json tagName --jq '.[].tagName')"
|
||||||
|
else
|
||||||
|
if [[ -n "${INPUT_TAG:-}" ]]; then
|
||||||
|
TAGS="${INPUT_TAG}"
|
||||||
|
elif [[ -n "${EVENT_TAG:-}" ]]; then
|
||||||
|
TAGS="${EVENT_TAG}"
|
||||||
|
else
|
||||||
|
echo "No tag provided; using latest release tag..."
|
||||||
|
TAGS="$(gh release view -R "${GH_REPO}" --json tagName --jq '.tagName')"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "Tags to process:"
|
||||||
|
printf '%s\n' "${TAGS}"
|
||||||
|
|
||||||
|
# Pull existing repo from S3 so we keep older versions
|
||||||
|
echo "Sync existing repo from S3..."
|
||||||
|
aws s3 sync "s3://${S3_BUCKET}/${S3_PREFIX}apt/" repo/apt/ >/dev/null 2>&1 || true
|
||||||
|
|
||||||
|
# Build and add packages
|
||||||
|
while IFS= read -r TAG; do
|
||||||
|
[[ -z "${TAG}" ]] && continue
|
||||||
|
echo "=== Processing tag: ${TAG} ==="
|
||||||
|
|
||||||
|
rm -rf assets build
|
||||||
|
mkdir -p assets build
|
||||||
|
|
||||||
|
gh release download "${TAG}" -R "${GH_REPO}" -p "newt_linux_amd64" -D assets
|
||||||
|
gh release download "${TAG}" -R "${GH_REPO}" -p "newt_linux_arm64" -D assets
|
||||||
|
|
||||||
|
VERSION="${TAG#v}"
|
||||||
|
|
||||||
|
for arch in amd64 arm64; do
|
||||||
|
bin="assets/newt_linux_${arch}"
|
||||||
|
if [[ ! -f "${bin}" ]]; then
|
||||||
|
echo "ERROR: Missing release asset: ${bin}"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
install -Dm755 "${bin}" "build/newt"
|
||||||
|
|
||||||
|
# Create nfpm config from template file (no heredoc here)
|
||||||
|
sed \
|
||||||
|
-e "s/__PKG_NAME__/${PKG_NAME}/g" \
|
||||||
|
-e "s/__ARCH__/${arch}/g" \
|
||||||
|
-e "s/__VERSION__/${VERSION}/g" \
|
||||||
|
scripts/nfpm.yaml.tmpl > nfpm.yaml
|
||||||
|
|
||||||
|
nfpm package -p deb -f nfpm.yaml -t "build/${PKG_NAME}_${VERSION}_${arch}.deb"
|
||||||
|
done
|
||||||
|
|
||||||
|
mkdir -p "repo/apt/pool/${COMPONENT}/${PKG_NAME:0:1}/${PKG_NAME}/"
|
||||||
|
cp -v build/*.deb "repo/apt/pool/${COMPONENT}/${PKG_NAME:0:1}/${PKG_NAME}/"
|
||||||
|
|
||||||
|
done <<< "${TAGS}"
|
||||||
|
|
||||||
|
# Regenerate metadata
|
||||||
|
cd repo/apt
|
||||||
|
|
||||||
|
for arch in amd64 arm64; do
|
||||||
|
mkdir -p "dists/${SUITE}/${COMPONENT}/binary-${arch}"
|
||||||
|
dpkg-scanpackages -a "${arch}" pool > "dists/${SUITE}/${COMPONENT}/binary-${arch}/Packages"
|
||||||
|
gzip -fk "dists/${SUITE}/${COMPONENT}/binary-${arch}/Packages"
|
||||||
|
done
|
||||||
|
|
||||||
|
# Release file with hashes
|
||||||
|
cat > apt-ftparchive.conf <<EOF
|
||||||
|
APT::FTPArchive::Release::Origin "fosrl";
|
||||||
|
APT::FTPArchive::Release::Label "newt";
|
||||||
|
APT::FTPArchive::Release::Suite "${SUITE}";
|
||||||
|
APT::FTPArchive::Release::Codename "${SUITE}";
|
||||||
|
APT::FTPArchive::Release::Architectures "amd64 arm64";
|
||||||
|
APT::FTPArchive::Release::Components "${COMPONENT}";
|
||||||
|
APT::FTPArchive::Release::Description "Newt APT repository";
|
||||||
|
EOF
|
||||||
|
|
||||||
|
apt-ftparchive -c apt-ftparchive.conf release "dists/${SUITE}" > "dists/${SUITE}/Release"
|
||||||
|
|
||||||
|
# Sign Release
|
||||||
|
cd "dists/${SUITE}"
|
||||||
|
|
||||||
|
gpg --batch --yes --pinentry-mode loopback \
|
||||||
|
${APT_GPG_PASSPHRASE:+--passphrase "${APT_GPG_PASSPHRASE}"} \
|
||||||
|
--local-user "${KEYID}" \
|
||||||
|
--clearsign -o InRelease Release
|
||||||
|
|
||||||
|
gpg --batch --yes --pinentry-mode loopback \
|
||||||
|
${APT_GPG_PASSPHRASE:+--passphrase "${APT_GPG_PASSPHRASE}"} \
|
||||||
|
--local-user "${KEYID}" \
|
||||||
|
-abs -o Release.gpg Release
|
||||||
|
|
||||||
|
# Export public key into apt repo root
|
||||||
|
cd ../../..
|
||||||
|
gpg --batch --yes --armor --export "${KEYID}" > public.key
|
||||||
|
|
||||||
|
# Upload to S3
|
||||||
|
echo "Uploading to S3..."
|
||||||
|
aws s3 sync "${WORKDIR}/repo/apt" "s3://${S3_BUCKET}/${S3_PREFIX}apt/" --delete
|
||||||
|
|
||||||
|
# Invalidate metadata
|
||||||
|
echo "CloudFront invalidation..."
|
||||||
|
aws cloudfront create-invalidation \
|
||||||
|
--distribution-id "${CLOUDFRONT_DISTRIBUTION_ID}" \
|
||||||
|
--paths "/${S3_PREFIX}apt/dists/*" "/${S3_PREFIX}apt/public.key"
|
||||||
|
|
||||||
|
echo "Done. Repo base: ${REPO_BASE_URL}"
|
||||||
Reference in New Issue
Block a user