コード例 #1
1
ファイル: hub_linux_test.go プロジェクト: v2ray/v2ray-core
func TestHubSocksOption(t *testing.T) {
	assert := assert.On(t)
	if os.Geteuid() != 0 {
		// This test case requires root permission.
		return
	}

	hub, err := ListenUDP(v2net.LocalHostIP, v2net.Port(0), ListenOption{
		Callback:            func(*buf.Buffer, *proxy.SessionInfo) {},
		ReceiveOriginalDest: true,
	})
	assert.Error(err).IsNil()
	conn := hub.Connection()

	fd, err := internal.GetSysFd(conn)
	assert.Error(err).IsNil()

	val, err := syscall.GetsockoptInt(fd, syscall.SOL_IP, syscall.IP_TRANSPARENT)
	assert.Error(err).IsNil()
	assert.Int(val).Equals(1)

	val, err = syscall.GetsockoptInt(fd, syscall.SOL_IP, syscall.IP_RECVORIGDSTADDR)
	assert.Error(err).IsNil()
	assert.Int(val).Equals(1)
}
コード例 #2
0
ファイル: main.go プロジェクト: wkharold/noeq9p
func serve9p() {
	var cl *Clone
	var err error
	var sf *StatsFile

	root, err = mkroot()
	if err != nil {
		goto error
	}

	cl = new(Clone)
	err = cl.Add(root, "clone", p.OsUsers.Uid2User(os.Geteuid()), nil, 0444, cl)
	if err != nil {
		goto error
	}

	sf = new(StatsFile)
	err = sf.Add(root, "stats", p.OsUsers.Uid2User(os.Geteuid()), nil, 0444, sf)
	if err != nil {
		goto error
	}

	fs = srv.NewFileSrv(root)
	fs.Dotu = true

	fs.Start(fs)
	err = fs.StartNetListener("tcp", *laddr)
	if err != nil {
		goto error
	}
	return

error:
	log.Fatalf("Error serving 9p: %s\n", err)
}
コード例 #3
0
ファイル: nfqueue.go プロジェクト: Safe3/fw-daemon
func NewNFQueue(qid uint16) (nfq *nfQueue) {
	if os.Geteuid() != 0 {

	}
	if os.Geteuid() != 0 {
		panic("Must be ran by root.")
	}
	nfq = &nfQueue{DefaultVerdict: ACCEPT, Timeout: time.Microsecond * 5, qid: qid}
	return nfq
}
コード例 #4
0
ファイル: ownership.go プロジェクト: rxacevedo/keywhiz-fs
// lookupUid resolves a username to a numeric id. Current euid is returned on failure.
func lookupUid(username string) uint32 {
	u, err := user.Lookup(username)
	if err != nil {
		log.Printf("Error resolving uid for %v: %v\n", username, err)
		return uint32(os.Geteuid())
	}

	uid, err := strconv.ParseUint(u.Uid, 10 /* base */, 32 /* bits */)
	if err != nil {
		log.Printf("Error resolving uid for %v: %v\n", username, err)
		return uint32(os.Geteuid())
	}

	return uint32(uid)
}
コード例 #5
0
ファイル: service.go プロジェクト: pb-it/rexray
func checkOpPerms(op string) error {
	if os.Geteuid() != 0 {
		return errors.Newf("REX-Ray can only be %s by root", op)
	}

	return nil
}
コード例 #6
0
ファイル: command_install.go プロジェクト: zhaohaiyi/git-lfs
func installCommand(cmd *cobra.Command, args []string) {
	requireGitVersion()

	if localInstall {
		requireInRepo()
	}

	if systemInstall && os.Geteuid() != 0 {
		Print("WARNING: current user is not root/admin, system install is likely to fail.")
	}

	if localInstall && systemInstall {
		Exit("Only one of --local and --system options can be specified.")
	}

	opt := lfs.InstallOptions{Force: forceInstall, Local: localInstall, System: systemInstall}
	if skipSmudgeInstall {
		// assume the user is changing their smudge mode, so enable force implicitly
		opt.Force = true
	}

	if err := lfs.InstallFilters(opt, skipSmudgeInstall); err != nil {
		Error(err.Error())
		Exit("Run `git lfs install --force` to reset git config.")
	}

	if localInstall || lfs.InRepo() {
		installHooksCommand(cmd, args)
	}

	Print("Git LFS initialized.")
}
コード例 #7
0
ファイル: core.go プロジェクト: troyxmccall/gogospoofdns
func main() {
	if os.Geteuid() != 0 {
		fmt.Println("gogospoofdns requires root!")
		return
	}

	var dev string = "eno1"

	fmt.Println("Running arp poison")
	routerMac, err := net.ParseMAC("00:1A:6D:38:15:FF")
	routerIP := net.IP{192, 168, 0, 100}
	localMac, err := net.ParseMAC("98:90:96:D5:84:7B")
	localIP := net.IP{192, 168, 0, 9}
	victimMac, err := net.ParseMAC("98:90:96:DC:fB:6A")
	victimIP := net.IP{192, 168, 0, 10}
	/********* end parse all IP's and MAC's relevent for poisoning / spoofing *********/

	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	go arpPoison(dev, routerMac, routerIP, localMac, localIP, victimMac, victimIP)

	fmt.Println("Running spoofer")
	spoof(dev)
}
コード例 #8
0
ファイル: fuse.go プロジェクト: hanwen/termite
func newFuseFS(tmpDir string, rpcFS *RpcFs, writableRoot string) (*fuseFS, error) {
	tmpDir, err := ioutil.TempDir(tmpDir, "termite-task")
	if err != nil {
		return nil, err
	}

	fs := &fuseFS{
		writableRoot: strings.TrimLeft(writableRoot, "/"),
		workers:      map[string]*workerFS{},
		rpcFS:        rpcFS,
		rpcNodeFS: pathfs.NewPathNodeFs(&multiRPCFS{rpcFS},
			&pathfs.PathNodeFsOptions{ClientInodes: true}),
		tmpDir: tmpDir,
		mount:  filepath.Join(tmpDir, "mnt"),
	}
	if err := os.Mkdir(fs.mount, 0755); err != nil {
		return nil, err
	}

	fs.fsConnector = nodefs.NewFileSystemConnector(fs.rpcNodeFS.Root(),
		nodeFSOptions())
	fuseOpts := fuse.MountOptions{}
	if os.Geteuid() == 0 {
		fuseOpts.AllowOther = true
	}

	fs.server, err = fuse.NewServer(fs.fsConnector.RawFS(), fs.mount, &fuseOpts)
	if err != nil {
		return nil, err
	}
	go fs.server.Serve()
	return fs, nil
}
コード例 #9
0
ファイル: fetcher.go プロジェクト: intelsdi-x/rkt
// FetchImage will take an image as either a path, a URL or a name
// string and import it into the store if found. If ascPath is not "",
// it must exist as a local file and will be used as the signature
// file for verification, unless verification is disabled. If
// f.WithDeps is true also image dependencies are fetched.
func (f *Fetcher) FetchImage(d dist.Distribution, image, ascPath string) (*types.Hash, error) {
	ensureLogger(f.Debug)
	db := &distBundle{
		dist:  d,
		image: image,
	}
	a := f.getAsc(ascPath)
	hash, err := f.fetchSingleImage(db, a)
	if err != nil {
		return nil, err
	}
	if f.WithDeps {
		err = f.fetchImageDeps(hash)
		if err != nil {
			return nil, err
		}
	}

	// we need to be able to do a chroot and access to the tree store
	// directories, we need to
	// 1) check if the system supports OverlayFS
	// 2) check if we're root
	if common.SupportsOverlay() == nil && os.Geteuid() == 0 {
		if _, _, err := f.Ts.Render(hash, false); err != nil {
			return nil, errwrap.Wrap(errors.New("error rendering tree store"), err)
		}
	}
	h, err := types.NewHash(hash)
	if err != nil {
		// should never happen
		log.PanicE("invalid hash", err)
	}
	return h, nil
}
コード例 #10
0
ファイル: ramfs.go プロジェクト: rjkroege/go9p
func main() {
	var err error
	var l *p.Logger

	flag.Parse()
	rsrv.user = p.OsUsers.Uid2User(os.Geteuid())
	rsrv.group = p.OsUsers.Gid2Group(os.Getegid())
	rsrv.blksz = *blksize
	rsrv.blkchan = make(chan []byte, 2048)
	rsrv.zero = make([]byte, rsrv.blksz)

	root := new(RFile)
	err = root.Add(nil, "/", rsrv.user, nil, p.DMDIR|0777, root)
	if err != nil {
		goto error
	}

	l = p.NewLogger(*logsz)
	rsrv.srv = srv.NewFileSrv(&root.File)
	rsrv.srv.Dotu = true
	rsrv.srv.Debuglevel = *debug
	rsrv.srv.Start(rsrv.srv)
	rsrv.srv.Id = "ramfs"
	rsrv.srv.Log = l

	err = rsrv.srv.StartNetListener("tcp", *addr)
	if err != nil {
		goto error
	}
	return

error:
	log.Println(fmt.Sprintf("Error: %s", err))
}
コード例 #11
0
ファイル: main.go プロジェクト: tbrogan/fw-daemon
func main() {

	if os.Geteuid() != 0 {
		log.Error("Must be run as root")
		os.Exit(1)
	}

	setupIPTables()

	ds, err := newDbusServer()
	if err != nil {
		log.Error(err.Error())
		os.Exit(1)
	}

	fw := &Firewall{
		dbus:      ds,
		dns:       NewDnsCache(),
		policyMap: make(map[string]*Policy),
	}

	fw.loadRules()

	/*
		go func() {
			http.ListenAndServe("localhost:6060", nil)
		}()
	*/

	fw.runFilter()
}
コード例 #12
0
ファイル: run.go プロジェクト: gosuper/run
// Initialize and exit if -I or --init is given.
func initialize() {
	for _, arg := range os.Args {
		if arg == "-I" || arg == "--init" {
			if utils.IsRunInstalled() {
				utils.LogInfo("Run is already installed\n")
			} else {
				if os.Geteuid() != 0 {
					utils.LogError("Root privilege is required\n")
					os.Exit(1)
				}
				// Create script cache directory.
				err := os.MkdirAll(utils.DATA_DIR, 0777)
				if err != nil {
					utils.ExitError(err)
				}
				// Download run.conf, VERSION and run.1 from master branch.
				err = utils.Fetch(utils.MASTER_URL+"run.conf", utils.CONFIG_PATH)
				if err != nil {
					utils.ExitError(err)
				}
				err = utils.Fetch(utils.MASTER_URL+"VERSION", utils.DATA_DIR+"/VERSION")
				if err != nil {
					utils.ExitError(err)
				}
				err = utils.Fetch(utils.MASTER_URL+"man/run.1", "/usr/share/man/man1/run.1.gz")
				if err != nil {
					utils.ExitError(err)
				}
			}
			os.Exit(0)
		}
	}
}
コード例 #13
0
ファイル: clonefs.go プロジェクト: jsouthworth/ixp
func (cl *Clone) Read(fid *srv.FFid, buf []byte, offset uint64) (int, error) {
	// we only allow a single read from us, change the offset and we're done
	if offset > uint64(0) {
		return 0, nil
	}

	cl.clones += 1
	ncl := new(ClFile)
	ncl.id = cl.clones
	ncl.created = time.Now().String()
	name := strconv.Itoa(ncl.id)

	err := root.Add(&ncl.File, name, ixp.OsUsers.Uid2User(os.Geteuid()), nil, 0666, ncl)
	if err != nil {
		return 0, &ixp.Error{"can not create file", 0}
	}

	b := []byte(name)
	if len(buf) < len(b) {
		// cleanup
		ncl.File.Remove()
		return 0, &ixp.Error{"not enough buffer space for result", 0}
	}

	copy(buf, b)
	return len(b), nil
}
コード例 #14
0
ファイル: main.go プロジェクト: lht/termite
func main() {
	cachedir := flag.String("cachedir", "/var/cache/termite/worker-cache", "content cache")
	tmpdir := flag.String("tmpdir", "/var/tmp",
		"where to create FUSE mounts; should be on same partition as cachedir.")
	secretFile := flag.String("secret", "secret.txt", "file containing password.")
	port := flag.Int("port", 1235, "Where to listen for work requests.")
	coordinator := flag.String("coordinator", "", "Where to register the worker.")
	jobs := flag.Int("jobs", 1, "Max number of jobs to run.")
	user := flag.String("user", "nobody", "Run as this user.")
	flag.Parse()

	if os.Geteuid() != 0 {
		log.Fatal("This program must run as root")
	}
	secret, err := ioutil.ReadFile(*secretFile)
	if err != nil {
		log.Fatal("ReadFile", err)
	}

	opts := termite.WorkerOptions{
		Secret:   secret,
		TempDir:  *tmpdir,
		CacheDir: *cachedir,
		Jobs:     *jobs,
		User:     user,
	}

	daemon := termite.NewWorkerDaemon(&opts)
	go handleStop(daemon)
	daemon.RunWorkerServer(*port, *coordinator)
}
コード例 #15
0
ファイル: files.go プロジェクト: joshix/acbuild
// ExtractImage will extract the contents of the image at path to the directory
// at dst. If fileMap is set, only files in it will be extracted.
func ExtractImage(path, dst string, fileMap map[string]struct{}) error {
	dst, err := filepath.Abs(dst)
	if err != nil {
		return err
	}
	file, err := os.Open(path)
	if err != nil {
		return err
	}
	defer file.Close()

	dr, err := aci.NewCompressedReader(file)
	if err != nil {
		return fmt.Errorf("error decompressing image: %v", err)
	}
	defer dr.Close()

	uidRange := user.NewBlankUidRange()

	if os.Geteuid() == 0 {
		return rkttar.ExtractTar(dr, dst, true, uidRange, fileMap)
	}

	editor, err := rkttar.NewUidShiftingFilePermEditor(uidRange)
	if err != nil {
		return fmt.Errorf("error determining current user: %v", err)
	}
	return rkttar.ExtractTarInsecure(tar.NewReader(dr), dst, true, fileMap, editor)
}
コード例 #16
0
ファイル: store.go プロジェクト: nhlfr/rkt
// backupDB backs up current database.
func (s *Store) backupDB() error {
	if os.Geteuid() != 0 {
		return ErrDBUpdateNeedsRoot
	}
	backupsDir := filepath.Join(s.dir, "db-backups")
	return backup.CreateBackup(s.dbDir(), backupsDir, backupsNumber)
}
コード例 #17
0
ファイル: main.go プロジェクト: nhooyr/dos
func main() {
	log.SetPrefix("")
	log.SetFlags(0)
	if os.Geteuid() != 0 {
		log.Fatal(errors.New("please run as root"))
	}
	fd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_RAW, syscall.IPPROTO_RAW)
	check(err)
	if len(os.Args) < 3 {
		log.Fatal("usage: synflood <victimIP> <spoofedIP>")
	}
	raddr := net.ParseIP(os.Args[1])
	addr := syscall.SockaddrInet4{
		Port: 0,
		Addr: to4Array(raddr),
	}
	p := packet(raddr)
	switch runtime.GOOS {
	case "darwin", "dragonfly", "freebsd", "netbsd":
		// need to set explicitly
		check(syscall.SetsockoptInt(fd, syscall.IPPROTO_IP, syscall.IP_HDRINCL, 1))
		// no need to receive anything
		check(syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_RCVBUF, 1))
	case "linux":
		// no need to receive anything
		check(syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_RCVBUF, 0))
	}
	for {
		check(syscall.Sendto(fd, p, 0, &addr))
	}
}
コード例 #18
0
func statusHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/plain")
	fmt.Fprintf(w, "pid=%d\n", os.Getpid())
	cwd, _ := os.Getwd()
	fmt.Fprintf(w, "cwd=%s\n", cwd)
	fmt.Fprintf(w, "uid=%d\n", os.Getuid())
	fmt.Fprintf(w, "euid=%d\n", os.Geteuid())
	fmt.Fprintf(w, "gid=%d\n", os.Getgid())

	groups, gerr := exec.Command("groups").CombinedOutput()
	if gerr != nil {
		fmt.Fprintf(w, "groups_err=%q\n", gerr)
	} else {
		fmt.Fprintf(w, "groups=%s\n", strings.TrimSpace(string(groups)))
	}

	ulimitN, _ := exec.Command("ulimit", "-n").Output()
	fmt.Fprintf(w, "ulimit_nofiles=%s\n", strings.TrimSpace(string(ulimitN)))

	env := os.Environ()
	sort.Strings(env)
	for _, env := range env {
		fmt.Fprintf(w, "%s\n", env)
	}
}
コード例 #19
0
ファイル: unionfs.go プロジェクト: taruti/go-fuse
func (me *UnionFs) Chown(name string, uid uint32, gid uint32, context *fuse.Context) (code fuse.Status) {
	name = stripSlash(name)
	r := me.getBranch(name)
	if r.attr == nil || r.code != fuse.OK {
		return r.code
	}

	if os.Geteuid() != 0 {
		return fuse.EPERM
	}

	if r.attr.Uid != int(uid) || r.attr.Gid != int(gid) {
		if r.branch > 0 {
			code := me.Promote(name, r, context)
			if code != fuse.OK {
				return code
			}
			r.branch = 0
		}
		me.fileSystems[0].Chown(name, uid, gid, context)
	}
	r.attr.Uid = int(uid)
	r.attr.Gid = int(gid)
	r.attr.Ctime_ns = time.Nanoseconds()
	me.branchCache.Set(name, r)
	return fuse.OK
}
コード例 #20
0
ファイル: worker_test.go プロジェクト: lht/termite
func TestEndToEndStdout(t *testing.T) {
	if os.Geteuid() == 0 {
		log.Println("This test should not run as root")
		return
	}

	tc := NewTestCase(t)
	defer tc.Clean()

	err := os.Symlink("oldlink", tc.tmp+"/wd/symlink")
	if err != nil {
		t.Fatal("oldlink symlink", err)
	}

	shcmd := make([]byte, 1500)
	for i := 0; i < len(shcmd); i++ {
		shcmd[i] = 'a'
	}
	err = ioutil.WriteFile(tc.tmp+"/wd/file.txt", shcmd, 0644)
	if err != nil {
		t.Fatalf("WriteFile %#v", err)
	}

	rep := tc.Run(WorkRequest{
		Binary: tc.FindBin("cat"),
		Argv:   []string{"cat", "file.txt"},
		Env:    testEnv(),
		Dir:    tc.tmp + "/wd",
	})

	if string(rep.Stdout) != string(shcmd) {
		t.Errorf("Reply mismatch %s expect %s", string(rep.Stdout), string(shcmd))
	}
}
コード例 #21
0
ファイル: unionfs.go プロジェクト: kicool/go-fuse
func (me *UnionFs) Chown(name string, uid uint32, gid uint32, context *fuse.Context) (code fuse.Status) {
	name = stripSlash(name)
	r := me.getBranch(name)
	if r.attr == nil || r.code != fuse.OK {
		return r.code
	}

	if os.Geteuid() != 0 {
		return fuse.EPERM
	}

	if r.attr.Uid != uid || r.attr.Gid != gid {
		if r.branch > 0 {
			code := me.Promote(name, r, context)
			if code != fuse.OK {
				return code
			}
			r.branch = 0
		}
		me.fileSystems[0].Chown(name, uid, gid, context)
	}
	r.attr.Uid = uid
	r.attr.Gid = gid
	now := time.Now()
	r.attr.SetTimes(nil, nil, &now)
	me.branchCache.Set(name, r)
	return fuse.OK
}
コード例 #22
0
ファイル: manager.go プロジェクト: laszlo-kiss/govisor
func (m *Manager) setBaseDir() {
	m.baseDir = os.Getenv("GOVISORDIR")
	switch runtime.GOOS {
	case "nacl", "plan9":
		m.baseDir = ""
	case "windows":
		if len(m.baseDir) == 0 {
			m.baseDir = os.Getenv("HOME")
		}
		if len(m.baseDir) == 0 {
			m.baseDir = "C:\\"
		}
	default:
		if len(m.baseDir) == 0 {
			if os.Geteuid() == 0 {
				m.baseDir = "/var"
			} else {
				m.baseDir = os.Getenv("HOME")
			}
		}
		if len(m.baseDir) == 0 {
			m.baseDir = "."
		}
	}
}
コード例 #23
0
ファイル: loopback_test.go プロジェクト: seacoastboy/go-fuse
func TestAccess(t *testing.T) {
	if os.Geteuid() == 0 {
		t.Log("Skipping TestAccess() as root.")
		return
	}
	tc := NewTestCase(t)
	defer tc.Cleanup()

	contents := []byte{1, 2, 3}
	err := ioutil.WriteFile(tc.origFile, []byte(contents), 0700)
	if err != nil {
		t.Fatalf("WriteFile failed: %v", err)
	}
	err = os.Chmod(tc.origFile, 0)
	if err != nil {
		t.Fatalf("Chmod failed: %v", err)
	}
	// Ugh - copied from unistd.h
	const W_OK uint32 = 2

	errCode := syscall.Access(tc.mountFile, W_OK)
	if errCode != syscall.EACCES {
		t.Errorf("Expected EACCES for non-writable, %v %v", errCode, syscall.EACCES)
	}
	err = os.Chmod(tc.origFile, 0222)
	if err != nil {
		t.Fatalf("Chmod failed: %v", err)
	}
	errCode = syscall.Access(tc.mountFile, W_OK)
	if errCode != nil {
		t.Errorf("Expected no error code for writable. %v", errCode)
	}
}
コード例 #24
0
ファイル: worker.go プロジェクト: lht/termite
func NewWorkerDaemon(options *WorkerOptions) *WorkerDaemon {
	if options.FileContentCount == 0 {
		options.FileContentCount = 1024
	}

	cache := NewContentCache(options.CacheDir)
	cache.SetMemoryCacheSize(options.FileContentCount)
	me := &WorkerDaemon{
		secret:        options.Secret,
		contentCache:  cache,
		mirrorMap:     make(map[string]*Mirror),
		contentServer: &ContentServer{Cache: cache},
		pending:       NewPendingConnections(),
		maxJobCount:   options.Jobs,
		tmpDir:        options.TempDir,
		rpcServer:     rpc.NewServer(),
	}
	if os.Geteuid() == 0 && options.User != nil {
		nobody, err := user.Lookup(*options.User)
		if err != nil {
			log.Fatalf("can't lookup %q: %v", options.User, err)
		}
		me.Nobody = nobody
	}
	me.cond = sync.NewCond(&me.mirrorMapMutex)
	me.stopListener = make(chan int, 1)
	me.rpcServer.Register(me)
	return me
}
コード例 #25
0
ファイル: worker_test.go プロジェクト: lht/termite
func TestEndToEndMove(t *testing.T) {
	if os.Geteuid() == 0 {
		log.Println("This test should not run as root")
		return
	}

	tc := NewTestCase(t)
	defer tc.Clean()

	rep := tc.Run(WorkRequest{
		Binary: tc.FindBin("mkdir"),
		Argv:   []string{"mkdir", "-p", "a/b/c"},
		Env:    testEnv(),
		Dir:    tc.tmp + "/wd",
	})
	if rep.Exit.ExitStatus() != 0 {
		t.Fatalf("mkdir should exit cleanly. Rep %v", rep)
	}
	rep = tc.Run(WorkRequest{
		Binary: tc.FindBin("mv"),
		Argv:   []string{"mv", "a", "q"},
		Env:    testEnv(),
		Dir:    tc.tmp + "/wd",
	})
	if rep.Exit.ExitStatus() != 0 {
		t.Fatalf("mv should exit cleanly. Rep %v", rep)
	}

	if fi, err := os.Lstat(tc.tmp + "/wd/q/b/c"); err != nil || !fi.IsDirectory() {
		t.Errorf("dir should have been moved. Err %v, fi %v", err, fi)
	}
}
コード例 #26
0
ファイル: loopback_test.go プロジェクト: taruti/go-fuse
func TestAccess(t *testing.T) {
	if os.Geteuid() == 0 {
		t.Log("Skipping TestAccess() as root.")
		return
	}
	me := NewTestCase(t)
	defer me.Cleanup()

	err := ioutil.WriteFile(me.origFile, []byte(contents), 0700)
	CheckSuccess(err)
	err = os.Chmod(me.origFile, 0)
	CheckSuccess(err)
	// Ugh - copied from unistd.h
	const W_OK uint32 = 2

	errCode := syscall.Access(me.mountFile, W_OK)
	if errCode != syscall.EACCES {
		t.Errorf("Expected EACCES for non-writable, %v %v", errCode, syscall.EACCES)
	}
	err = os.Chmod(me.origFile, 0222)
	CheckSuccess(err)
	errCode = syscall.Access(me.mountFile, W_OK)
	if errCode != nil {
		t.Errorf("Expected no error code for writable. %v", errCode)
	}
}
コード例 #27
0
ファイル: main.go プロジェクト: datatonic/Dominator
func main() {
	flag.Parse()
	tricorder.RegisterFlags()
	if os.Geteuid() == 0 {
		fmt.Fprintln(os.Stderr, "Do not run the Image Server as root")
		os.Exit(1)
	}
	setupTls(*caFile, *certFile, *keyFile)
	circularBuffer := logbuf.New(*logbufLines)
	logger := log.New(circularBuffer, "", log.LstdFlags)
	objSrv, err := filesystem.NewObjectServer(*objectDir, logger)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Cannot create ObjectServer\t%s\n", err)
		os.Exit(1)
	}
	imdb, err := scanner.LoadImageDataBase(*imageDir, objSrv, logger)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Cannot load image database\t%s\n", err)
		os.Exit(1)
	}
	tricorder.RegisterMetric("/image-count",
		func() uint { return imdb.CountImages() },
		units.None, "number of images")
	imageserverRpcd.Setup(imdb, logger)
	rpcHtmlWriter := objectserverRpcd.Setup(objSrv, logger)
	rpc.HandleHTTP()
	httpd.AddHtmlWriter(imdb)
	httpd.AddHtmlWriter(rpcHtmlWriter)
	httpd.AddHtmlWriter(circularBuffer)
	if err = httpd.StartServer(*portNum, imdb, false); err != nil {
		fmt.Fprintf(os.Stderr, "Unable to create http server\t%s\n", err)
		os.Exit(1)
	}
}
コード例 #28
0
ファイル: snapenv_test.go プロジェクト: pedronis/snappy
func (s *HTestSuite) TestSnapRunSnapExecEnv(c *C) {
	info, err := snap.InfoFromSnapYaml(mockYaml)
	c.Assert(err, IsNil)
	info.SideInfo.Revision = snap.R(42)

	usr, err := user.Current()
	c.Assert(err, IsNil)

	homeEnv := os.Getenv("HOME")
	defer os.Setenv("HOME", homeEnv)

	for _, withHomeEnv := range []bool{true, false} {
		if !withHomeEnv {
			os.Setenv("HOME", "")
		}

		env := snapEnv(info)
		c.Check(env, DeepEquals, map[string]string{
			"HOME":              fmt.Sprintf("%s/snap/snapname/42", usr.HomeDir),
			"SNAP":              fmt.Sprintf("%s/snapname/42", dirs.SnapMountDir),
			"SNAP_ARCH":         arch.UbuntuArchitecture(),
			"SNAP_COMMON":       "/var/snap/snapname/common",
			"SNAP_DATA":         "/var/snap/snapname/42",
			"SNAP_LIBRARY_PATH": "/var/lib/snapd/lib/gl:",
			"SNAP_NAME":         "snapname",
			"SNAP_REEXEC":       "",
			"SNAP_REVISION":     "42",
			"SNAP_USER_COMMON":  fmt.Sprintf("%s/snap/snapname/common", usr.HomeDir),
			"SNAP_USER_DATA":    fmt.Sprintf("%s/snap/snapname/42", usr.HomeDir),
			"SNAP_VERSION":      "1.0",
			"XDG_RUNTIME_DIR":   fmt.Sprintf("/run/user/%d/snap.snapname", os.Geteuid()),
		})
	}
}
コード例 #29
0
ファイル: tar.go プロジェクト: rhencke/acbuild
func NewUidShiftingFilePermEditor(uidRange *uid.UidRange) (FilePermissionsEditor, error) {
	if os.Geteuid() != 0 {
		return func(_ string, _, _ int, _ byte, _ os.FileInfo) error {
			// The files are owned by the current user on creation.
			// If we do nothing, they will remain so.
			return nil
		}, nil
	}

	return func(path string, uid, gid int, typ byte, fi os.FileInfo) error {
		shiftedUid, shiftedGid, err := uidRange.ShiftRange(uint32(uid), uint32(gid))
		if err != nil {
			return err
		}
		if err := os.Lchown(path, int(shiftedUid), int(shiftedGid)); err != nil {
			return err
		}

		// lchown(2) says that, depending on the linux kernel version, it
		// can change the file's mode also if executed as root. So call
		// os.Chmod after it.
		if typ != tar.TypeSymlink {
			if err := os.Chmod(path, fi.Mode()); err != nil {
				return err
			}
		}
		return nil
	}, nil
}
コード例 #30
0
ファイル: nullfs_test.go プロジェクト: hugelgupf/ninep
// It's recommended not to have a helper. But this is so much boiler plate.
func setup(msize uint32, failf func(...interface{})) (*clnt.Clnt, *clnt.Fid) {
	f := new(NullFS)
	f.Dotu = false
	f.Id = "ufs"
	f.Debuglevel = 0
	if !f.Start(f) {
		failf("Can't happen: Starting the server failed")
	}

	l, err := net.Listen("unix", "")
	if err != nil {
		failf("net.Listen: want nil, got %v", err)
	}

	go func() {
		if err = f.StartListener(l); err != nil {
			failf("Can not start listener: %v", err)
		}
	}()

	user := ninep.OsUsers.Uid2User(os.Geteuid())

	clnt, err := clnt.Mount("unix", l.Addr().String(), "/", 8192, user)

	if err != nil {
		failf("Attach: %v", err)
	}

	rootfid := clnt.Root
	return clnt, rootfid
}