signing

package
v0.8.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2026 License: AGPL-3.0 Imports: 30 Imported by: 0

Documentation

Overview

Package signing implements the external certificate signing mode: import of a PKCS#12 identity and its provisioning profile, sealed storage of the private key, compatibility checks against an IPA and a device, per-task materialization of the signing material and verification of the signed output produced by PlumeImpactor.

Index

Constants

View Source
const (
	MaxP12Size     = 1 << 20
	MaxProfileSize = 2 << 20
)

Upload limits. HTTP handlers reject larger files before reading them and the decoders reject larger inputs.

View Source
const (
	CodeUploadTooLarge = "upload_too_large"

	CodeP12Invalid       = "p12_invalid"
	CodeP12WrongPassword = "p12_wrong_password"
	CodeP12NoPrivateKey  = "p12_no_private_key"
	CodeP12NoCertificate = "p12_no_certificate"
	CodeP12KeyMismatch   = "p12_key_mismatch"
	CodeP12Ambiguous     = "p12_ambiguous"
	CodeP12Unsupported   = "p12_unsupported"
	// CodeP12PasswordUnsupported: the password contains characters that a
	// PKCS#12 password cannot encode (outside the Unicode BMP, such as emoji).
	CodeP12PasswordUnsupported = "p12_password_unsupported"

	CodeCertificateNotCodeSigning = "certificate_not_code_signing"
	CodeCertificateExpired        = "certificate_expired"
	CodeCertificateNotYetValid    = "certificate_not_yet_valid"
	CodeCertificateNoTeam         = "certificate_no_team"
	CodeRevocationNotChecked      = "revocation_not_checked"

	CodeProfileInvalid            = "profile_invalid"
	CodeProfileSignatureInvalid   = "profile_signature_invalid"
	CodeProfileExpired            = "profile_expired"
	CodeProfileNotInstallable     = "profile_not_installable"
	CodeProfileCertificateMissing = "profile_certificate_mismatch"
	CodeProfileTeamMismatch       = "profile_team_mismatch"
	CodeIdentityExpiringSoon      = "identity_expiring_soon"

	CodeIdentityDuplicate  = "identity_duplicate"
	CodeIdentityNotFound   = "identity_not_found"
	CodeIdentityInUse      = "identity_in_use"
	CodeIdentityReferenced = "identity_referenced"
	CodeKeyUnavailable     = "key_unavailable"
	CodeKeyMismatch        = "key_mismatch"
	CodeSealedKeyCorrupt   = "sealed_key_corrupt"
	CodeWorkspaceFailed    = "workspace_failed"

	CodeDevicePlatformUnknown   = "device_platform_unknown"
	CodeDeviceUnreachable       = "device_unreachable"
	CodeProfilePlatformMismatch = "profile_platform_mismatch"
	CodeIPAPlatformMismatch     = "ipa_platform_mismatch"
	CodeIPAPlatformUnknown      = "ipa_platform_unknown"
	CodeDeviceNotProvisioned    = "device_not_provisioned"
	CodeIPAInvalid              = "ipa_invalid"
	CodeIPAPathRejected         = "ipa_path_rejected"
	// CodeCustomIconInvalid: the uploaded custom app icon is not a readable
	// image inside the allowed directories.
	CodeCustomIconInvalid            = "custom_icon_invalid"
	CodeNestedBundlesNotSigned       = "nested_bundles_not_signed"
	CodeBundleIdentifierRewritten    = "bundle_identifier_rewritten"
	CodeExtensionRemoved             = "extension_removed"
	CodeApplicationIDMismatch        = "application_identifier_mismatch"
	CodeWildcardRequiresEntitlements = "wildcard_requires_binary_entitlements"
	CodeEntitlementsMissing          = "entitlements_missing"
	CodeEntitlementValueChanged      = "entitlement_value_changed"
	CodeIncompatible                 = "incompatible"
	// CodeApplicationIdentifierFromProfile: a bundle is signed with the
	// application identifier of the provisioning profile, which differs from
	// the one its bundle identifier would give (warning).
	CodeApplicationIdentifierFromProfile = "application_identifier_from_profile"
	// CodeCustomIdentifierInvalid: the bundle identifier requested by the user
	// is not a valid bundle identifier.
	CodeCustomIdentifierInvalid = "custom_identifier_invalid"

	CodeEngineFailed                   = "engine_failed"
	CodeSignedOutputMissing            = "signed_output_missing"
	CodeSignedBundlesMismatch          = "signed_bundles_mismatch"
	CodeSignedBundleIdentifierMismatch = "signed_bundle_identifier_mismatch"
	CodeSignedProfileMismatch          = "signed_profile_mismatch"
	CodeSignedCertificateMismatch      = "signed_certificate_mismatch"
	CodeSignedEntitlementsInvalid      = "signed_entitlements_invalid"

	CodeTransportFailed = "transport_failed"
	// CodePairingRecordInvalid: the remote pairing record of the device is
	// missing or unreadable; the device must be paired again.
	CodePairingRecordInvalid = "pairing_record_invalid"

	// CodeCertificateInvalid: the stored certificate of an identity cannot be parsed.
	CodeCertificateInvalid = "certificate_invalid"
)

