mirror of
https://github.com/fosrl/newt.git
synced 2026-03-13 10:24:03 -05:00
Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0f6852b681 | ||
|
|
2b8e280f2e | ||
|
|
3a377d43de | ||
|
|
792057cf6c | ||
|
|
57afe91e85 | ||
|
|
3389088c43 | ||
|
|
e73150c187 | ||
|
|
18556f34b2 | ||
|
|
66c235624a |
24
.github/workflows/cicd.yml
vendored
24
.github/workflows/cicd.yml
vendored
@@ -589,15 +589,23 @@ jobs:
|
||||
# sarif_file: trivy-ghcr.sarif
|
||||
# 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:
|
||||
CGO_ENABLED: "0"
|
||||
GOFLAGS: "-trimpath"
|
||||
run: |
|
||||
set -euo pipefail
|
||||
TAG_VAR="${TAG}"
|
||||
make -j 10 go-build-release tag=$TAG_VAR
|
||||
shell: bash
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Create GitHub Release
|
||||
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
|
||||
@@ -46,12 +46,11 @@ func startAuthDaemon(ctx context.Context) error {
|
||||
|
||||
// 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,
|
||||
GenerateRandomPassword: authDaemonGenerateRandomPassword,
|
||||
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)
|
||||
@@ -73,6 +72,8 @@ func startAuthDaemon(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
|
||||
// runPrincipalsCmd executes the principals subcommand logic
|
||||
func runPrincipalsCmd(args []string) {
|
||||
opts := struct {
|
||||
@@ -147,4 +148,4 @@ Example:
|
||||
newt principals --username alice
|
||||
|
||||
`, defaultPrincipalsPath)
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,8 @@ import (
|
||||
// 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.sudoMode=%q metadata.sudoCommands=%v metadata.homedir=%v metadata.groups=%v",
|
||||
req.NiceId, req.Username, req.Metadata.SudoMode, req.Metadata.SudoCommands, req.Metadata.Homedir, req.Metadata.Groups)
|
||||
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 != "" {
|
||||
@@ -16,7 +16,7 @@ func (s *Server) ProcessConnection(req ConnectionRequest) {
|
||||
logger.Warn("auth-daemon: write CA cert: %v", err)
|
||||
}
|
||||
}
|
||||
if err := ensureUser(req.Username, req.Metadata, s.cfg.GenerateRandomPassword); err != nil {
|
||||
if err := ensureUser(req.Username, req.Metadata); err != nil {
|
||||
logger.Warn("auth-daemon: ensure user: %v", err)
|
||||
}
|
||||
if cfg.PrincipalsFilePath != "" {
|
||||
|
||||
@@ -4,8 +4,6 @@ package authdaemon
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
@@ -124,73 +122,8 @@ func sudoGroup() string {
|
||||
return "sudo"
|
||||
}
|
||||
|
||||
// setRandomPassword generates a random password and sets it for username via chpasswd.
|
||||
// Used when GenerateRandomPassword is true so SSH with PermitEmptyPasswords no can accept the user.
|
||||
func setRandomPassword(username string) error {
|
||||
b := make([]byte, 16)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return fmt.Errorf("generate password: %w", err)
|
||||
}
|
||||
password := hex.EncodeToString(b)
|
||||
cmd := exec.Command("chpasswd")
|
||||
cmd.Stdin = strings.NewReader(username + ":" + password)
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
return fmt.Errorf("chpasswd: %w (output: %s)", err, string(out))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
const skelDir = "/etc/skel"
|
||||
|
||||
// copySkelInto copies files from srcDir (e.g. /etc/skel) into dstDir (e.g. user's home).
|
||||
// Only creates files that don't already exist. All created paths are chowned to uid:gid.
|
||||
func copySkelInto(srcDir, dstDir string, uid, gid int) {
|
||||
entries, err := os.ReadDir(srcDir)
|
||||
if err != nil {
|
||||
if !os.IsNotExist(err) {
|
||||
logger.Warn("auth-daemon: read %s: %v", srcDir, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
for _, e := range entries {
|
||||
name := e.Name()
|
||||
src := filepath.Join(srcDir, name)
|
||||
dst := filepath.Join(dstDir, name)
|
||||
if e.IsDir() {
|
||||
if st, err := os.Stat(dst); err == nil && st.IsDir() {
|
||||
copySkelInto(src, dst, uid, gid)
|
||||
continue
|
||||
}
|
||||
if err := os.MkdirAll(dst, 0755); err != nil {
|
||||
logger.Warn("auth-daemon: mkdir %s: %v", dst, err)
|
||||
continue
|
||||
}
|
||||
if err := os.Chown(dst, uid, gid); err != nil {
|
||||
logger.Warn("auth-daemon: chown %s: %v", dst, err)
|
||||
}
|
||||
copySkelInto(src, dst, uid, gid)
|
||||
continue
|
||||
}
|
||||
if _, err := os.Stat(dst); err == nil {
|
||||
continue
|
||||
}
|
||||
data, err := os.ReadFile(src)
|
||||
if err != nil {
|
||||
logger.Warn("auth-daemon: read %s: %v", src, err)
|
||||
continue
|
||||
}
|
||||
if err := os.WriteFile(dst, data, 0644); err != nil {
|
||||
logger.Warn("auth-daemon: write %s: %v", dst, err)
|
||||
continue
|
||||
}
|
||||
if err := os.Chown(dst, uid, gid); err != nil {
|
||||
logger.Warn("auth-daemon: chown %s: %v", dst, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ensureUser creates the system user if missing, or reconciles sudo and homedir to match meta.
|
||||
func ensureUser(username string, meta ConnectionMetadata, generateRandomPassword bool) error {
|
||||
func ensureUser(username string, meta ConnectionMetadata) error {
|
||||
if username == "" {
|
||||
return nil
|
||||
}
|
||||
@@ -199,49 +132,12 @@ func ensureUser(username string, meta ConnectionMetadata, generateRandomPassword
|
||||
if _, ok := err.(user.UnknownUserError); !ok {
|
||||
return fmt.Errorf("lookup user %s: %w", username, err)
|
||||
}
|
||||
return createUser(username, meta, generateRandomPassword)
|
||||
return createUser(username, meta)
|
||||
}
|
||||
return reconcileUser(u, meta)
|
||||
}
|
||||
|
||||
// desiredGroups returns the exact list of supplementary groups the user should have:
|
||||
// meta.Groups plus the sudo group when meta.SudoMode is "full" (deduped).
|
||||
func desiredGroups(meta ConnectionMetadata) []string {
|
||||
seen := make(map[string]struct{})
|
||||
var out []string
|
||||
for _, g := range meta.Groups {
|
||||
g = strings.TrimSpace(g)
|
||||
if g == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[g]; ok {
|
||||
continue
|
||||
}
|
||||
seen[g] = struct{}{}
|
||||
out = append(out, g)
|
||||
}
|
||||
if meta.SudoMode == "full" {
|
||||
sg := sudoGroup()
|
||||
if _, ok := seen[sg]; !ok {
|
||||
out = append(out, sg)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// setUserGroups sets the user's supplementary groups to exactly groups (local mirrors metadata).
|
||||
// When groups is empty, clears all supplementary groups (usermod -G "").
|
||||
func setUserGroups(username string, groups []string) {
|
||||
list := strings.Join(groups, ",")
|
||||
cmd := exec.Command("usermod", "-G", list, username)
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
logger.Warn("auth-daemon: usermod -G %s: %v (output: %s)", list, err, string(out))
|
||||
} else {
|
||||
logger.Info("auth-daemon: set %s supplementary groups to %s", username, list)
|
||||
}
|
||||
}
|
||||
|
||||
func createUser(username string, meta ConnectionMetadata, generateRandomPassword bool) error {
|
||||
func createUser(username string, meta ConnectionMetadata) error {
|
||||
args := []string{"-s", "/bin/bash"}
|
||||
if meta.Homedir {
|
||||
args = append(args, "-m")
|
||||
@@ -254,143 +150,75 @@ func createUser(username string, meta ConnectionMetadata, generateRandomPassword
|
||||
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 generateRandomPassword {
|
||||
if err := setRandomPassword(username); err != nil {
|
||||
logger.Warn("auth-daemon: set random password for %s: %v", username, err)
|
||||
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: set random password for %s (PermitEmptyPasswords no)", username)
|
||||
logger.Info("auth-daemon: added %s to %s", username, group)
|
||||
}
|
||||
}
|
||||
if meta.Homedir {
|
||||
if u, err := user.Lookup(username); err == nil && u.HomeDir != "" {
|
||||
uid, gid := mustAtoi(u.Uid), mustAtoi(u.Gid)
|
||||
copySkelInto(skelDir, u.HomeDir, uid, gid)
|
||||
}
|
||||
}
|
||||
setUserGroups(username, desiredGroups(meta))
|
||||
switch meta.SudoMode {
|
||||
case "full":
|
||||
if err := configurePasswordlessSudo(username); err != nil {
|
||||
logger.Warn("auth-daemon: configure passwordless sudo for %s: %v", username, err)
|
||||
}
|
||||
case "commands":
|
||||
if len(meta.SudoCommands) > 0 {
|
||||
if err := configureSudoCommands(username, meta.SudoCommands); err != nil {
|
||||
logger.Warn("auth-daemon: configure sudo commands for %s: %v", username, err)
|
||||
}
|
||||
}
|
||||
default:
|
||||
removeSudoers(username)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
const sudoersFilePrefix = "90-pangolin-"
|
||||
|
||||
func sudoersPath(username string) string {
|
||||
return filepath.Join("/etc/sudoers.d", sudoersFilePrefix+username)
|
||||
}
|
||||
|
||||
// writeSudoersFile writes content to the user's sudoers.d file and validates with visudo.
|
||||
func writeSudoersFile(username, content string) error {
|
||||
sudoersFile := sudoersPath(username)
|
||||
tmpFile := sudoersFile + ".tmp"
|
||||
if err := os.WriteFile(tmpFile, []byte(content), 0440); err != nil {
|
||||
return fmt.Errorf("write temp sudoers file: %w", err)
|
||||
}
|
||||
cmd := exec.Command("visudo", "-c", "-f", tmpFile)
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
os.Remove(tmpFile)
|
||||
return fmt.Errorf("visudo validation failed: %w (output: %s)", err, string(out))
|
||||
}
|
||||
if err := os.Rename(tmpFile, sudoersFile); err != nil {
|
||||
os.Remove(tmpFile)
|
||||
return fmt.Errorf("move sudoers file: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// configurePasswordlessSudo creates a sudoers.d file to allow passwordless sudo for the user.
|
||||
func configurePasswordlessSudo(username string) error {
|
||||
content := fmt.Sprintf("# Created by Pangolin auth-daemon\n%s ALL=(ALL) NOPASSWD:ALL\n", username)
|
||||
if err := writeSudoersFile(username, content); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Info("auth-daemon: configured passwordless sudo for %s", username)
|
||||
return nil
|
||||
}
|
||||
|
||||
// configureSudoCommands creates a sudoers.d file allowing only the listed commands (NOPASSWD).
|
||||
// Each command should be a full path (e.g. /usr/bin/systemctl).
|
||||
func configureSudoCommands(username string, commands []string) error {
|
||||
var b strings.Builder
|
||||
b.WriteString("# Created by Pangolin auth-daemon (restricted commands)\n")
|
||||
n := 0
|
||||
for _, c := range commands {
|
||||
c = strings.TrimSpace(c)
|
||||
if c == "" {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(&b, "%s ALL=(ALL) NOPASSWD: %s\n", username, c)
|
||||
n++
|
||||
}
|
||||
if n == 0 {
|
||||
return fmt.Errorf("no valid sudo commands")
|
||||
}
|
||||
if err := writeSudoersFile(username, b.String()); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Info("auth-daemon: configured restricted sudo for %s (%d commands)", username, len(commands))
|
||||
return nil
|
||||
}
|
||||
|
||||
// removeSudoers removes the sudoers.d file for the user.
|
||||
func removeSudoers(username string) {
|
||||
sudoersFile := sudoersPath(username)
|
||||
if err := os.Remove(sudoersFile); err != nil && !os.IsNotExist(err) {
|
||||
logger.Warn("auth-daemon: remove sudoers for %s: %v", username, err)
|
||||
} else if err == nil {
|
||||
logger.Info("auth-daemon: removed sudoers for %s", username)
|
||||
}
|
||||
}
|
||||
|
||||
func mustAtoi(s string) int {
|
||||
n, _ := strconv.Atoi(s)
|
||||
return n
|
||||
}
|
||||
|
||||
func reconcileUser(u *user.User, meta ConnectionMetadata) error {
|
||||
setUserGroups(u.Username, desiredGroups(meta))
|
||||
switch meta.SudoMode {
|
||||
case "full":
|
||||
if err := configurePasswordlessSudo(u.Username); err != nil {
|
||||
logger.Warn("auth-daemon: configure passwordless sudo for %s: %v", u.Username, err)
|
||||
}
|
||||
case "commands":
|
||||
if len(meta.SudoCommands) > 0 {
|
||||
if err := configureSudoCommands(u.Username, meta.SudoCommands); err != nil {
|
||||
logger.Warn("auth-daemon: configure sudo commands for %s: %v", u.Username, err)
|
||||
}
|
||||
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 {
|
||||
removeSudoers(u.Username)
|
||||
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)
|
||||
}
|
||||
default:
|
||||
removeSudoers(u.Username)
|
||||
}
|
||||
if meta.Homedir && u.HomeDir != "" {
|
||||
uid, gid := mustAtoi(u.Uid), mustAtoi(u.Gid)
|
||||
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)
|
||||
copySkelInto(skelDir, u.HomeDir, uid, gid)
|
||||
logger.Info("auth-daemon: created home %s for %s", u.HomeDir, u.Username)
|
||||
}
|
||||
} else {
|
||||
// Ensure .bashrc etc. exist (e.g. home existed but was empty or skel was minimal)
|
||||
copySkelInto(skelDir, u.HomeDir, uid, gid)
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ func writeCACertIfNotExists(path, contents string, force bool) error {
|
||||
}
|
||||
|
||||
// ensureUser returns an error on non-Linux.
|
||||
func ensureUser(username string, meta ConnectionMetadata, generateRandomPassword bool) error {
|
||||
func ensureUser(username string, meta ConnectionMetadata) error {
|
||||
return errLinuxOnly
|
||||
}
|
||||
|
||||
|
||||
@@ -13,10 +13,8 @@ func (s *Server) registerRoutes() {
|
||||
|
||||
// ConnectionMetadata is the metadata object in POST /connection.
|
||||
type ConnectionMetadata struct {
|
||||
SudoMode string `json:"sudoMode"` // "none" | "full" | "commands"
|
||||
SudoCommands []string `json:"sudoCommands"` // used when sudoMode is "commands"
|
||||
Homedir bool `json:"homedir"`
|
||||
Groups []string `json:"groups"` // system groups to add the user to
|
||||
Sudo bool `json:"sudo"`
|
||||
Homedir bool `json:"homedir"`
|
||||
}
|
||||
|
||||
// ConnectionRequest is the JSON body for POST /connection.
|
||||
|
||||
@@ -27,9 +27,8 @@ type Config struct {
|
||||
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.
|
||||
GenerateRandomPassword bool // If true, set a random password on users when they are provisioned (for SSH PermitEmptyPasswords no).
|
||||
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 {
|
||||
|
||||
47
main.go
47
main.go
@@ -116,7 +116,6 @@ var (
|
||||
logLevel string
|
||||
interfaceName string
|
||||
port uint16
|
||||
portStr string
|
||||
disableClients bool
|
||||
updownScript string
|
||||
dockerSocket string
|
||||
@@ -137,7 +136,6 @@ var (
|
||||
authDaemonPrincipalsFile string
|
||||
authDaemonCACertPath string
|
||||
authDaemonEnabled bool
|
||||
authDaemonGenerateRandomPassword bool
|
||||
// Build/version (can be overridden via -ldflags "-X main.newtVersion=...")
|
||||
newtVersion = "version_replaceme"
|
||||
|
||||
@@ -212,12 +210,11 @@ func runNewtMain(ctx context.Context) {
|
||||
logLevel = os.Getenv("LOG_LEVEL")
|
||||
updownScript = os.Getenv("UPDOWN_SCRIPT")
|
||||
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")
|
||||
authDaemonGenerateRandomPasswordEnv := os.Getenv("AD_GENERATE_RANDOM_PASSWORD")
|
||||
|
||||
// Metrics/observability env mirrors
|
||||
metricsEnabledEnv := os.Getenv("NEWT_METRICS_PROMETHEUS_ENABLED")
|
||||
@@ -423,13 +420,6 @@ func runNewtMain(ctx context.Context) {
|
||||
authDaemonEnabled = v
|
||||
}
|
||||
}
|
||||
if authDaemonGenerateRandomPasswordEnv == "" {
|
||||
flag.BoolVar(&authDaemonGenerateRandomPassword, "ad-generate-random-password", false, "Generate a random password for authenticated users")
|
||||
} else {
|
||||
if v, err := strconv.ParseBool(authDaemonGenerateRandomPasswordEnv); err == nil {
|
||||
authDaemonGenerateRandomPassword = v
|
||||
}
|
||||
}
|
||||
|
||||
// do a --version check
|
||||
version := flag.Bool("version", false, "Print the version")
|
||||
@@ -1388,18 +1378,15 @@ persistent_keepalive_interval=5`, util.FixKey(privateKey.String()), util.FixKey(
|
||||
|
||||
// Define the structure of the incoming message
|
||||
type SSHCertData struct {
|
||||
MessageId int `json:"messageId"`
|
||||
AgentPort int `json:"agentPort"`
|
||||
AgentHost string `json:"agentHost"`
|
||||
ExternalAuthDaemon bool `json:"externalAuthDaemon"`
|
||||
CACert string `json:"caCert"`
|
||||
Username string `json:"username"`
|
||||
NiceID string `json:"niceId"`
|
||||
Metadata struct {
|
||||
SudoMode string `json:"sudoMode"`
|
||||
SudoCommands []string `json:"sudoCommands"`
|
||||
Homedir bool `json:"homedir"`
|
||||
Groups []string `json:"groups"`
|
||||
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"`
|
||||
}
|
||||
|
||||
@@ -1419,7 +1406,7 @@ persistent_keepalive_interval=5`, util.FixKey(privateKey.String()), util.FixKey(
|
||||
}
|
||||
|
||||
// Check if we're running the auth daemon internally
|
||||
if authDaemonServer != nil && !certData.ExternalAuthDaemon { // if the auth daemon is running internally and the external auth daemon is not enabled
|
||||
if authDaemonServer != nil {
|
||||
// Call ProcessConnection directly when running internally
|
||||
logger.Debug("Calling internal auth daemon ProcessConnection for user %s", certData.Username)
|
||||
|
||||
@@ -1428,10 +1415,8 @@ persistent_keepalive_interval=5`, util.FixKey(privateKey.String()), util.FixKey(
|
||||
NiceId: certData.NiceID,
|
||||
Username: certData.Username,
|
||||
Metadata: authdaemon.ConnectionMetadata{
|
||||
SudoMode: certData.Metadata.SudoMode,
|
||||
SudoCommands: certData.Metadata.SudoCommands,
|
||||
Homedir: certData.Metadata.Homedir,
|
||||
Groups: certData.Metadata.Groups,
|
||||
Sudo: certData.Metadata.Sudo,
|
||||
Homedir: certData.Metadata.Homedir,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -1465,10 +1450,8 @@ persistent_keepalive_interval=5`, util.FixKey(privateKey.String()), util.FixKey(
|
||||
"niceId": certData.NiceID,
|
||||
"username": certData.Username,
|
||||
"metadata": map[string]interface{}{
|
||||
"sudoMode": certData.Metadata.SudoMode,
|
||||
"sudoCommands": certData.Metadata.SudoCommands,
|
||||
"homedir": certData.Metadata.Homedir,
|
||||
"groups": certData.Metadata.Groups,
|
||||
"sudo": certData.Metadata.Sudo,
|
||||
"homedir": certData.Metadata.Homedir,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
2
newt.iss
2
newt.iss
@@ -32,7 +32,7 @@ DefaultGroupName={#MyAppName}
|
||||
DisableProgramGroupPage=yes
|
||||
; Uncomment the following line to run in non administrative install mode (install for current user only).
|
||||
;PrivilegesRequired=lowest
|
||||
OutputBaseFilename=newt_windows_installer
|
||||
OutputBaseFilename=mysetup
|
||||
SolidCompression=yes
|
||||
WizardStyle=modern
|
||||
; Add this to ensure PATH changes are applied and the system is prompted for a restart if needed
|
||||
|
||||
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