You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@cloudstack.apache.org by "andrijapanicsb (via GitHub)" <gi...@apache.org> on 2026/06/02 11:37:43 UTC

[PR] Support FIPS-compatible API signing [cloudstack-cloudmonkey]

andrijapanicsb opened a new pull request, #213:
URL: https://github.com/apache/cloudstack-cloudmonkey/pull/213

   # Support FIPS-compatible API request signing in CloudMonkey
   
   ## Summary
   
   This change adds support for CloudStack API key request signing with `HmacSHA512`, while preserving compatibility with older CloudStack deployments that still require or allow `HmacSHA1`.
   
   CloudMonkey profiles now support a profile-level `signaturealgorithm` setting:
   
   - `auto`
   - `HmacSHA512`
   - `HmacSHA1`
   
   New and migrated profiles default to `auto`. In `auto` mode, CloudMonkey probes the active endpoint with the read-only `listApis` API, trying `HmacSHA512` first and falling back to `HmacSHA1` only if the SHA-512 probe fails authentication/signature verification. Once a probe succeeds, the concrete algorithm is persisted to the active profile before the user-requested API command is executed.
   
   This avoids retrying user-requested APIs directly and prevents duplicate execution of state-changing commands during signature algorithm detection.
   
   ## Motivation
   
   When legacy algorithms are disabled, CloudStack rejects API requests signed with `HmacSHA1` and accepts modern `HmacSHA512` signatures. CloudMonkey previously signed API key requests with `HmacSHA1` only, so API key authentication failed against such deployments.
   
   This change allows CloudMonkey to work with FIPS-compatible CloudStack environments while keeping existing legacy deployments usable without manual trial and error.
   
   ## Behavior
   
   ### New or migrated profiles
   
   If `signaturealgorithm` is absent from an existing profile, CloudMonkey writes:
   
   ```ini
   signaturealgorithm = auto
   ```
   
   ### Auto detection
   
   When API key and secret key authentication is used and the active profile is set to `auto`, CloudMonkey:
   
   1. Sends a read-only `listApis listall=true` probe signed with `HmacSHA512`.
   2. If that succeeds, persists:
   
      ```ini
      signaturealgorithm = HmacSHA512
      ```
   
   3. If SHA-512 fails authentication/signature verification, retries the same read-only probe with `HmacSHA1`.
   4. If SHA-1 succeeds, persists:
   
      ```ini
      signaturealgorithm = HmacSHA1
      ```
   
   5. Executes the original user-requested API only after detection has completed.
   
   ### Explicit configuration
   
   If a profile explicitly sets `HmacSHA512` or `HmacSHA1`, CloudMonkey uses only that configured algorithm and does not silently fall back.
   
   ### Prompt indicator
   
   Profiles using `HmacSHA512` show a `-fips` marker in the interactive prompt. For example:
   
   ```text
   (localcloud-fips) cmk >
   ```
   
   The marker indicates that CloudMonkey is using the FIPS-compatible CloudStack API signing algorithm. It does not imply full end-to-end FIPS validation of the local environment.
   
   ### Debug logging
   
   Auto-detection probe attempts are logged only when debug mode is enabled. Normal interactive output is not noisy when fallback succeeds.
   
   Debug output includes which signature algorithm probe is attempted, which probe fails, and which algorithm is selected.
   
   ## Testing
   
   Automated tests added:
   
   - `HmacSHA1` signature generation against a fixed request string
   - `HmacSHA512` signature generation against a fixed request string
   - default profile uses `signaturealgorithm = auto`
   - missing `signaturealgorithm` is migrated to `auto`
   - explicit `HmacSHA512` does not silently try `HmacSHA1`
   - `auto` persists `HmacSHA512` when the SHA-512 probe succeeds
   - `auto` falls back and persists `HmacSHA1` when SHA-512 fails but SHA-1 succeeds
   - `auto` does not retry the user-requested API directly, avoiding duplicate execution risk for state-changing APIs
   - prompt shows `-fips` when the active profile uses `HmacSHA512`
   
   Command run:
   
   ```text
   go test ./...
   ```
   
   ## Lab verification
   
   Verified against a CloudStack lab environment.
   
   With legacy algorithms enabled:
   
   ```text
   api.legacy.algorithm.supported=true
   ```
   
   - `auto` selected and persisted `HmacSHA512`
   - read-only `sync` succeeded and discovered 878 APIs
   
   With legacy algorithms disabled:
   
   ```text
   api.legacy.algorithm.supported=false
   ```
   
   Control checks:
   
   - forced `signaturealgorithm = HmacSHA1` failed with HTTP 401 signature verification error
   - forced `signaturealgorithm = HmacSHA512` succeeded
   - `signaturealgorithm = auto` succeeded and persisted `HmacSHA512`
   
   Observed result:
   
   ```text
   forced HmacSHA1:
   HTTP 401: unable to verify user credentials and/or request signature
   
   forced HmacSHA512:
   Discovered 878 APIs
   
   auto detection:
   Discovered 878 APIs
   signaturealgorithm = HmacSHA512
   ```
   
   ## Performance note
   
   I also compared SHA-1 and SHA-512 signing overhead during local validation.
   
   Local signer-only measurement showed SHA-512 signing is slower than SHA-1 in isolation, but still on the order of **microseconds** per request. Lab API request latency was dominated by network and CloudStack server round-trip time, with no meaningful API-level bottleneck observed from using `HmacSHA512`.
   
   Benchmark tooling and result artifacts are not included in this PR.
   
   ## Compatibility
   
   - Existing profiles without `signaturealgorithm` migrate to `auto`.
   - Older CloudStack deployments that only support `HmacSHA1` remain supported through auto fallback or explicit `HmacSHA1` configuration.
   - CloudStack deployments with legacy algorithms disabled are supported through `HmacSHA512`.
   - Username/password session authentication is not changed.
   
   ## Notes
   
   The detection probe intentionally uses `listApis` before executing the user-requested API so that state-changing APIs are not retried as part of algorithm detection.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@cloudstack.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Support FIPS-compatible API signing [cloudstack-cloudmonkey]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #213:
