Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

complete field development of first usable version #9

Merged
merged 3 commits into from
Jul 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ go.work

# Binary
/bunker
/cmd/bunker/__debug*

# Data
/bunker.yaml
Expand Down
19 changes: 19 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Launch Package",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${workspaceFolder}/cmd/bunker",
"cwd": "${workspaceFolder}",
"env": {
"DEBUG": "ui"
}
}
]
}
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ password: guest
Prepare a `bunker.yaml` file

```yaml
ui: # for display only
ssh_host: 'my.fancy.domain'
ssh_port: '8022'
server:
listen: ":8080"
ssh_server:
Expand Down
16 changes: 15 additions & 1 deletion app.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,27 @@ import (

type App struct {
db *gorm.DB

uiOpts uiOptions
}

type uiOptions struct {
SSHHost string `json:"ssh_host"`
SSHPort int `json:"ssh_port"`
}

type AppOptions struct {
fx.In

DB *gorm.DB
DB *gorm.DB
Conf ufx.Conf
}

func CreateApp(opts AppOptions) (app *App, err error) {
app = &App{
db: opts.DB,
}
err = opts.Conf.Bind(&app.uiOpts, "ui")
return
}

Expand Down Expand Up @@ -68,6 +77,10 @@ func (a *App) currentUser(c ufx.Context) (token *model.Token, user *model.User,
return
}

func (a *App) routeUIOptions(c ufx.Context) {
c.JSON(a.uiOpts)
}

func (a *App) routeCurrentUser(c ufx.Context) {
token, user := rg.Must2(a.currentUser(c))
if user != nil {
Expand Down Expand Up @@ -482,6 +495,7 @@ func (a *App) routeUpdatePassword(c ufx.Context) {
}

func InstallAppToRouter(a *App, ur ufx.Router) {
ur.HandleFunc("/backend/ui_options", a.routeUIOptions)
ur.HandleFunc("/backend/sign_in", a.routeSignIn)
ur.HandleFunc("/backend/sign_out", a.routeSignOut)
ur.HandleFunc("/backend/update_password", a.routeUpdatePassword)
Expand Down
50 changes: 34 additions & 16 deletions ssh.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ func CreateSSHServer(opts SSHServerOptions) (s *SSHServer, err error) {
listen: p.Listen,
signers: opts.Signers,
loggers: opts.Logger,
db: opts.DB,
}

if opts.Lifecycle != nil {
Expand Down Expand Up @@ -103,9 +104,9 @@ func (s *SSHServer) PublicKeyCallback(conn ssh.ConnMetadata, _key ssh.PublicKey)

// find key and user
var key *model.Key
if key, err = db.Key.Where(dao.Key.ID.Eq(
strings.ToLower(ssh.FingerprintSHA256(_key)),
)).Preload(dao.Key.User).First(); err != nil {
if key, err = db.Key.Where(db.Key.ID.Eq(
ssh.FingerprintSHA256(_key),
)).Preload(db.Key.User).First(); err != nil {
return nil, err
}

Expand All @@ -132,13 +133,13 @@ func (s *SSHServer) PublicKeyCallback(conn ssh.ConnMetadata, _key ssh.PublicKey)
)

var server *model.Server
if server, err = db.Server.Where(dao.Server.ID.Eq(serverID)).First(); err != nil {
if server, err = db.Server.Where(db.Server.ID.Eq(serverID)).First(); err != nil {
return
}

// find grants
var grants = []*model.Grant{}
if grants, err = db.Grant.Where(dao.Grant.UserID.Eq(key.User.ID)).Find(); err != nil {
if grants, err = db.Grant.Where(db.Grant.UserID.Eq(key.User.ID)).Find(); err != nil {
return
}

Expand Down Expand Up @@ -212,25 +213,31 @@ func (s *SSHServer) HandleServerConn(conn net.Conn) {
serverAddress = userConn.Permissions.Extensions[sshExtKeyServerAddress]
)

if _, port, _ := net.SplitHostPort(serverAddress); port == "" {
serverAddress = net.JoinHostPort(serverAddress, "22")
}

log := s.loggers.With(
"remote_addr", conn.RemoteAddr().String(),
"server_user", serverUser,
"server_address", serverAddress,
"server_id", userConn.Permissions.Extensions[sshExtKeyServerID],
"session_id", hex.EncodeToString(userConn.SessionID()),
)

var client *ssh.Client
if client, err = ssh.Dial("tcp", serverAddress, &ssh.ClientConfig{
User: serverUser,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(s.signers.Client...),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}); err != nil {
log.With("error", err).Error("ssh dial")
return
}
defer client.Close()

log := s.loggers.With(
"remote_addr", conn.RemoteAddr().String(),
"server_user", serverUser,
"server_address", serverAddress,
"server_id", userConn.Permissions.Extensions[sshExtKeyServerID],
"session_id", hex.EncodeToString(userConn.SessionID()),
)

PipeSSH(log, client, userConn, chUserNewChannel, chUserRequest)
}

Expand Down Expand Up @@ -269,12 +276,12 @@ func (s *SSHServer) Shutdown(ctx context.Context) (err error) {
}

func PipeSSH(log *zap.SugaredLogger, target *ssh.Client, userConn *ssh.ServerConn, chUserNewChannel <-chan ssh.NewChannel, chUserRequest <-chan *ssh.Request) {
// 'user' stands for the user side
// 'target' stands for the target server side

// handle user request for new channel
handleUserNewChannel := func(wg *sync.WaitGroup, userNewChannel ssh.NewChannel) {
defer wg.Done()

log := log.With("channel_type", userNewChannel.ChannelType())

// create target channel and target request channel
targetChannel, chTargetRequest, err1 := target.OpenChannel(userNewChannel.ChannelType(), userNewChannel.ExtraData())
if err1 != nil {
Expand All @@ -286,6 +293,7 @@ func PipeSSH(log *zap.SugaredLogger, target *ssh.Client, userConn *ssh.ServerCon
}
return
}
defer log.Info("channel end")
defer targetChannel.Close()

userChannel, chUserRequest, err1 := userNewChannel.Accept()
Expand All @@ -299,18 +307,23 @@ func PipeSSH(log *zap.SugaredLogger, target *ssh.Client, userConn *ssh.ServerCon
wg1.Add(1)
go func() {
defer wg1.Done()
defer log.Info("channel pipe end: from target")
defer userChannel.Close()
io.Copy(userChannel, targetChannel)
}()

wg1.Add(1)
go func() {
defer wg1.Done()
defer log.Info("channel pipe end: from user")
defer targetChannel.Close()
io.Copy(targetChannel, userChannel)
}()

wg1.Add(1)
go func() {
defer wg1.Done()
defer log.Info("channel request end: from target")
for targetRequest := range chTargetRequest {
ok, err2 := userChannel.SendRequest(targetRequest.Type, targetRequest.WantReply, targetRequest.Payload)
if targetRequest.WantReply {
Expand All @@ -325,6 +338,7 @@ func PipeSSH(log *zap.SugaredLogger, target *ssh.Client, userConn *ssh.ServerCon
wg1.Add(1)
go func() {
defer wg1.Done()
defer log.Info("channel request end: from user")
for userRequest := range chUserRequest {
ok, err2 := targetChannel.SendRequest(userRequest.Type, userRequest.WantReply, userRequest.Payload)
if userRequest.WantReply {
Expand All @@ -342,6 +356,8 @@ func PipeSSH(log *zap.SugaredLogger, target *ssh.Client, userConn *ssh.ServerCon
handleUserRequest := func(wg *sync.WaitGroup, userRequest *ssh.Request) {
defer wg.Done()

log.With("request_type", userRequest.Type).Info("user global request")

ok, buf, err1 := target.SendRequest(userRequest.Type, userRequest.WantReply, userRequest.Payload)
if userRequest.WantReply {
userRequest.Reply(ok, buf)
Expand All @@ -356,6 +372,7 @@ func PipeSSH(log *zap.SugaredLogger, target *ssh.Client, userConn *ssh.ServerCon
wg.Add(1)
go func() {
defer wg.Done()
defer log.Info("user new chan end")

wg1 := &sync.WaitGroup{}
for userNewChannel := range chUserNewChannel {
Expand All @@ -368,6 +385,7 @@ func PipeSSH(log *zap.SugaredLogger, target *ssh.Client, userConn *ssh.ServerCon
wg.Add(1)
go func() {
defer wg.Done()
defer log.Info("user request end")

wg1 := &sync.WaitGroup{}
for userRequest := range chUserRequest {
Expand Down
12 changes: 12 additions & 0 deletions ui/composables/ui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,16 @@ export const uiCard = {
footer: {
padding: 'py-2 px-1'
}
}

export const useUIOptions = () => {
return useAsyncData<{ ssh_host?: string; ssh_port?: number }>(
"ui-options",
() => $fetch("/backend/ui_options"),
{
default() {
return { ssh_host: '', ssh_port: 0 };
}
}
)
}
22 changes: 20 additions & 2 deletions ui/pages/dashboard/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,19 @@ definePageMeta({

const { data: items, refresh: refreshItems } = await useGrantedItems();

const { data: uiOptions, refresh: refreshUIOptions } = await useUIOptions();

const addressHint = computed(() => {
if (uiOptions.value.ssh_host) {
if (uiOptions.value.ssh_port) {
return `${uiOptions.value.ssh_host} -p ${uiOptions.value.ssh_port}`
} else {
return uiOptions.value.ssh_host
}
}
return 'BUNKER_ADDRESS'
})

const columns = [
{
key: "server_user",
Expand All @@ -31,18 +44,23 @@ function expandServerUser(s: string): string {
}
return s
}

</script>

<template>
<SkeletonDashboard :title-name="$t('dashboard.title')" title-icon="i-mdi-view-dashboard">
<template #left>
<UCard :ui="uiCard">
<article v-if="uiOptions.ssh_host" class="prose dark:prose-invert mb-4">
<p>Bunker SSH 地址: <span class="font-semibold">{{ uiOptions.ssh_host }}</span><span class="font-semibold"
v-if="uiOptions.ssh_port">:{{
uiOptions.ssh_port }}</span></p>
</article>
<article class="prose dark:prose-invert" v-html="$t('dashboard.intro')"></article>
</UCard>
</template>
<UTable :rows="items.granted_items" :columns="columns">
<template #example-data="{ row }">
<code class="font-mono">ssh {{ expandServerUser(row.server_user) }}@{{ row.server_id }}@BUNKER_ADDRESS</code>
<code class="font-mono">ssh {{ expandServerUser(row.server_user) }}@{{ row.server_id }}@{{ addressHint }}</code>
</template>
</UTable>
</SkeletonDashboard>
Expand Down
Loading