package plugin import ( "context" "errors" "fmt" "runtime/metrics" "strings" "sync" "sync/atomic" "time" lua "github.com/yuin/gopher-lua" "git.security-command.org/Overlord/dibs/internal/config" ) // Limits cap every Lua call. They come from [sandbox] in dibs.toml. type Limits struct { // Timeout applies to loading a plugin and to matches, normalize, parse // and cart_link. Timeout time.Duration // SessionTimeout applies to login and add_to_cart. SessionTimeout time.Duration // MemoryBytes is the heap growth one call may cause. It is measured for // the whole process, so it is approximate. MemoryBytes int64 // CallStack is the maximum Lua call depth. CallStack int } func DefaultLimits() Limits { return Limits{ Timeout: config.DefaultSandboxTimeout, SessionTimeout: config.DefaultSessionTimeout, MemoryBytes: config.DefaultMemoryMB << 20, CallStack: config.DefaultCallStack, } } func LimitsFrom(s config.Sandbox) Limits { return Limits{ Timeout: s.Timeout.Duration, SessionTimeout: s.SessionTimeout.Duration, MemoryBytes: int64(s.MemoryMB) << 20, CallStack: s.CallStack, } } var ( ErrTimeout = errors.New("timed out") ErrMemoryLimit = errors.New("exceeded the memory limit") ) // removedGlobals could load code, or reach the interpreter's internals. // The os, io, debug, package and coroutine libraries are never opened. var removedGlobals = []string{ "dofile", "loadfile", "load", "loadstring", "require", "module", "collectgarbage", "getfenv", "setfenv", "newproxy", "_printregs", } // shortCalls lets one parse-type call run at a time, so the heap growth the // memory watchdog sees is that call's. These calls take milliseconds. var shortCalls sync.Mutex const watchInterval = 2 * time.Millisecond func newState(limits Limits) *lua.LState { L := lua.NewState(lua.Options{ SkipOpenLibs: true, CallStackSize: limits.CallStack, RegistrySize: 16 * 1024, RegistryMaxSize: 256 * 1024, MinimizeStackMemory: true, }) for _, lib := range []struct { name string open lua.LGFunction } { {lua.BaseLibName, lua.OpenBase}, {lua.TabLibName, lua.OpenTable}, {lua.StringLibName, lua.OpenString}, {lua.MathLibName, lua.OpenMath}, } { L.Push(L.NewFunction(lib.open)) L.Push(lua.LString(lib.name)) L.Call(1, 0) } for _, name := range removedGlobals { L.SetGlobal(name, lua.LNil) } // string.rep allocates its whole result at once, faster than the // watchdog can react. if str, ok := L.GetGlobal("string").(*lua.LTable); ok { str.RawSetString("rep", L.NewFunction(cappedRep(limits.MemoryBytes))) } return L } func cappedRep(limit int64) lua.LGFunction { return func(L *lua.LState) int { s := L.CheckString(1) n := L.CheckInt(2) if n <= 0 || s == "" { L.Push(lua.LString("")) return 1 } if int64(len(s))*int64(n) > limit { L.RaiseError("string.rep: result of %d bytes exceeds the memory limit", int64(len(s))*int64(n)) } L.Push(lua.LString(strings.Repeat(s, n))) return 1 } } // run calls fn, which must call into L, under a timeout and the memory // watchdog. func run(L *lua.LState, parent context.Context, timeout time.Duration, m *meter, fn func() error) error { ctx, cancel := context.WithTimeout(parent, timeout) defer cancel() done := make(chan struct{}) defer close(done) go m.watch(ctx, done, cancel) L.SetContext(ctx) defer L.RemoveContext() err := fn() switch { case err == nil: return nil case m.overLimit.Load(): return ErrMemoryLimit case parent.Err() != nil: return parent.Err() case errors.Is(ctx.Err(), context.DeadlineExceeded): return fmt.Errorf("%w after %s", ErrTimeout, timeout) default: return luaError(err) } } // meter is the memory watchdog of one call. It measures the heap growth of // the whole process, so host functions that wait on the network or the user // pause it: what they allocate is the host's, and the measurement starts // over when they return. type meter struct { limit int64 base atomic.Int64 paused atomic.Bool overLimit atomic.Bool } func newMeter(limit int64) *meter { m := &meter{limit: limit} m.base.Store(heapBytes()) return m } func (m *meter) pause() { m.paused.Store(true) } func (m *meter) resume() { m.base.Store(heapBytes()) m.paused.Store(false) } // watch cancels the call once the heap has grown by more than the limit. func (m *meter) watch(ctx context.Context, done <-chan struct{}, cancel context.CancelFunc) { ticker := time.NewTicker(watchInterval) defer ticker.Stop() for { select { case <-done: return case <-ctx.Done(): return case <-ticker.C: if !m.paused.Load() && heapBytes()-m.base.Load() > m.limit { m.overLimit.Store(true) cancel() return } } } } func heapBytes() int64 { sample := []metrics.Sample{{Name: "/memory/classes/heap/objects:bytes"}} metrics.Read(sample) return int64(sample[0].Value.Uint64()) } // luaError turns a Lua error into a one-line error such as // "amazon.lua:12: attempt to index a nil value". func luaError(err error) error { var apiErr *lua.ApiError if errors.As(err, &apiErr) && apiErr.Object != nil { return errors.New(strings.TrimSpace(apiErr.Object.String())) } return err }