URL: https://github.com/apache/cloudstack-cloudmonkey/pull/213#discussion_r3341029529


##########
cmd/network.go:
##########
@@ -218,6 +219,195 @@ func encodeRequestParams(params url.Values) string {
 	return buf.String()
 }
 
+func cloneRequestParams(params url.Values) url.Values {
+	cloned := make(url.Values)
+	for key, values := range params {
+		for _, value := range values {
+			cloned.Add(key, value)
+		}
+	}
+	return cloned
+}
+
+func buildAPIRequestParams(r *Request, api string, args []string) url.Values {
+	params := make(url.Values)
+	params.Add("command", api)
+	apiData := r.Config.GetCache()[api]
+	for _, arg := range args {
+		if apiData != nil {
+			skip := false
+			for _, fakeArg := range apiData.FakeArgs {
+				if strings.HasPrefix(arg, fakeArg) {
+					skip = true
+					break
+				}
+			}
+			if skip {
+				continue
+			}
+
+		}
+		parts := strings.SplitN(arg, "=", 2)
+		if len(parts) == 2 {
+			key := parts[0]
+			value := parts[1]
+			if strings.HasPrefix(value, "\"") && strings.HasSuffix(value, "\"") {
+				value = value[1 : len(value)-1]
+			}
+			if strings.HasPrefix(value, "@") {
+				possibleFileName := value[1:]
+				if fileInfo, err := os.Stat(possibleFileName); err == nil && !fileInfo.IsDir() {
+					bytes, err := ioutil.ReadFile(possibleFileName)
+					config.Debug()
+					if err == nil {
+						value = string(bytes)
+						config.Debug("Content for argument ", key, " read from file: ", possibleFileName, " is: ", value)
+					}
+				}
+			}
+			params.Add(key, value)
+		}
+	}
+	signatureversion := "3"
+	expiresKey := "expires"
+	params.Add("response", "json")
+	params.Add("signatureversion", signatureversion)
+	params.Add(expiresKey, time.Now().UTC().Add(15*time.Minute).Format(time.RFC3339))
+	return params
+}
+
+func signRequest(unsignedRequest, secretKey, algorithm string) (string, error) {
+	signatureAlgorithm, err := config.NormalizeSignatureAlgorithm(algorithm)
+	if err != nil {
+		return "", err
+	}
+
+	var signature []byte
+	switch signatureAlgorithm {
+	case config.SignatureAlgorithmHmacSHA1:
+		mac := hmac.New(sha1.New, []byte(secretKey))
+		mac.Write([]byte(strings.ToLower(unsignedRequest)))
+		signature = mac.Sum(nil)
+	case config.SignatureAlgorithmHmacSHA512:
+		mac := hmac.New(sha512.New, []byte(secretKey))
+		mac.Write([]byte(strings.ToLower(unsignedRequest)))
+		signature = mac.Sum(nil)
+	default:
+		return "", errors.New("signature algorithm must be concrete")
+	}
+	return base64.StdEncoding.EncodeToString(signature), nil
+}
+
+func executeSignedAPIRequest(r *Request, unsignedParams url.Values, algorithm string) (*http.Response, error) {
+	params := cloneRequestParams(unsignedParams)
+	encodedParams := encodeRequestParams(params)
+
+	signature, err := signRequest(encodedParams, r.Config.ActiveProfile.SecretKey, algorithm)
+	if err != nil {
+		return nil, err
+	}
+	if r.Config.Core.PostRequest {
+		params.Add("signature", signature)
+	} else {
+		encodedParams = encodedParams + fmt.Sprintf("&signature=%s", url.QueryEscape(signature))
+		params = nil
+	}
+
+	requestURL := fmt.Sprintf("%s?%s", r.Config.ActiveProfile.URL, encodedParams)
+	config.Debug("NewAPIRequest API request URL:", requestURL)
+	return executeRequest(r, requestURL, params)
+}
+
+func parseAPIResponse(body []byte) (map[string]interface{}, error) {
+	var data map[string]interface{}
+	if err := json.Unmarshal(body, &data); err != nil {
+		return nil, errors.New("failed to decode response")
+	}
+
+	if apiResponse := getResponseData(data); apiResponse != nil {
+		if _, ok := apiResponse["errorcode"]; ok {
+			return nil, fmt.Errorf("(HTTP %v, error code %v) %v", apiResponse["errorcode"], apiResponse["cserrorcode"], apiResponse["errortext"])
+		}
+		return apiResponse, nil
+	}
+
+	return nil, errors.New("failed to decode response")
+}
+
+func isAuthenticationFailure(statusCode int, err error) bool {
+	if statusCode == http.StatusUnauthorized || statusCode == http.StatusForbidden {
+		return true
+	}
+	if err == nil {
+		return false
+	}
+	errText := strings.ToLower(err.Error())
+	for _, marker := range []string{"signature", "authenticate", "authentication", "credential", "unauthoriz", "api key", "apikey"} {
+		if strings.Contains(errText, marker) {
+			return true
+		}
+	}
+	return false
+}
+
+func persistDetectedSignatureAlgorithm(r *Request, algorithm string) {
+	r.Config.ActiveProfile.SignatureAlgorithm = algorithm
+	if r.CredentialsSupplied {
+		config.Debug("Credentials supplied on command-line, not persisting detected signature algorithm")
+		return
+	}
+	r.Config.UpdateConfig("signaturealgorithm", algorithm, true)
+}
+
+func detectSignatureAlgorithm(r *Request) (string, error) {
+	attempts := []string{config.SignatureAlgorithmHmacSHA512, config.SignatureAlgorithmHmacSHA1}
+	var lastErr error
+
+	for _, algorithm := range attempts {
+		config.Debug("Trying API signature algorithm probe:", algorithm)
+		params := buildAPIRequestParams(r, "listApis", []string{"listall=true"})
+		params.Add("apiKey", r.Config.ActiveProfile.APIKey)
+		response, err := executeSignedAPIRequest(r, params, algorithm)
+		if err != nil {
+			config.Debug("API signature algorithm probe failed before response for ", algorithm, ": ", err)
+			lastErr = err
+			continue
+		}
+
+		body, _ := ioutil.ReadAll(response.Body)
+		config.Debug("Signature algorithm probe response body:", string(body))
+		if _, err := parseAPIResponse(body); err == nil {

Review Comment:
   The signature algorithm probe reads the response body without closing it and ignores potential read errors. This can leak HTTP connections and hide IO failures during autodetection.



##########
cmd/network.go:
##########
@@ -384,27 +530,26 @@ func NewAPIRequest(r *Request, api string, args []string, isAsync bool) (map[str
 		}
 	}
 
+	return processAPIResponse(r, response, isAsync)
+}
+
+func processAPIResponse(r *Request, response *http.Response, isAsync bool) (map[string]interface{}, error) {
 	body, _ := ioutil.ReadAll(response.Body)
 	config.Debug("NewAPIRequest response body:", string(body))

Review Comment:
   processAPIResponse reads the response body without closing it and ignores any ReadAll error. This can leak HTTP connections and make failures harder to diagnose.



##########
cmd/network.go:
##########
@@ -218,6 +219,195 @@ func encodeRequestParams(params url.Values) string {
 	return buf.String()
 }
 
+func cloneRequestParams(params url.Values) url.Values {
+	cloned := make(url.Values)
+	for key, values := range params {
+		for _, value := range values {
+			cloned.Add(key, value)
+		}
+	}
+	return cloned
+}
+
+func buildAPIRequestParams(r *Request, api string, args []string) url.Values {
+	params := make(url.Values)
+	params.Add("command", api)
+	apiData := r.Config.GetCache()[api]
+	for _, arg := range args {
+		if apiData != nil {
+			skip := false
+			for _, fakeArg := range apiData.FakeArgs {
+				if strings.HasPrefix(arg, fakeArg) {
+					skip = true
+					break
+				}
+			}
+			if skip {
+				continue
+			}
+
+		}
+		parts := strings.SplitN(arg, "=", 2)
+		if len(parts) == 2 {
+			key := parts[0]
+			value := parts[1]
+			if strings.HasPrefix(value, "\"") && strings.HasSuffix(value, "\"") {
+				value = value[1 : len(value)-1]
+			}
+			if strings.HasPrefix(value, "@") {
+				possibleFileName := value[1:]
+				if fileInfo, err := os.Stat(possibleFileName); err == nil && !fileInfo.IsDir() {
+					bytes, err := ioutil.ReadFile(possibleFileName)
+					config.Debug()
+					if err == nil {
+						value = string(bytes)
+						config.Debug("Content for argument ", key, " read from file: ", possibleFileName, " is: ", value)
+					}
+				}
+			}
+			params.Add(key, value)
+		}
+	}
+	signatureversion := "3"
+	expiresKey := "expires"
+	params.Add("response", "json")
+	params.Add("signatureversion", signatureversion)
+	params.Add(expiresKey, time.Now().UTC().Add(15*time.Minute).Format(time.RFC3339))
+	return params
+}
+
+func signRequest(unsignedRequest, secretKey, algorithm string) (string, error) {
+	signatureAlgorithm, err := config.NormalizeSignatureAlgorithm(algorithm)
+	if err != nil {
+		return "", err
+	}
+
+	var signature []byte
+	switch signatureAlgorithm {
+	case config.SignatureAlgorithmHmacSHA1:
+		mac := hmac.New(sha1.New, []byte(secretKey))
+		mac.Write([]byte(strings.ToLower(unsignedRequest)))
+		signature = mac.Sum(nil)
+	case config.SignatureAlgorithmHmacSHA512:
+		mac := hmac.New(sha512.New, []byte(secretKey))
+		mac.Write([]byte(strings.ToLower(unsignedRequest)))
+		signature = mac.Sum(nil)
+	default:
+		return "", errors.New("signature algorithm must be concrete")
+	}
+	return base64.StdEncoding.EncodeToString(signature), nil
+}
+
+func executeSignedAPIRequest(r *Request, unsignedParams url.Values, algorithm string) (*http.Response, error) {
+	params := cloneRequestParams(unsignedParams)
+	encodedParams := encodeRequestParams(params)
+
+	signature, err := signRequest(encodedParams, r.Config.ActiveProfile.SecretKey, algorithm)
+	if err != nil {
+		return nil, err
+	}
+	if r.Config.Core.PostRequest {
+		params.Add("signature", signature)
+	} else {
+		encodedParams = encodedParams + fmt.Sprintf("&signature=%s", url.QueryEscape(signature))
+		params = nil
+	}
+
+	requestURL := fmt.Sprintf("%s?%s", r.Config.ActiveProfile.URL, encodedParams)
+	config.Debug("NewAPIRequest API request URL:", requestURL)
+	return executeRequest(r, requestURL, params)
+}
+
+func parseAPIResponse(body []byte) (map[string]interface{}, error) {
+	var data map[string]interface{}
+	if err := json.Unmarshal(body, &data); err != nil {
+		return nil, errors.New("failed to decode response")
+	}
+
+	if apiResponse := getResponseData(data); apiResponse != nil {
+		if _, ok := apiResponse["errorcode"]; ok {
+			return nil, fmt.Errorf("(HTTP %v, error code %v) %v", apiResponse["errorcode"], apiResponse["cserrorcode"], apiResponse["errortext"])
+		}
+		return apiResponse, nil
+	}
+
+	return nil, errors.New("failed to decode response")
+}
+
+func isAuthenticationFailure(statusCode int, err error) bool {
+	if statusCode == http.StatusUnauthorized || statusCode == http.StatusForbidden {
+		return true
+	}
+	if err == nil {
+		return false
+	}
+	errText := strings.ToLower(err.Error())
+	for _, marker := range []string{"signature", "authenticate", "authentication", "credential", "unauthoriz", "api key", "apikey"} {
+		if strings.Contains(errText, marker) {
+			return true
+		}
+	}
+	return false
+}
+
+func persistDetectedSignatureAlgorithm(r *Request, algorithm string) {
+	r.Config.ActiveProfile.SignatureAlgorithm = algorithm
+	if r.CredentialsSupplied {
+		config.Debug("Credentials supplied on command-line, not persisting detected signature algorithm")
+		return
+	}
+	r.Config.UpdateConfig("signaturealgorithm", algorithm, true)
+}
+
+func detectSignatureAlgorithm(r *Request) (string, error) {
+	attempts := []string{config.SignatureAlgorithmHmacSHA512, config.SignatureAlgorithmHmacSHA1}
+	var lastErr error
+
+	for _, algorithm := range attempts {
+		config.Debug("Trying API signature algorithm probe:", algorithm)
+		params := buildAPIRequestParams(r, "listApis", []string{"listall=true"})
+		params.Add("apiKey", r.Config.ActiveProfile.APIKey)
+		response, err := executeSignedAPIRequest(r, params, algorithm)
+		if err != nil {
+			config.Debug("API signature algorithm probe failed before response for ", algorithm, ": ", err)
+			lastErr = err
+			continue
+		}
+
+		body, _ := ioutil.ReadAll(response.Body)
+		config.Debug("Signature algorithm probe response body:", string(body))
+		if _, err := parseAPIResponse(body); err == nil {
+			config.Debug("Selected API signature algorithm:", algorithm)
+			persistDetectedSignatureAlgorithm(r, algorithm)
+			return algorithm, nil
+		} else {
+			lastErr = err
+			if isAuthenticationFailure(response.StatusCode, err) {
+				config.Debug("API signature algorithm probe failed authentication for ", algorithm, ": ", err)
+			} else {
+				config.Debug("API signature algorithm probe failed with non-authentication error for ", algorithm, ": ", err)
+			}
+		}

Review Comment:
   Autodetection currently falls back to trying the next algorithm even when the probe failed for a non-authentication reason (e.g., server error, decode error). Per the PR behavior description, fallback should only happen on authentication/signature verification failures; otherwise the original error should be returned immediately.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@cloudstack.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Support API signing with HmacSHA512 [cloudstack-cloudmonkey]

Posted by "weizhouapache (via GitHub)" <gi...@apache.org>.
weizhouapache commented on code in PR #213:
URL: https://github.com/apache/cloudstack-cloudmonkey/pull/213#discussion_r3956214988


##########
cmd/network.go:
##########
@@ -218,6 +219,201 @@ func encodeRequestParams(params url.Values) string {
 	return buf.String()
 }
 
+func cloneRequestParams(params url.Values) url.Values {
+	cloned := make(url.Values)
+	for key, values := range params {
+		for _, value := range values {
+			cloned.Add(key, value)
+		}
+	}
+	return cloned
+}
+
+func buildAPIRequestParams(r *Request, api string, args []string) url.Values {
+	params := make(url.Values)
+	params.Add("command", api)
+	apiData := r.Config.GetCache()[api]
+	for _, arg := range args {
+		if apiData != nil {
+			skip := false
+			for _, fakeArg := range apiData.FakeArgs {
+				if strings.HasPrefix(arg, fakeArg) {
+					skip = true
+					break
+				}
+			}
+			if skip {
+				continue
+			}
+
+		}
+		parts := strings.SplitN(arg, "=", 2)
+		if len(parts) == 2 {
+			key := parts[0]
+			value := parts[1]
+			if strings.HasPrefix(value, "\"") && strings.HasSuffix(value, "\"") {
+				value = value[1 : len(value)-1]
+			}
+			if strings.HasPrefix(value, "@") {
+				possibleFileName := value[1:]
+				if fileInfo, err := os.Stat(possibleFileName); err == nil && !fileInfo.IsDir() {
+					bytes, err := ioutil.ReadFile(possibleFileName)
+					config.Debug()
+					if err == nil {
+						value = string(bytes)
+						config.Debug("Content for argument ", key, " read from file: ", possibleFileName, " is: ", value)
+					}
+				}
+			}
+			params.Add(key, value)
+		}
+	}
+	signatureversion := "3"
+	expiresKey := "expires"
+	params.Add("response", "json")
+	params.Add("signatureversion", signatureversion)
+	params.Add(expiresKey, time.Now().UTC().Add(15*time.Minute).Format(time.RFC3339))
+	return params
+}
+
+func signRequest(unsignedRequest, secretKey, algorithm string) (string, error) {
+	signatureAlgorithm, err := config.NormalizeSignatureAlgorithm(algorithm)
+	if err != nil {
+		return "", err
+	}
+
+	var signature []byte
+	switch signatureAlgorithm {
+	case config.SignatureAlgorithmHmacSHA1:
+		mac := hmac.New(sha1.New, []byte(secretKey))
+		mac.Write([]byte(strings.ToLower(unsignedRequest)))
+		signature = mac.Sum(nil)
+	case config.SignatureAlgorithmHmacSHA512:
+		mac := hmac.New(sha512.New, []byte(secretKey))
+		mac.Write([]byte(strings.ToLower(unsignedRequest)))
+		signature = mac.Sum(nil)
+	default:
+		return "", errors.New("signature algorithm must be concrete")
+	}
+	return base64.StdEncoding.EncodeToString(signature), nil
+}
+
+func executeSignedAPIRequest(r *Request, unsignedParams url.Values, algorithm string) (*http.Response, error) {
+	params := cloneRequestParams(unsignedParams)
+	encodedParams := encodeRequestParams(params)
+
+	signature, err := signRequest(encodedParams, r.Config.ActiveProfile.SecretKey, algorithm)
+	if err != nil {
+		return nil, err
+	}
+	if r.Config.Core.PostRequest {
+		params.Add("signature", signature)
+	} else {
+		encodedParams = encodedParams + fmt.Sprintf("&signature=%s", url.QueryEscape(signature))
+		params = nil
+	}
+
+	requestURL := fmt.Sprintf("%s?%s", r.Config.ActiveProfile.URL, encodedParams)
+	config.Debug("NewAPIRequest API request URL:", requestURL)
+	return executeRequest(r, requestURL, params)
+}
+
+func parseAPIResponse(body []byte) (map[string]interface{}, error) {
+	var data map[string]interface{}
+	if err := json.Unmarshal(body, &data); err != nil {
+		return nil, errors.New("failed to decode response")
+	}
+
+	if apiResponse := getResponseData(data); apiResponse != nil {
+		if _, ok := apiResponse["errorcode"]; ok {
+			return nil, fmt.Errorf("(HTTP %v, error code %v) %v", apiResponse["errorcode"], apiResponse["cserrorcode"], apiResponse["errortext"])
+		}
+		return apiResponse, nil
+	}
+
+	return nil, errors.New("failed to decode response")
+}
+
+func isAuthenticationFailure(statusCode int, err error) bool {
+	if statusCode == http.StatusUnauthorized || statusCode == http.StatusForbidden {
+		return true
+	}
+	if err == nil {
+		return false
+	}
+	errText := strings.ToLower(err.Error())
+	for _, marker := range []string{"signature", "authenticate", "authentication", "credential", "unauthoriz", "api key", "apikey"} {
+		if strings.Contains(errText, marker) {
+			return true
+		}
+	}
+	return false
+}
+
+func persistDetectedSignatureAlgorithm(r *Request, algorithm string) {
+	r.Config.ActiveProfile.SignatureAlgorithm = algorithm
+	if r.CredentialsSupplied {
+		config.Debug("Credentials supplied on command-line, not persisting detected signature algorithm")
+		return
+	}
+	r.Config.UpdateConfig("signaturealgorithm", algorithm, true)
+}
+
+func detectSignatureAlgorithm(r *Request) (string, error) {
+	attempts := []string{config.SignatureAlgorithmHmacSHA512, config.SignatureAlgorithmHmacSHA1}
+	var lastErr error
+
+	for _, algorithm := range attempts {
+		config.Debug("Trying API signature algorithm probe:", algorithm)
+		params := buildAPIRequestParams(r, "listApis", []string{"listall=true"})

Review Comment:
   since this method is only used to detect the algorithm, would listApis with a specific command be faster ?
   
   for example, `listApis?command=listapis`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@cloudstack.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Support FIPS-compatible API signing [cloudstack-cloudmonkey]

Posted by "DaanHoogland (via GitHub)" <gi...@apache.org>.
DaanHoogland commented on PR #213:
URL: https://github.com/apache/cloudstack-cloudmonkey/pull/213#issuecomment-5370269604

   @weizhouapache , can I ask you to look at this one?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@cloudstack.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Support API signing with HmacSHA512 [cloudstack-cloudmonkey]

Posted by "borisstoyanov (via GitHub)" <gi...@apache.org>.
borisstoyanov closed pull request #213: Support API signing with HmacSHA512
URL: https://github.com/apache/cloudstack-cloudmonkey/pull/213


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@cloudstack.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Support FIPS-compatible API signing [cloudstack-cloudmonkey]

Posted by "weizhouapache (via GitHub)" <gi...@apache.org>.
weizhouapache commented on PR #213:
URL: https://github.com/apache/cloudstack-cloudmonkey/pull/213#issuecomment-5370492192

   > @weizhouapache , can I ask you to look at this one?
   
   @DaanHoogland @andrijapanicsb 
   this is good. we have tested it.
   
   However, there is not a public pull request to support `HmacSHA512` instead of insecure `HmacSHA1` in cloudstack repo. I can create one.
   
   Also, it woud be better to mention new algorithm `HmacSHA512` instead of `fips`
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@cloudstack.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Support API signing with HmacSHA512 [cloudstack-cloudmonkey]

Posted by "weizhouapache (via GitHub)" <gi...@apache.org>.
weizhouapache commented on code in PR #213:
URL: https://github.com/apache/cloudstack-cloudmonkey/pull/213#discussion_r3956214988


##########
cmd/network.go:
##########
@@ -218,6 +219,201 @@ func encodeRequestParams(params url.Values) string {
 	return buf.String()
 }
 
+func cloneRequestParams(params url.Values) url.Values {
+	cloned := make(url.Values)
+	for key, values := range params {
+		for _, value := range values {
+			cloned.Add(key, value)
+		}
+	}
+	return cloned
+}
+
+func buildAPIRequestParams(r *Request, api string, args []string) url.Values {
+	params := make(url.Values)
+	params.Add("command", api)
+	apiData := r.Config.GetCache()[api]
+	for _, arg := range args {
+		if apiData != nil {
+			skip := false
+			for _, fakeArg := range apiData.FakeArgs {
+				if strings.HasPrefix(arg, fakeArg) {
+					skip = true
+					break
+				}
+			}
+			if skip {
+				continue
+			}
+
+		}
+		parts := strings.SplitN(arg, "=", 2)
+		if len(parts) == 2 {
+			key := parts[0]
+			value := parts[1]
+			if strings.HasPrefix(value, "\"") && strings.HasSuffix(value, "\"") {
+				value = value[1 : len(value)-1]
+			}
+			if strings.HasPrefix(value, "@") {
+				possibleFileName := value[1:]
+				if fileInfo, err := os.Stat(possibleFileName); err == nil && !fileInfo.IsDir() {
+					bytes, err := ioutil.ReadFile(possibleFileName)
+					config.Debug()
+					if err == nil {
+						value = string(bytes)
+						config.Debug("Content for argument ", key, " read from file: ", possibleFileName, " is: ", value)
+					}
+				}
+			}
+			params.Add(key, value)
+		}
+	}
+	signatureversion := "3"
+	expiresKey := "expires"
+	params.Add("response", "json")
+	params.Add("signatureversion", signatureversion)
+	params.Add(expiresKey, time.Now().UTC().Add(15*time.Minute).Format(time.RFC3339))
+	return params
+}
+
+func signRequest(unsignedRequest, secretKey, algorithm string) (string, error) {
+	signatureAlgorithm, err := config.NormalizeSignatureAlgorithm(algorithm)
+	if err != nil {
+		return "", err
+	}
+
+	var signature []byte
+	switch signatureAlgorithm {
+	case config.SignatureAlgorithmHmacSHA1:
+		mac := hmac.New(sha1.New, []byte(secretKey))
+		mac.Write([]byte(strings.ToLower(unsignedRequest)))
+		signature = mac.Sum(nil)
+	case config.SignatureAlgorithmHmacSHA512:
+		mac := hmac.New(sha512.New, []byte(secretKey))
+		mac.Write([]byte(strings.ToLower(unsignedRequest)))
+		signature = mac.Sum(nil)
+	default:
+		return "", errors.New("signature algorithm must be concrete")
+	}
+	return base64.StdEncoding.EncodeToString(signature), nil
+}
+
+func executeSignedAPIRequest(r *Request, unsignedParams url.Values, algorithm string) (*http.Response, error) {
+	params := cloneRequestParams(unsignedParams)
+	encodedParams := encodeRequestParams(params)
+
+	signature, err := signRequest(encodedParams, r.Config.ActiveProfile.SecretKey, algorithm)
+	if err != nil {
+		return nil, err
+	}
+	if r.Config.Core.PostRequest {
+		params.Add("signature", signature)
+	} else {
+		encodedParams = encodedParams + fmt.Sprintf("&signature=%s", url.QueryEscape(signature))
+		params = nil
+	}
+
+	requestURL := fmt.Sprintf("%s?%s", r.Config.ActiveProfile.URL, encodedParams)
+	config.Debug("NewAPIRequest API request URL:", requestURL)
+	return executeRequest(r, requestURL, params)
+}
+
+func parseAPIResponse(body []byte) (map[string]interface{}, error) {
+	var data map[string]interface{}
+	if err := json.Unmarshal(body, &data); err != nil {
+		return nil, errors.New("failed to decode response")
+	}
+
+	if apiResponse := getResponseData(data); apiResponse != nil {
+		if _, ok := apiResponse["errorcode"]; ok {
+			return nil, fmt.Errorf("(HTTP %v, error code %v) %v", apiResponse["errorcode"], apiResponse["cserrorcode"], apiResponse["errortext"])
+		}
+		return apiResponse, nil
+	}
+
+	return nil, errors.New("failed to decode response")
+}
+
+func isAuthenticationFailure(statusCode int, err error) bool {
+	if statusCode == http.StatusUnauthorized || statusCode == http.StatusForbidden {
+		return true
+	}
+	if err == nil {
+		return false
+	}
+	errText := strings.ToLower(err.Error())
+	for _, marker := range []string{"signature", "authenticate", "authentication", "credential", "unauthoriz", "api key", "apikey"} {
+		if strings.Contains(errText, marker) {
+			return true
+		}
+	}
+	return false
+}
+
+func persistDetectedSignatureAlgorithm(r *Request, algorithm string) {
+	r.Config.ActiveProfile.SignatureAlgorithm = algorithm
+	if r.CredentialsSupplied {
+		config.Debug("Credentials supplied on command-line, not persisting detected signature algorithm")
+		return
+	}
+	r.Config.UpdateConfig("signaturealgorithm", algorithm, true)
+}
+
+func detectSignatureAlgorithm(r *Request) (string, error) {
+	attempts := []string{config.SignatureAlgorithmHmacSHA512, config.SignatureAlgorithmHmacSHA1}
+	var lastErr error
+
+	for _, algorithm := range attempts {
+		config.Debug("Trying API signature algorithm probe:", algorithm)
+		params := buildAPIRequestParams(r, "listApis", []string{"listall=true"})

Review Comment:
   since this method is only used to detect the algorithm, would listApis with a specific command be faster ?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@cloudstack.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Support FIPS-compatible API signing [cloudstack-cloudmonkey]

Posted by "andrijapanicsb (via GitHub)" <gi...@apache.org>.
andrijapanicsb commented on code in PR #213:
URL: https://github.com/apache/cloudstack-cloudmonkey/pull/213#discussion_r3344773177


##########
cmd/network.go:
##########
@@ -218,6 +219,195 @@ func encodeRequestParams(params url.Values) string {
 	return buf.String()
 }
 
+func cloneRequestParams(params url.Values) url.Values {
+	cloned := make(url.Values)
+	for key, values := range params {
+		for _, value := range values {
+			cloned.Add(key, value)
+		}
+	}
+	return cloned
+}
+
+func buildAPIRequestParams(r *Request, api string, args []string) url.Values {
+	params := make(url.Values)
+	params.Add("command", api)
+	apiData := r.Config.GetCache()[api]
+	for _, arg := range args {
+		if apiData != nil {
+			skip := false
+			for _, fakeArg := range apiData.FakeArgs {
+				if strings.HasPrefix(arg, fakeArg) {
+					skip = true
+					break
+				}
+			}
+			if skip {
+				continue
+			}
+
+		}
+		parts := strings.SplitN(arg, "=", 2)
+		if len(parts) == 2 {
+			key := parts[0]
+			value := parts[1]
+			if strings.HasPrefix(value, "\"") && strings.HasSuffix(value, "\"") {
+				value = value[1 : len(value)-1]
+			}
+			if strings.HasPrefix(value, "@") {
+				possibleFileName := value[1:]
+				if fileInfo, err := os.Stat(possibleFileName); err == nil && !fileInfo.IsDir() {
+					bytes, err := ioutil.ReadFile(possibleFileName)
+					config.Debug()
+					if err == nil {
+						value = string(bytes)
+						config.Debug("Content for argument ", key, " read from file: ", possibleFileName, " is: ", value)
+					}
+				}
+			}
+			params.Add(key, value)
+		}
+	}
+	signatureversion := "3"
+	expiresKey := "expires"
+	params.Add("response", "json")
+	params.Add("signatureversion", signatureversion)
+	params.Add(expiresKey, time.Now().UTC().Add(15*time.Minute).Format(time.RFC3339))
+	return params
+}
+
+func signRequest(unsignedRequest, secretKey, algorithm string) (string, error) {
+	signatureAlgorithm, err := config.NormalizeSignatureAlgorithm(algorithm)
+	if err != nil {
+		return "", err
+	}
+
+	var signature []byte
+	switch signatureAlgorithm {
+	case config.SignatureAlgorithmHmacSHA1:
+		mac := hmac.New(sha1.New, []byte(secretKey))
+		mac.Write([]byte(strings.ToLower(unsignedRequest)))
+		signature = mac.Sum(nil)
+	case config.SignatureAlgorithmHmacSHA512:
+		mac := hmac.New(sha512.New, []byte(secretKey))
+		mac.Write([]byte(strings.ToLower(unsignedRequest)))
+		signature = mac.Sum(nil)
+	default:
+		return "", errors.New("signature algorithm must be concrete")
+	}
+	return base64.StdEncoding.EncodeToString(signature), nil
+}
+
+func executeSignedAPIRequest(r *Request, unsignedParams url.Values, algorithm string) (*http.Response, error) {
+	params := cloneRequestParams(unsignedParams)
+	encodedParams := encodeRequestParams(params)
+
+	signature, err := signRequest(encodedParams, r.Config.ActiveProfile.SecretKey, algorithm)
+	if err != nil {
+		return nil, err
+	}
+	if r.Config.Core.PostRequest {
+		params.Add("signature", signature)
+	} else {
+		encodedParams = encodedParams + fmt.Sprintf("&signature=%s", url.QueryEscape(signature))
+		params = nil
+	}
+
+	requestURL := fmt.Sprintf("%s?%s", r.Config.ActiveProfile.URL, encodedParams)
+	config.Debug("NewAPIRequest API request URL:", requestURL)
+	return executeRequest(r, requestURL, params)
+}
+
+func parseAPIResponse(body []byte) (map[string]interface{}, error) {
+	var data map[string]interface{}
+	if err := json.Unmarshal(body, &data); err != nil {
+		return nil, errors.New("failed to decode response")
+	}
+
+	if apiResponse := getResponseData(data); apiResponse != nil {
+		if _, ok := apiResponse["errorcode"]; ok {
+			return nil, fmt.Errorf("(HTTP %v, error code %v) %v", apiResponse["errorcode"], apiResponse["cserrorcode"], apiResponse["errortext"])
+		}
+		return apiResponse, nil
+	}
+
+	return nil, errors.New("failed to decode response")
+}
+
+func isAuthenticationFailure(statusCode int, err error) bool {
+	if statusCode == http.StatusUnauthorized || statusCode == http.StatusForbidden {
+		return true
+	}
+	if err == nil {
+		return false
+	}
+	errText := strings.ToLower(err.Error())
+	for _, marker := range []string{"signature", "authenticate", "authentication", "credential", "unauthoriz", "api key", "apikey"} {
+		if strings.Contains(errText, marker) {
+			return true
+		}
+	}
+	return false
+}
+
+func persistDetectedSignatureAlgorithm(r *Request, algorithm string) {
+	r.Config.ActiveProfile.SignatureAlgorithm = algorithm
+	if r.CredentialsSupplied {
+		config.Debug("Credentials supplied on command-line, not persisting detected signature algorithm")
+		return
+	}
+	r.Config.UpdateConfig("signaturealgorithm", algorithm, true)
+}
+
+func detectSignatureAlgorithm(r *Request) (string, error) {
+	attempts := []string{config.SignatureAlgorithmHmacSHA512, config.SignatureAlgorithmHmacSHA1}
+	var lastErr error
+
+	for _, algorithm := range attempts {
+		config.Debug("Trying API signature algorithm probe:", algorithm)
+		params := buildAPIRequestParams(r, "listApis", []string{"listall=true"})
+		params.Add("apiKey", r.Config.ActiveProfile.APIKey)
+		response, err := executeSignedAPIRequest(r, params, algorithm)
+		if err != nil {
+			config.Debug("API signature algorithm probe failed before response for ", algorithm, ": ", err)
+			lastErr = err
+			continue
+		}
+
+		body, _ := ioutil.ReadAll(response.Body)
+		config.Debug("Signature algorithm probe response body:", string(body))
+		if _, err := parseAPIResponse(body); err == nil {

Review Comment:
   This is an intentional probe of the newer SHA512 signing method, and if that fails, it doesn't throw an error, it retries, but this time with SHA1



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@cloudstack.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Support FIPS-compatible API signing [cloudstack-cloudmonkey]

Posted by "DaanHoogland (via GitHub)" <gi...@apache.org>.
DaanHoogland commented on PR #213:
URL: https://github.com/apache/cloudstack-cloudmonkey/pull/213#issuecomment-5379875636

   > Also, it woud be better to mention new algorithm `HmacSHA512` instead of `fips`
   
   Do you mean edit the title of the PR, @weizhouapache ? or is there more to do? cc @andrijapanicsb 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@cloudstack.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Support FIPS-compatible API signing [cloudstack-cloudmonkey]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #213:
URL: https://github.com/apache/cloudstack-cloudmonkey/pull/213#issuecomment-4602013816

   <!-- cmk-build-artifact-comment -->
   ✅ Build complete for PR #213.
   
   📦 Binary artifacts are available in the [workflow run](https://github.com/apache/cloudstack-cloudmonkey/actions/runs/26817199996) (expires on June 12, 2026).
   
   > **Note:** Download artifacts by clicking on the workflow run link above, then scroll to the "Artifacts" section.
   > _Artifacts from PR builds are for testing only and may contain unreviewed, malicious code._


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@cloudstack.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Support FIPS-compatible API signing [cloudstack-cloudmonkey]

Posted by "weizhouapache (via GitHub)" <gi...@apache.org>.
weizhouapache commented on PR #213:
URL: https://github.com/apache/cloudstack-cloudmonkey/pull/213#issuecomment-5381118003

   > > Also, it woud be better to mention new algorithm `HmacSHA512` instead of `fips`
   > 
   > Do you mean edit the title of the PR, @weizhouapache ? or is there more to do? cc @andrijapanicsb
   
   @DaanHoogland 
   it would be better to update both title and codes.
   FIPS stands for some standards.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@cloudstack.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Support API signing with HmacSHA512 [cloudstack-cloudmonkey]

Posted by "borisstoyanov (via GitHub)" <gi...@apache.org>.
borisstoyanov merged PR #213:
URL: https://github.com/apache/cloudstack-cloudmonkey/pull/213


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@cloudstack.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org