github.com/containerd/containerd@v22.0.0-20200918172823-438c87b8e050+incompatible/contrib/apparmor/apparmor.go (about)

     1  // +build linux
     2  
     3  /*
     4     Copyright The containerd Authors.
     5  
     6     Licensed under the Apache License, Version 2.0 (the "License");
     7     you may not use this file except in compliance with the License.
     8     You may obtain a copy of the License at
     9  
    10         http://www.apache.org/licenses/LICENSE-2.0
    11  
    12     Unless required by applicable law or agreed to in writing, software
    13     distributed under the License is distributed on an "AS IS" BASIS,
    14     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    15     See the License for the specific language governing permissions and
    16     limitations under the License.
    17  */
    18  
    19  package apparmor
    20  
    21  import (
    22  	"context"
    23  	"io/ioutil"
    24  	"os"
    25  
    26  	"github.com/containerd/containerd/containers"
    27  	"github.com/containerd/containerd/oci"
    28  	specs "github.com/opencontainers/runtime-spec/specs-go"
    29  	"github.com/pkg/errors"
    30  )
    31  
    32  // WithProfile sets the provided apparmor profile to the spec
    33  func WithProfile(profile string) oci.SpecOpts {
    34  	return func(_ context.Context, _ oci.Client, _ *containers.Container, s *specs.Spec) error {
    35  		s.Process.ApparmorProfile = profile
    36  		return nil
    37  	}
    38  }
    39  
    40  // WithDefaultProfile will generate a default apparmor profile under the provided name
    41  // for the container.  It is only generated if a profile under that name does not exist.
    42  func WithDefaultProfile(name string) oci.SpecOpts {
    43  	return func(_ context.Context, _ oci.Client, _ *containers.Container, s *specs.Spec) error {
    44  		yes, err := isLoaded(name)
    45  		if err != nil {
    46  			return err
    47  		}
    48  		if yes {
    49  			s.Process.ApparmorProfile = name
    50  			return nil
    51  		}
    52  		p, err := loadData(name)
    53  		if err != nil {
    54  			return err
    55  		}
    56  		f, err := ioutil.TempFile(os.Getenv("XDG_RUNTIME_DIR"), p.Name)
    57  		if err != nil {
    58  			return err
    59  		}
    60  		defer f.Close()
    61  		path := f.Name()
    62  		defer os.Remove(path)
    63  
    64  		if err := generate(p, f); err != nil {
    65  			return err
    66  		}
    67  		if err := load(path); err != nil {
    68  			return errors.Wrapf(err, "load apparmor profile %s", path)
    69  		}
    70  		s.Process.ApparmorProfile = name
    71  		return nil
    72  	}
    73  }