Stable issue and error codes. The frontend maps them to translated texts and falls back to Issue.Message for unknown codes.

Variables

This section is empty.

Functions

func AcquireLease

func AcquireLease(identityID uint) (release func())

AcquireLease marks the identity as used by a running task until release is called. It waits while an Exclusive operation runs on the identity. Calling release more than once has no effect.

func CodeOf

func CodeOf(err error) string

CodeOf returns the code of the first *Error in err's chain, or "".

func Configure

func Configure(keyFile, workRoot string)

Configure sets the deployment key file and the workspace root. Call once at startup.

func Exclusive

func Exclusive(identityID uint, fn func() error) error

Exclusive runs fn only when no lease is held on the identity and blocks new leases while fn runs. It returns an *Error with CodeIdentityInUse otherwise. Concurrent Exclusive calls on the same identity run one after the other.

func HasErrors

func HasErrors(issues []Issue) bool

HasErrors reports whether issues contains at least one blocking issue.

func IdentityAAD

func IdentityAAD(certificateSHA256 string) []byte

IdentityAAD returns the additional authenticated data binding a sealed key to the identity certificate.

func LeaseHeld

func LeaseHeld(identityID uint) bool

LeaseHeld reports whether a running task holds a lease on the identity.

func RecoverWorkspaces

func RecoverWorkspaces() (int, error)

RecoverWorkspaces removes the workspaces left by crashed processes: every ws-* directory of the configured root whose lock is not held. It returns the number of removed workspaces.

func RewrapP12 added in v0.6.3

func RewrapP12(data []byte, password string) (rewrapped []byte, rewrapPassword string, err error)

RewrapP12 decodes a PKCS#12 file in process and encodes the identity it holds again as a legacy PKCS#12 file.

SideStore's "Export Full (.p12)" writes the private key as a plain keyBag without a MAC (its export dialog ignores the password it asks for). The signing engine reads such a file as holding no private key, so the identity is decoded here and written again as a shrouded, MAC-protected file.

The returned password protects the re-wrapped bytes only. It is random, used once for that file and never stored, logged or returned to a client. The certificate chain of the input is dropped: the signing engine rebuilds the chain from the certificate of the account it signs with.

Errors are *Error of ClassIdentity with a CodeP12* code.

func VerifyProfile

func VerifyProfile(data []byte) (*model.MobileProvisioningProfile, error)

VerifyProfile parses a .mobileprovision, verifies its CMS signature and that the signer is Apple's provisioning profile signing certificate chaining to an embedded Apple root CA at the profile creation date. Revocation is not checked. Errors are *Error of ClassIdentity with CodeProfileInvalid or CodeProfileSignatureInvalid.

Types

type Class

type Class string

Class groups failures by what the user has to fix. Callers map classes to model.RefreshedError values and must never retry identity or signing errors.

const (
	// ClassIdentity: certificate, private key, provisioning profile, sealing key
	// or their compatibility with the app and the device.
	ClassIdentity Class = "identity"
	// ClassSigning: the IPA could not be read, the signing engine failed or its
	// output did not pass verification.
	ClassSigning Class = "signing"
	// ClassTransport: the device could not be reached or rejected the installation.
	ClassTransport Class = "transport"
)

func ClassOf

func ClassOf(err error) Class

ClassOf returns the class of the first *Error in err's chain, or "" when err does not come from the external signing pipeline.

type Error

type Error struct {
	Class   Class
	Code    string
	Message string
	// Issues holds the detailed findings when the error summarizes a
	// validation step (for example the blocking issues of a compatibility plan).
	Issues []Issue
	Err    error
}

Error is the error type returned by this package and by the external installation pipeline. Use ClassOf or errors.As to classify it.

func Errorf

func Errorf(class Class, code string, format string, args ...any) *Error

Errorf builds an *Error without detailed issues.

func IssuesError

func IssuesError(class Class, code string, message string, issues []Issue) *Error

IssuesError wraps the blocking issues of a validation step into an *Error of the given class, or returns nil when there is no blocking issue.

func Wrap

func Wrap(class Class, code string, cause error, format string, args ...any) *Error

Wrap builds an *Error that keeps cause as its wrapped error.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type ImportRequest

type ImportRequest struct {
	Name     string
	P12      []byte
	Password string
	Profile  []byte
}

ImportRequest carries the raw inputs of an identity import. P12 and Password are never persisted.

type Issue

