74 lines
1.8 KiB
Go
74 lines
1.8 KiB
Go
package proto
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"io"
|
|
"os"
|
|
"os/exec"
|
|
|
|
"github.com/libp2p/go-libp2p/core/host"
|
|
"github.com/libp2p/go-libp2p/core/network"
|
|
"github.com/libp2p/go-libp2p/core/peer"
|
|
protocol "github.com/libp2p/go-libp2p/core/protocol"
|
|
"github.com/portal-co/portald/provision"
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
func HasHash(pws [][]byte, x []byte) bool {
|
|
for _, pw := range pws {
|
|
if bcrypt.CompareHashAndPassword(x, pw) == nil {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
func ReadHash(pw [][]byte, x io.Reader) error {
|
|
var b [1]byte
|
|
h := bytes.NewBuffer([]byte{})
|
|
for !HasHash(pw, h.Bytes()) {
|
|
_, err := x.Read(b[:])
|
|
if err != nil {
|
|
return err
|
|
}
|
|
h.Write(b[:])
|
|
}
|
|
return nil
|
|
}
|
|
|
|
var BashId = "/p2p/portal-co-bash/0.0.1"
|
|
|
|
func AddBash(h host.Host, pw [][]byte) {
|
|
h.SetStreamHandler(protocol.ID(BashId), func(s network.Stream) {
|
|
if ReadHash(pw, s) != nil {
|
|
return
|
|
}
|
|
o, _ := os.MkdirTemp("/tmp", "portal-*")
|
|
defer os.RemoveAll(o)
|
|
e := exec.Command("bwrap", "--unshare-all", "--share-net", "--ro-bind", "/", "/", "--ro-bind", "/ipfs", "/ipfs", "--dev /dev", "--proc", "/proc", "--tmp", "/tmp", "--bind", o, o, "/bin/bash")
|
|
e.Stdin = s
|
|
e.Stdout = s
|
|
e.Dir = o
|
|
e.Run()
|
|
})
|
|
}
|
|
func GetBash(ctx context.Context, host host.Host, peer peer.ID) (network.Stream, error) {
|
|
return host.NewStream(ctx, peer, protocol.ID(BashId))
|
|
}
|
|
func RunIn(ctx context.Context, host host.Host, peer peer.ID, x provision.ProcessInputs, pw []byte) (provision.ProcessOutputs, error) {
|
|
s, err := GetBash(ctx, host, peer)
|
|
if err != nil {
|
|
return provision.ProcessOutputs{}, err
|
|
}
|
|
defer s.Close()
|
|
b, err := bcrypt.GenerateFromPassword(pw, bcrypt.DefaultCost)
|
|
if err != nil {
|
|
return provision.ProcessOutputs{}, err
|
|
}
|
|
_, err = s.Write(b)
|
|
if err != nil {
|
|
return provision.ProcessOutputs{}, err
|
|
}
|
|
return provision.Run(s, x)
|
|
}
|