Beispiel #1
0
// AcquireUserCredentials acquires credentials of user described by
// domain, username and password. These will be used by the client to
// authenticate itself to the server. It will also be used by the
// server to impersonate the user.
func AcquireUserCredentials(domain, username, password string) (*sspi.Credentials, error) {
	if len(domain) == 0 {
		return nil, errors.New("domain parameter cannot be empty")
	}
	if len(username) == 0 {
		return nil, errors.New("username parameter cannot be empty")
	}
	d, err := syscall.UTF16FromString(domain)
	if err != nil {
		return nil, err
	}
	u, err := syscall.UTF16FromString(username)
	if err != nil {
		return nil, err
	}
	var p []uint16
	var plen uint32
	if len(password) > 0 {
		p, err = syscall.UTF16FromString(password)
		if err != nil {
			return nil, err
		}
		plen = uint32(len(p) - 1) // do not count terminating 0
	}
	ai := _SEC_WINNT_AUTH_IDENTITY{
		User:           &u[0],
		UserLength:     uint32(len(u) - 1), // do not count terminating 0
		Domain:         &d[0],
		DomainLength:   uint32(len(d) - 1), // do not count terminating 0
		Password:       &p[0],
		PasswordLength: plen,
		Flags:          _SEC_WINNT_AUTH_IDENTITY_UNICODE,
	}
	return acquireCredentials(sspi.SECPKG_CRED_OUTBOUND, &ai)
}
Beispiel #2
0
// NewClientContext creates new client context. It uses client
// credentials cred generated by AcquireCurrentUserCredentials or
// AcquireUserCredentials and SPN to start client Negotiate
// negotiation sequence. targetName is the service principal name
// (SPN) or the security context of the destination server.
// NewClientContext returns new token to be sent to the server.
func NewClientContext(cred *sspi.Credentials, targetName string) (cc *ClientContext, outputToken []byte, err error) {
	var tname *uint16
	if len(targetName) > 0 {
		p, err2 := syscall.UTF16FromString(targetName)
		if err2 != nil {
			return nil, nil, err2
		}
		if len(p) > 0 {
			tname = &p[0]
		}
	}
	otoken := make([]byte, PackageInfo.MaxToken)
	c := sspi.NewClientContext(cred, sspi.ISC_REQ_CONNECTION)
	authCompleted, n, err2 := updateContext(c, otoken, nil, tname)
	if err2 != nil {
		return nil, nil, err2
	}
	if authCompleted {
		c.Release()
		return nil, nil, errors.New("negotiate authentication should not be completed yet")
	}
	if n == 0 {
		c.Release()
		return nil, nil, errors.New("negotiate token should not be empty")
	}
	otoken = otoken[:n]
	return &ClientContext{sctxt: c, targetName: tname}, otoken, nil
}
Beispiel #3
0
// SetText sets the current text data of the clipboard.
func (c *ClipboardService) SetText(s string) error {
	return c.withOpenClipboard(func() error {
		utf16, err := syscall.UTF16FromString(s)
		if err != nil {
			return err
		}

		hMem := win.GlobalAlloc(win.GMEM_MOVEABLE, uintptr(len(utf16)*2))
		if hMem == 0 {
			return lastError("GlobalAlloc")
		}

		p := win.GlobalLock(hMem)
		if p == nil {
			return lastError("GlobalLock()")
		}

		win.MoveMemory(p, unsafe.Pointer(&utf16[0]), uintptr(len(utf16)*2))

		win.GlobalUnlock(hMem)

		if 0 == win.SetClipboardData(win.CF_UNICODETEXT, win.HANDLE(hMem)) {
			// We need to free hMem.
			defer win.GlobalFree(hMem)

			return lastError("SetClipboardData")
		}

		// The system now owns the memory referred to by hMem.

		return nil
	})
}
Beispiel #4
0
func (k Key) setStringValue(name string, valtype uint32, value string) error {
	v, err := syscall.UTF16FromString(value)
	if err != nil {
		return err
	}
	buf := (*[1 << 10]byte)(unsafe.Pointer(&v[0]))[:len(v)*2]
	return k.setValue(name, valtype, buf)
}
Beispiel #5
0
// convertToUTF16 converts the utf8 string to utf16
func convertToUTF16(a string) ([]byte, error) {
	u16, err := syscall.UTF16FromString(a)
	if err != nil {
		return nil, errors.Annotate(err, "Failed to convert string to UTF16")
	}
	buf := &bytes.Buffer{}
	if err := binary.Write(buf, binary.LittleEndian, u16); err != nil {
		return nil, errors.Annotate(err, "Failed to convert UTF16 to bytes")
	}
	return buf.Bytes(), nil
}
Beispiel #6
0
// OpenForBackup opens a file or directory, potentially skipping access checks if the backup
// or restore privileges have been acquired.
//
// If the file opened was a directory, it cannot be used with Readdir().
func OpenForBackup(path string, access uint32, share uint32, createmode uint32) (*os.File, error) {
	winPath, err := syscall.UTF16FromString(path)
	if err != nil {
		return nil, err
	}
	h, err := syscall.CreateFile(&winPath[0], access, share, nil, createmode, syscall.FILE_FLAG_BACKUP_SEMANTICS, 0)
	if err != nil {
		err = &os.PathError{Op: "open", Path: path, Err: err}
		return nil, err
	}
	return os.NewFile(uintptr(h), path), nil
}
Beispiel #7
0
func openFileOrDir(path string, mode uint32, createDisposition uint32) (file *os.File, err error) {
	winPath, err := syscall.UTF16FromString(path)
	if err != nil {
		return
	}
	h, err := syscall.CreateFile(&winPath[0], mode, syscall.FILE_SHARE_READ, nil, createDisposition, syscall.FILE_FLAG_BACKUP_SEMANTICS, 0)
	if err != nil {
		err = &os.PathError{"open", path, err}
		return
	}
	file = os.NewFile(uintptr(h), path)
	return
}
Beispiel #8
0
// newWatched creates a new watched instance. It splits the filter variable into
// two parts. The first part is responsible for watching all events which can be
// created for a file in watched directory structure and the second one watches
// only directory Create/Remove actions. If all operations succeed, the Create
// message is sent to I/O completion port queue for further processing.
func newWatched(cph syscall.Handle, filter uint32, recursive bool,
	path string) (wd *watched, err error) {
	wd = &watched{
		filter:    filter,
		recursive: recursive,
	}
	if wd.pathw, err = syscall.UTF16FromString(path); err != nil {
		return
	}
	if err = wd.recreate(cph); err != nil {
		return
	}
	return wd, nil
}
Beispiel #9
0
// SetPrefix sets the text that appears in the NumberEdit before the number.
func (ne *NumberEdit) SetPrefix(prefix string) error {
	p, err := syscall.UTF16FromString(prefix)
	if err != nil {
		return err
	}

	old := ne.edit.prefix
	ne.edit.prefix = p[:len(p)-1]

	if err := ne.edit.setTextFromValue(ne.edit.value); err != nil {
		ne.edit.prefix = old
		return err
	}

	return nil
}
Beispiel #10
0
// SetSuffix sets the text that appears in the NumberEdit after the number.
func (ne *NumberEdit) SetSuffix(suffix string) error {
	s, err := syscall.UTF16FromString(suffix)
	if err != nil {
		return err
	}

	old := ne.edit.suffix
	ne.edit.suffix = s[:len(s)-1]

	if err := ne.edit.setTextFromValue(ne.edit.value); err != nil {
		ne.edit.suffix = old
		return err
	}

	return nil
}
Beispiel #11
0
func toLong(path string) (string, error) {
	p, err := syscall.UTF16FromString(path)
	if err != nil {
		return "", err
	}
	b := p // GetLongPathName says we can reuse buffer
	n := uint32(len(b))
	for {
		n, err = syscall.GetLongPathName(&p[0], &b[0], uint32(len(b)))
		if err != nil {
			return "", err
		}
		if n <= uint32(len(b)) {
			return syscall.UTF16ToString(b[:n]), nil
		}
		b = make([]uint16, n)
	}
}
Beispiel #12
0
func toShort(path string) (string, error) {
	p, err := syscall.UTF16FromString(path)
	if err != nil {
		return "", err
	}
	b := p // GetShortPathName says we can reuse buffer
	n, err := syscall.GetShortPathName(&p[0], &b[0], uint32(len(b)))
	if err != nil {
		return "", err
	}
	if n > uint32(len(b)) {
		b = make([]uint16, n)
		if _, err = syscall.GetShortPathName(&p[0], &b[0], uint32(len(b))); err != nil {
			return "", err
		}
	}
	return syscall.UTF16ToString(b), nil
}
Beispiel #13
0
func (fg *fileGetCloserWithBackupPrivileges) Get(filename string) (io.ReadCloser, error) {
	var f *os.File
	// Open the file while holding the Windows backup privilege. This ensures that the
	// file can be opened even if the caller does not actually have access to it according
	// to the security descriptor.
	err := winio.RunWithPrivilege(winio.SeBackupPrivilege, func() error {
		path := longpath.AddPrefix(filepath.Join(fg.path, filename))
		p, err := syscall.UTF16FromString(path)
		if err != nil {
			return err
		}
		h, err := syscall.CreateFile(&p[0], syscall.GENERIC_READ, syscall.FILE_SHARE_READ, nil, syscall.OPEN_EXISTING, syscall.FILE_FLAG_BACKUP_SEMANTICS, 0)
		if err != nil {
			return &os.PathError{Op: "open", Path: path, Err: err}
		}
		f = os.NewFile(uintptr(h), path)
		return nil
	})
	return f, err
}
Beispiel #14
0
// longPath is copied over from the symlink package. This should be removed
// if we add it to gc or in some other convenience package
func longPath(path string) ([]uint16, error) {
	pathp, err := syscall.UTF16FromString(path)
	if err != nil {
		return nil, err
	}

	longp := pathp
	n, err := syscall.GetLongPathName(&pathp[0], &longp[0], uint32(len(longp)))
	if err != nil {
		return nil, err
	}
	if n > uint32(len(longp)) {
		longp = make([]uint16, n)
		n, err = syscall.GetLongPathName(&pathp[0], &longp[0], uint32(len(longp)))
		if err != nil {
			return nil, err
		}
	}
	longp = longp[:n]

	return longp, nil
}
Beispiel #15
0
// Adds the notification icon and starts handling the mouse
// interaction with the icon.
// Calls to this function will block until the Stop() function
// will be called from another goroutine/thread.
// Returns an error, if adding the notify icons fails.
func (t *_NotifyIcon) Start() (err error) {
	log.Println("Creating notification icon")

	tooltipUtf16, _ := syscall.UTF16FromString(t.tooltip)
	t.nid.CbSize = w32.DWORD(unsafe.Sizeof(&t.nid))
	t.nid.HWnd = t.hwnd
	t.nid.UFlags = _NIF_MESSAGE | _NIF_ICON | _NIF_TIP
	t.nid.UID = niUID
	t.nid.UCallbackMessage = niCallbackMessage
	copy(t.nid.SzTip[:], tooltipUtf16)
	err = shellNotifyIcon(_NIM_ADD, &t.nid)
	if err != nil {
		return
	}

	var msg w32.MSG
	for w32.GetMessage(&msg, t.hwnd, uint32(0), uint32(0)) != 0 {
		w32.TranslateMessage(&msg)
		w32.DispatchMessage(&msg)
	}
	return nil
}
Beispiel #16
0
// Get ansi string (current codepage multibyte string)
// from utf8(go-native) string
func UtoA(utf8 string) ([]byte, error) {
	utf16, err := syscall.UTF16FromString(utf8)
	if err != nil {
		return nil, err
	}
	size, _, _ := wideCharToMultiByte.Call(CP_THREAD_ACP, 0,
		uintptr(unsafe.Pointer(&utf16[0])),
		uintptr(len(utf16)),
		uintptr(0), 0, uintptr(0), uintptr(0))
	if size <= 0 {
		return nil, syscall.GetLastError()
	}
	mbcs := make([]byte, size)
	rc, _, _ := wideCharToMultiByte.Call(CP_THREAD_ACP, 0,
		uintptr(unsafe.Pointer(&utf16[0])),
		uintptr(len(utf16)),
		uintptr(unsafe.Pointer(&mbcs[0])), size, uintptr(0), uintptr(0))
	if rc == 0 {
		return nil, syscall.GetLastError()
	}
	return mbcs, nil
}
Beispiel #17
0
func InjectDll(d *SubprocessData, loadLibraryW uintptr, dll string) error {
	if int(loadLibraryW) == 0 {
		return nil
	}

	ec := tools.ErrorContext("InjectDll")

	log.Debug("InjectDll: Injecting library %s with call to %d", dll, loadLibraryW)
	name, err := syscall.UTF16FromString(dll)
	if err != nil {
		return ec.NewError(err, ERR_USER, "UTF16FromString")
	}
	nameLen := uint32((len(name) + 1) * 2)
	remoteName, err := win32.VirtualAllocEx(d.platformData.hProcess, 0, nameLen, win32.MEM_COMMIT, win32.PAGE_READWRITE)
	if err != nil {
		return ec.NewError(err)
	}
	defer win32.VirtualFreeEx(d.platformData.hProcess, remoteName, 0, win32.MEM_RELEASE)

	_, err = win32.WriteProcessMemory(d.platformData.hProcess, remoteName, unsafe.Pointer(&name[0]), nameLen)
	if err != nil {
		return ec.NewError(err)
	}
	thread, _, err := win32.CreateRemoteThread(d.platformData.hProcess, win32.MakeInheritSa(), 0, loadLibraryW, remoteName, 0)
	if err != nil {
		return ec.NewError(err)
	}
	defer syscall.CloseHandle(thread)
	wr, err := syscall.WaitForSingleObject(thread, syscall.INFINITE)
	if err != nil {
		return ec.NewError(os.NewSyscallError("WaitForSingleObject", err))
	}
	if wr != syscall.WAIT_OBJECT_0 {
		return ec.NewError(fmt.Errorf("Unexpected wait result %s", wr))
	}

	return nil
}
Beispiel #18
0
func RegSetString(hKey HKEY, subKey string, value string) (errno int) {
	var lptr, vptr unsafe.Pointer
	if len(subKey) > 0 {
		lptr = unsafe.Pointer(syscall.StringToUTF16Ptr(subKey))
	}
	var buf []uint16
	if len(value) > 0 {
		buf, err := syscall.UTF16FromString(value)
		if err != nil {
			return ERROR_BAD_FORMAT
		}
		vptr = unsafe.Pointer(&buf[0])
	}
	ret, _, _ := procRegSetValueEx.Call(
		uintptr(hKey),
		uintptr(lptr),
		uintptr(0),
		uintptr(REG_SZ),
		uintptr(vptr),
		uintptr(unsafe.Sizeof(buf)+2)) // 2 is the size of the terminating null character

	return int(ret)
}
Beispiel #19
0
// CreateRenderContext creates a render context. Close must be called on
// returned EvtHandle when finished with the handle.
func CreateRenderContext(valuePaths []string, flag EvtRenderContextFlag) (EvtHandle, error) {
	var paths []uintptr
	for _, path := range valuePaths {
		utf16, err := syscall.UTF16FromString(path)
		if err != nil {
			return 0, err
		}

		paths = append(paths, reflect.ValueOf(&utf16[0]).Pointer())
	}

	var pathsAddr uintptr
	if len(paths) > 0 {
		pathsAddr = reflect.ValueOf(&paths[0]).Pointer()
	}

	context, err := _EvtCreateRenderContext(uint32(len(paths)), pathsAddr, flag)
	if err != nil {
		return 0, err
	}

	return context, nil
}
Beispiel #20
0
func SetTitle(title string) {
	ctitle, err := syscall.UTF16FromString(title)
	if ctitle != nil && err == nil {
		setConsoleTitle.Call(uintptr(unsafe.Pointer(&ctitle[0])))
	}
}
Beispiel #21
0
// strUTF16 converts a Go string into a utf16 byte sequence
func strUTF16(s string) (utf16, error) {
	return syscall.UTF16FromString(s)
}
Beispiel #22
0
func (d *Driver) create(id, parent, mountLabel string, readOnly bool, storageOpt map[string]string) error {
	if len(storageOpt) != 0 {
		return fmt.Errorf("--storage-opt is not supported for windows")
	}

	rPId, err := d.resolveID(parent)
	if err != nil {
		return err
	}

	parentChain, err := d.getLayerChain(rPId)
	if err != nil {
		return err
	}

	var layerChain []string

	if rPId != "" {
		parentPath, err := hcsshim.GetLayerMountPath(d.info, rPId)
		if err != nil {
			return err
		}
		if _, err := os.Stat(filepath.Join(parentPath, "Files")); err == nil {
			// This is a legitimate parent layer (not the empty "-init" layer),
			// so include it in the layer chain.
			layerChain = []string{parentPath}
		}
	}

	layerChain = append(layerChain, parentChain...)

	if readOnly {
		if err := hcsshim.CreateLayer(d.info, id, rPId); err != nil {
			return err
		}
	} else {
		var parentPath string
		if len(layerChain) != 0 {
			parentPath = layerChain[0]
		}

		if isTP5OrOlder() {
			// Pre-create the layer directory, providing an ACL to give the Hyper-V Virtual Machines
			// group access. This is necessary to ensure that Hyper-V containers can access the
			// virtual machine data. This is not necessary post-TP5.
			path, err := syscall.UTF16FromString(filepath.Join(d.info.HomeDir, id))
			if err != nil {
				return err
			}
			// Give system and administrators full control, and VMs read, write, and execute.
			// Mark these ACEs as inherited.
			sd, err := winio.SddlToSecurityDescriptor("D:(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FRFWFX;;;S-1-5-83-0)")
			if err != nil {
				return err
			}
			err = syscall.CreateDirectory(&path[0], &syscall.SecurityAttributes{
				Length:             uint32(unsafe.Sizeof(syscall.SecurityAttributes{})),
				SecurityDescriptor: uintptr(unsafe.Pointer(&sd[0])),
			})
			if err != nil {
				return err
			}
		}

		if err := hcsshim.CreateSandboxLayer(d.info, id, parentPath, layerChain); err != nil {
			return err
		}
	}

	if _, err := os.Lstat(d.dir(parent)); err != nil {
		if err2 := hcsshim.DestroyLayer(d.info, id); err2 != nil {
			logrus.Warnf("Failed to DestroyLayer %s: %s", id, err2)
		}
		return fmt.Errorf("Cannot create layer with missing parent %s: %s", parent, err)
	}

	if err := d.setLayerChain(id, layerChain); err != nil {
		if err2 := hcsshim.DestroyLayer(d.info, id); err2 != nil {
			logrus.Warnf("Failed to DestroyLayer %s: %s", id, err2)
		}
		return err
	}

	return nil
}