type Issue struct {
	Code     string   `json:"code"`
	Severity Severity `json:"severity"`
	Message  string   `json:"message"`
	// Bundle is the bundle path inside the IPA (for example
	// "Payload/App.app/PlugIns/Widget.appex") when the issue concerns one bundle.
	Bundle string `json:"bundle,omitempty"`
}

Issue is one finding of a validation step. Code is stable and machine readable; Message is an English diagnostic meant for logs and the UI.

func IdentityStatus

func IdentityStatus(identity model.SigningIdentity, now time.Time) []Issue

IdentityStatus returns the display findings of a stored identity at time now.

func NewIdentity

func NewIdentity(req ImportRequest, sealer *Sealer, now time.Time) (*model.SigningIdentity, []Issue, error)

NewIdentity decodes and validates an import and returns the identity to persist (ID 0, Revision 1) with its private key sealed by sealer, plus the non-blocking issues. Blocking findings are returned as *Error.

func ReplaceProfile

func ReplaceProfile(identity model.SigningIdentity, profileData []byte, now time.Time) (*model.SigningIdentity, []Issue, error)

ReplaceProfile validates profileData against the identity certificate and returns a copy with every profile field, including the team name, replaced and Revision incremented.

func ValidateIdentity

func ValidateIdentity(cert *x509.Certificate, profile *model.MobileProvisioningProfile, now time.Time) []Issue

ValidateIdentity returns the findings about a certificate and a provisioning profile at time now: certificate usage, validity dates, team, profile expiry, installability and whether the profile lists the certificate. Compatibility with a device or an IPA is not checked here.

type Material

type Material struct {
	CertificatePath string
	PrivateKeyPath  string
	ProfilePath     string
}

Material lists the signing files written into a workspace.

func Materialize

func Materialize(ws *Workspace, identity model.SigningIdentity, sealer *Sealer) (*Material, error)

Materialize unseals the identity private key and writes the leaf certificate PEM, the unencrypted PKCS#8 key PEM and the profile into ws. The certificate file holds the leaf only: the signing engine keeps the last CERTIFICATE block it reads.

type P12Identity

type P12Identity struct {
	Certificate *x509.Certificate
	PrivateKey  crypto.Signer
}

P12Identity is the single code signing identity (leaf certificate matching the private key) found in a PKCS#12 file.

func DecodeP12

func DecodeP12(data []byte, password string) (*P12Identity, error)

DecodeP12 decodes a PKCS#12 file in-process. The password may be empty. Errors are *Error of ClassIdentity with a CodeP12* code.

The MAC policy is the one of go-pkcs12: a file with a MAC is only accepted when the MAC verifies, and a file without MAC is only accepted with an empty password, without any integrity check. Every key derivation of the file, including the one of a key bag nested in an encrypted safe, is refused beyond the iteration bound of the vendored library.

type Sealer

type Sealer struct {
	// contains filtered or unexported fields
}

Sealer encrypts private keys with AES-256-GCM under the deployment key.

func DefaultSealer

func DefaultSealer() (*Sealer, error)

DefaultSealer returns the sealer of the configured key file, loading or creating it on first use. A failed load is retried on the next call.

func LoadOrCreateSealer

func LoadOrCreateSealer(path string) (*Sealer, error)

LoadOrCreateSealer loads the deployment key file, creating it when missing. Errors are *Error of ClassIdentity with CodeKeyUnavailable.

func (*Sealer) Open

func (s *Sealer) Open(blob, aad []byte) ([]byte, error)

Open decrypts a blob produced by Seal with the same aad.

func (*Sealer) Seal

func (s *Sealer) Seal(plaintext, aad []byte) ([]byte, error)

Seal encrypts plaintext bound to aad.

type Severity

type Severity string

Severity of an Issue. Only SeverityError blocks signing.

const (
	SeverityError   Severity = "error"
	SeverityWarning Severity = "warning"
	SeverityInfo    Severity = "info"
)

type Workspace

type Workspace struct {
	Dir     string
	HomeDir string
	TempDir string
	// contains filtered or unexported fields
}

Workspace is a private per-task directory holding the materialized signing files and the isolated HOME and TMPDIR of the signing engine.

While a workspace is open its lock file is held with flock(2), so a RecoverWorkspaces run by any process never removes it.

func NewWorkspace

func NewWorkspace() (*Workspace, error)

NewWorkspace creates a workspace under the configured root. Errors are *Error of ClassSigning with CodeWorkspaceFailed.

func (*Workspace) Close

func (w *Workspace) Close() error

Close removes the workspace and everything in it, then releases its lock. Calling Close again has no effect.

Directories

Path Synopsis
Package appcheck analyzes an IPA, plans how the signing engine will sign it with one provisioning profile, refuses what the engine would mishandle and verifies the signed output.
Package appcheck analyzes an IPA, plans how the signing engine will sign it with one provisioning profile, refuses what the engine would mishandle and verifies the signed output.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址