-
Notifications
You must be signed in to change notification settings - Fork 14
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feature: skip image download if it exists #447
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -10,16 +10,13 @@ package secureagent | |
|
||
import ( | ||
"bytes" | ||
"crypto/tls" | ||
"crypto/x509" | ||
"encoding/asn1" | ||
"encoding/base64" | ||
"encoding/json" | ||
"errors" | ||
"fmt" | ||
"io" | ||
"log" | ||
"net/http" | ||
"net/url" | ||
"os" | ||
"os/exec" | ||
|
@@ -181,88 +178,106 @@ func (a *Agent) doRequestBootstrapServerOnboardingInfo() error { | |
return errri | ||
} | ||
|
||
//nolint:funlen | ||
func (a *Agent) downloadAndValidateImage() error { | ||
log.Printf("[INFO] Starting the Download Image: %v", a.BootstrapServerOnboardingInfo.IetfSztpConveyedInfoOnboardingInformation.BootImage.DownloadURI) | ||
_ = a.doReportProgress(ProgressTypeBootImageInitiated, "BootImage Initiated") | ||
// Download the image from DownloadURI and save it to a file | ||
a.BootstrapServerOnboardingInfo.IetfSztpConveyedInfoOnboardingInformation.InfoTimestampReference = fmt.Sprintf("%8d", time.Now().Unix()) | ||
for i, item := range a.BootstrapServerOnboardingInfo.IetfSztpConveyedInfoOnboardingInformation.BootImage.DownloadURI { | ||
// TODO: maybe need to file download to a function in util.go | ||
log.Printf("[INFO] Downloading Image %v", item) | ||
// Create a empty file | ||
file, err := os.Create(ARTIFACTS_PATH + a.BootstrapServerOnboardingInfo.IetfSztpConveyedInfoOnboardingInformation.InfoTimestampReference + filepath.Base(item)) | ||
if err != nil { | ||
return err | ||
} | ||
func (a *Agent) downloadArtifact(uri string) (*os.File, error) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. should |
||
file, err := os.CreateTemp("", filepath.Base(uri)) | ||
|
||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
caCert, _ := os.ReadFile(a.GetBootstrapTrustAnchorCert()) | ||
caCertPool := x509.NewCertPool() | ||
caCertPool.AppendCertsFromPEM(caCert) | ||
cert, _ := tls.LoadX509KeyPair(a.GetDeviceEndEntityCert(), a.GetDevicePrivateKey()) | ||
response, err := a.HttpClient.Get(uri) | ||
if err != nil { | ||
return nil, err | ||
} | ||
sizeorigin, _ := strconv.Atoi(response.Header.Get("Content-Length")) | ||
downloadSize := int64(sizeorigin) | ||
log.Printf("[INFO] Downloading the image with size: %v", downloadSize) | ||
|
||
check := http.Client{ | ||
CheckRedirect: func(r *http.Request, _ []*http.Request) error { | ||
r.URL.Opaque = r.URL.Path | ||
return nil | ||
}, | ||
Transport: &http.Transport{ | ||
TLSClientConfig: &tls.Config{ | ||
//nolint:gosec | ||
InsecureSkipVerify: true, // TODO: remove skip verify | ||
RootCAs: caCertPool, | ||
Certificates: []tls.Certificate{cert}, | ||
}, | ||
}, | ||
if response.StatusCode != 200 { | ||
return nil, errors.New("received non 200 response code") | ||
} | ||
size, err := io.Copy(file, response.Body) | ||
if err != nil { | ||
return nil, err | ||
} | ||
defer func() { | ||
if err := file.Close(); err != nil { | ||
log.Println("[ERROR] Error when closing:", err) | ||
} | ||
}() | ||
defer func() { | ||
if err := response.Body.Close(); err != nil { | ||
log.Println("[ERROR] Error when closing:", err) | ||
} | ||
}() | ||
log.Printf("[INFO] Downloaded file: %s with size: %d", file.Name(), size) | ||
return file, nil | ||
} | ||
|
||
func (a *Agent) validateImage(filePath string, algorithm string, expected string) error { | ||
switch algorithm { | ||
case "ietf-sztp-conveyed-info:sha-256": | ||
checksum, err := calculateSHA256File(filePath) | ||
|
||
response, err := check.Get(item) | ||
if err != nil { | ||
return err | ||
log.Println("[ERROR] Could not calculate checksum", err) | ||
} | ||
log.Println("calculated: " + checksum) | ||
log.Println("expected : " + expected) | ||
|
||
sizeorigin, _ := strconv.Atoi(response.Header.Get("Content-Length")) | ||
downloadSize := int64(sizeorigin) | ||
log.Printf("[INFO] Downloading the image with size: %v", downloadSize) | ||
|
||
if response.StatusCode != 200 { | ||
return errors.New("received non 200 response code") | ||
if checksum != expected { | ||
return errors.New("checksum mismatch") | ||
} | ||
size, err := io.Copy(file, response.Body) | ||
if err != nil { | ||
return err | ||
log.Println("[INFO] Checksum verified successfully") | ||
return nil | ||
default: | ||
return errors.New("unsupported hash algorithm") | ||
} | ||
} | ||
|
||
func (a *Agent) artifactExists(item string, algorithm string, expected string) bool { | ||
filePath := ARTIFACTS_PATH + filepath.Base(item) | ||
_, err := os.Stat(filePath) | ||
if err != nil { | ||
return false | ||
} | ||
err = a.validateImage(filePath, algorithm, expected) | ||
return err == nil | ||
} | ||
|
||
//nolint:funlen | ||
func (a *Agent) downloadAndValidateImage() error { | ||
bootImage := a.BootstrapServerOnboardingInfo.IetfSztpConveyedInfoOnboardingInformation.BootImage | ||
log.Printf("[INFO] Starting the Download Image: %v", bootImage.DownloadURI) | ||
_ = a.doReportProgress(ProgressTypeBootImageInitiated, "BootImage Initiated") | ||
// Download the image from DownloadURI and save it to a file | ||
for i, item := range bootImage.DownloadURI { | ||
if len(bootImage.ImageVerification) <= i { | ||
return errors.New("invalid verification") | ||
} | ||
defer func() { | ||
if err := file.Close(); err != nil { | ||
log.Println("[ERROR] Error when closing:", err) | ||
} | ||
}() | ||
defer func() { | ||
if err := response.Body.Close(); err != nil { | ||
log.Println("[ERROR] Error when closing:", err) | ||
} | ||
}() | ||
|
||
log.Printf("[INFO] Downloaded file: %s with size: %d", ARTIFACTS_PATH+a.BootstrapServerOnboardingInfo.IetfSztpConveyedInfoOnboardingInformation.InfoTimestampReference+filepath.Base(item), size) | ||
log.Println("[INFO] Verify the file checksum: ", ARTIFACTS_PATH+a.BootstrapServerOnboardingInfo.IetfSztpConveyedInfoOnboardingInformation.InfoTimestampReference+filepath.Base(item)) | ||
switch a.BootstrapServerOnboardingInfo.IetfSztpConveyedInfoOnboardingInformation.BootImage.ImageVerification[i].HashAlgorithm { | ||
case "ietf-sztp-conveyed-info:sha-256": | ||
filePath := ARTIFACTS_PATH + a.BootstrapServerOnboardingInfo.IetfSztpConveyedInfoOnboardingInformation.InfoTimestampReference + filepath.Base(item) | ||
checksum, err := calculateSHA256File(filePath) | ||
original := strings.ReplaceAll(a.BootstrapServerOnboardingInfo.IetfSztpConveyedInfoOnboardingInformation.BootImage.ImageVerification[i].HashValue, ":", "") | ||
imageVerification := bootImage.ImageVerification[i] | ||
expected := strings.ReplaceAll(imageVerification.HashValue, ":", "") | ||
algorithm := imageVerification.HashAlgorithm | ||
|
||
if a.artifactExists(item, algorithm, expected) { | ||
log.Printf("[INFO] Image %v already exists", item) | ||
} else { | ||
log.Printf("[INFO] Downloading Image %v", item) | ||
file, err := a.downloadArtifact(item) | ||
if err != nil { | ||
log.Println("[ERROR] Could not calculate checksum", err) | ||
return err | ||
} | ||
log.Println("calculated: " + checksum) | ||
log.Println("expected : " + original) | ||
if checksum != original { | ||
return errors.New("checksum mismatch") | ||
log.Println("[INFO] Verify the file checksum: ", file.Name()) | ||
err = a.validateImage(file.Name(), algorithm, expected) | ||
if err != nil { | ||
return err | ||
} | ||
log.Println("[INFO] Checksum verified successfully") | ||
|
||
log.Printf("[INFO] Moving file %s to %s", file.Name(), ARTIFACTS_PATH+filepath.Base(item)) | ||
_ = os.Rename(file.Name(), ARTIFACTS_PATH+filepath.Base(item)) | ||
_ = a.doReportProgress(ProgressTypeBootImageComplete, "BootImage Complete") | ||
|
||
return nil | ||
default: | ||
return errors.New("unsupported hash algorithm") | ||
} | ||
} | ||
return nil | ||
|
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Check failure
Code scanning / CodeQL
Disabled TLS certificate check High
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@glimchb Should I remove this?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@h0lyalg0rithm we have a separate issue for this #341 if you remove it it will fail CI/CD.. need to fix server certs