github.com/imannamdari/v2ray-core/v5@v5.0.5/common/platform/securedload/embeddedhash.go (about)

     1  package securedload
     2  
     3  import (
     4  	"bytes"
     5  	"crypto/sha256"
     6  	"encoding/hex"
     7  	"path/filepath"
     8  	"strings"
     9  
    10  	"github.com/v2fly/VSign/insmgr"
    11  	"github.com/v2fly/VSign/signerVerify"
    12  
    13  	"github.com/imannamdari/v2ray-core/v5/common/platform"
    14  	"github.com/imannamdari/v2ray-core/v5/common/platform/filesystem"
    15  )
    16  
    17  type EmbeddedHashProtectedLoader struct {
    18  	checkedFile map[string]string
    19  }
    20  
    21  func (e EmbeddedHashProtectedLoader) VerifyAndLoad(filename string) ([]byte, error) {
    22  	platformFileName := filepath.FromSlash(filename)
    23  	fileContent, err := filesystem.ReadFile(platform.GetAssetLocation(platformFileName))
    24  	if err != nil {
    25  		return nil, newError("Cannot find file", filename).Base(err)
    26  	}
    27  	fileHash := sha256.Sum256(fileContent)
    28  	fileHashAsString := hex.EncodeToString(fileHash[:])
    29  	if fileNameVerified, ok := e.checkedFile[fileHashAsString]; ok {
    30  		for _, filenameVerifiedIndividual := range strings.Split(fileNameVerified, ";") {
    31  			if strings.HasSuffix(filenameVerifiedIndividual, filename) {
    32  				return fileContent, nil
    33  			}
    34  		}
    35  	}
    36  	return nil, newError("Unrecognized file at ", filename, " can not be loaded for execution")
    37  }
    38  
    39  func NewEmbeddedHashProtectedLoader() *EmbeddedHashProtectedLoader {
    40  	instructions := insmgr.ReadAllIns(bytes.NewReader([]byte(allowedHashes)))
    41  	checkedFile, _, ok := signerVerify.CheckAsClient(instructions, "v2fly", true)
    42  	if !ok {
    43  		panic("Embedded Hash data is invalid")
    44  	}
    45  	return &EmbeddedHashProtectedLoader{checkedFile: checkedFile}
    46  }
    47  
    48  func init() {
    49  	RegisterProtectedLoader("embedded", NewEmbeddedHashProtectedLoader())
    50  }