github.com/google/fleetspeak@v0.1.15-0.20240426164851-4f31f62c1aea/fleetspeak/src/windows/hashpipe/hashpipe_windows.go (about)

     1  // Copyright 2017 Google Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     https://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  //go:build windows
    16  
    17  // Package hashpipe implements a name randomization mechanism over Windows
    18  // named pipes.
    19  package hashpipe
    20  
    21  import (
    22  	"crypto/rand"
    23  	"encoding/base64"
    24  	"fmt"
    25  	"net"
    26  
    27  	"github.com/Microsoft/go-winio"
    28  )
    29  
    30  // ListenPipe refines winio.ListenPipe by providing a crypto-secure random name
    31  // for the pipe and returning the name alongside the normal net.Listener.
    32  func ListenPipe(c *winio.PipeConfig) (l net.Listener, path string, err error) {
    33  	if path, err = randomizePath(); err != nil {
    34  		return
    35  	}
    36  
    37  	l, err = winio.ListenPipe(path, c)
    38  	return
    39  }
    40  
    41  func randomizePath() (string, error) {
    42  	// 96 bytes of information gives us 128 base-64 characters. Windows named
    43  	// pipes support paths of up to 256 characters. See:
    44  	// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365783(v=vs.85).aspx
    45  	randBuf := make([]byte, 96)
    46  
    47  	if n, err := rand.Read(randBuf); err != nil {
    48  		return "", fmt.Errorf("error in rand.Read (%d bytes read): %v", n, err)
    49  	}
    50  
    51  	randB64String := base64.URLEncoding.EncodeToString(randBuf)
    52  
    53  	pipePath := `\\.\pipe\` + randB64String
    54  	return pipePath, nil
    55  }