azure.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. package provisioner
  2. import (
  3. "context"
  4. "crypto/sha256"
  5. "crypto/x509"
  6. "encoding/hex"
  7. "encoding/json"
  8. "io"
  9. "net/http"
  10. "regexp"
  11. "strings"
  12. "time"
  13. "github.com/pkg/errors"
  14. "go.step.sm/crypto/jose"
  15. "go.step.sm/crypto/sshutil"
  16. "go.step.sm/crypto/x509util"
  17. "go.step.sm/linkedca"
  18. "github.com/smallstep/certificates/errs"
  19. )
  20. // azureOIDCBaseURL is the base discovery url for Microsoft Azure tokens.
  21. const azureOIDCBaseURL = "https://login.microsoftonline.com"
  22. //nolint:gosec // azureIdentityTokenURL is the URL to get the identity token for an instance.
  23. const azureIdentityTokenURL = "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fmanagement.azure.com%2F"
  24. // azureDefaultAudience is the default audience used.
  25. const azureDefaultAudience = "https://management.azure.com/"
  26. // azureXMSMirIDRegExp is the regular expression used to parse the xms_mirid claim.
  27. // Using case insensitive as resourceGroups appears as resourcegroups.
  28. var azureXMSMirIDRegExp = regexp.MustCompile(`(?i)^/subscriptions/([^/]+)/resourceGroups/([^/]+)/providers/Microsoft.(Compute/virtualMachines|ManagedIdentity/userAssignedIdentities)/([^/]+)$`)
  29. type azureConfig struct {
  30. oidcDiscoveryURL string
  31. identityTokenURL string
  32. }
  33. func newAzureConfig(tenantID string) *azureConfig {
  34. return &azureConfig{
  35. oidcDiscoveryURL: azureOIDCBaseURL + "/" + tenantID + "/.well-known/openid-configuration",
  36. identityTokenURL: azureIdentityTokenURL,
  37. }
  38. }
  39. type azureIdentityToken struct {
  40. AccessToken string `json:"access_token"`
  41. RefreshToken string `json:"refresh_token"`
  42. ClientID string `json:"client_id"`
  43. ExpiresIn int64 `json:"expires_in,string"`
  44. ExpiresOn int64 `json:"expires_on,string"`
  45. ExtExpiresIn int64 `json:"ext_expires_in,string"`
  46. NotBefore int64 `json:"not_before,string"`
  47. Resource string `json:"resource"`
  48. TokenType string `json:"token_type"`
  49. }
  50. type azurePayload struct {
  51. jose.Claims
  52. AppID string `json:"appid"`
  53. AppIDAcr string `json:"appidacr"`
  54. IdentityProvider string `json:"idp"`
  55. ObjectID string `json:"oid"`
  56. TenantID string `json:"tid"`
  57. Version string `json:"ver"`
  58. XMSMirID string `json:"xms_mirid"`
  59. }
  60. // Azure is the provisioner that supports identity tokens created from the
  61. // Microsoft Azure Instance Metadata service.
  62. //
  63. // The default audience is "https://management.azure.com/".
  64. //
  65. // If DisableCustomSANs is true, only the internal DNS and IP will be added as a
  66. // SAN. By default it will accept any SAN in the CSR.
  67. //
  68. // If DisableTrustOnFirstUse is true, multiple sign request for this provisioner
  69. // with the same instance will be accepted. By default only the first request
  70. // will be accepted.
  71. //
  72. // Microsoft Azure identity docs are available at
  73. // https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/how-to-use-vm-token
  74. // and https://docs.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service
  75. type Azure struct {
  76. *base
  77. ID string `json:"-"`
  78. Type string `json:"type"`
  79. Name string `json:"name"`
  80. TenantID string `json:"tenantID"`
  81. ResourceGroups []string `json:"resourceGroups"`
  82. SubscriptionIDs []string `json:"subscriptionIDs"`
  83. ObjectIDs []string `json:"objectIDs"`
  84. Audience string `json:"audience,omitempty"`
  85. DisableCustomSANs bool `json:"disableCustomSANs"`
  86. DisableTrustOnFirstUse bool `json:"disableTrustOnFirstUse"`
  87. Claims *Claims `json:"claims,omitempty"`
  88. Options *Options `json:"options,omitempty"`
  89. config *azureConfig
  90. oidcConfig openIDConfiguration
  91. keyStore *keyStore
  92. ctl *Controller
  93. }
  94. // GetID returns the provisioner unique identifier.
  95. func (p *Azure) GetID() string {
  96. if p.ID != "" {
  97. return p.ID
  98. }
  99. return p.GetIDForToken()
  100. }
  101. // GetIDForToken returns an identifier that will be used to load the provisioner
  102. // from a token.
  103. func (p *Azure) GetIDForToken() string {
  104. return p.TenantID
  105. }
  106. // GetTokenID returns the identifier of the token. The default value for Azure
  107. // the SHA256 of "xms_mirid", but if DisableTrustOnFirstUse is set to true, then
  108. // it will be the token kid.
  109. func (p *Azure) GetTokenID(token string) (string, error) {
  110. jwt, err := jose.ParseSigned(token)
  111. if err != nil {
  112. return "", errors.Wrap(err, "error parsing token")
  113. }
  114. // Get claims w/out verification. We need to look up the provisioner
  115. // key in order to verify the claims and we need the issuer from the claims
  116. // before we can look up the provisioner.
  117. var claims azurePayload
  118. if err = jwt.UnsafeClaimsWithoutVerification(&claims); err != nil {
  119. return "", errors.Wrap(err, "error verifying claims")
  120. }
  121. // If TOFU is disabled then allow token re-use. Azure caches the token for
  122. // 24h and without allowing the re-use we cannot use it twice.
  123. if p.DisableTrustOnFirstUse {
  124. return "", ErrAllowTokenReuse
  125. }
  126. sum := sha256.Sum256([]byte(claims.XMSMirID))
  127. return strings.ToLower(hex.EncodeToString(sum[:])), nil
  128. }
  129. // GetName returns the name of the provisioner.
  130. func (p *Azure) GetName() string {
  131. return p.Name
  132. }
  133. // GetType returns the type of provisioner.
  134. func (p *Azure) GetType() Type {
  135. return TypeAzure
  136. }
  137. // GetEncryptedKey is not available in an Azure provisioner.
  138. func (p *Azure) GetEncryptedKey() (kid, key string, ok bool) {
  139. return "", "", false
  140. }
  141. // GetIdentityToken retrieves from the metadata service the identity token and
  142. // returns it.
  143. func (p *Azure) GetIdentityToken(subject, caURL string) (string, error) {
  144. // Initialize the config if this method is used from the cli.
  145. p.assertConfig()
  146. req, err := http.NewRequest("GET", p.config.identityTokenURL, http.NoBody)
  147. if err != nil {
  148. return "", errors.Wrap(err, "error creating request")
  149. }
  150. req.Header.Set("Metadata", "true")
  151. resp, err := http.DefaultClient.Do(req)
  152. if err != nil {
  153. return "", errors.Wrap(err, "error getting identity token, are you in a Azure VM?")
  154. }
  155. defer resp.Body.Close()
  156. b, err := io.ReadAll(resp.Body)
  157. if err != nil {
  158. return "", errors.Wrap(err, "error reading identity token response")
  159. }
  160. if resp.StatusCode >= 400 {
  161. return "", errors.Errorf("error getting identity token: status=%d, response=%s", resp.StatusCode, b)
  162. }
  163. var identityToken azureIdentityToken
  164. if err := json.Unmarshal(b, &identityToken); err != nil {
  165. return "", errors.Wrap(err, "error unmarshaling identity token response")
  166. }
  167. return identityToken.AccessToken, nil
  168. }
  169. // Init validates and initializes the Azure provisioner.
  170. func (p *Azure) Init(config Config) (err error) {
  171. switch {
  172. case p.Type == "":
  173. return errors.New("provisioner type cannot be empty")
  174. case p.Name == "":
  175. return errors.New("provisioner name cannot be empty")
  176. case p.TenantID == "":
  177. return errors.New("provisioner tenantId cannot be empty")
  178. case p.Audience == "": // use default audience
  179. p.Audience = azureDefaultAudience
  180. }
  181. // Initialize config
  182. p.assertConfig()
  183. // Decode and validate openid-configuration endpoint
  184. if err = getAndDecode(p.config.oidcDiscoveryURL, &p.oidcConfig); err != nil {
  185. return
  186. }
  187. if err := p.oidcConfig.Validate(); err != nil {
  188. return errors.Wrapf(err, "error parsing %s", p.config.oidcDiscoveryURL)
  189. }
  190. // Get JWK key set
  191. if p.keyStore, err = newKeyStore(p.oidcConfig.JWKSetURI); err != nil {
  192. return
  193. }
  194. p.ctl, err = NewController(p, p.Claims, config, p.Options)
  195. return
  196. }
  197. // authorizeToken returns the claims, name, group, subscription, identityObjectID, error.
  198. func (p *Azure) authorizeToken(token string) (*azurePayload, string, string, string, string, error) {
  199. jwt, err := jose.ParseSigned(token)
  200. if err != nil {
  201. return nil, "", "", "", "", errs.Wrap(http.StatusUnauthorized, err, "azure.authorizeToken; error parsing azure token")
  202. }
  203. if len(jwt.Headers) == 0 {
  204. return nil, "", "", "", "", errs.Unauthorized("azure.authorizeToken; azure token missing header")
  205. }
  206. var found bool
  207. var claims azurePayload
  208. keys := p.keyStore.Get(jwt.Headers[0].KeyID)
  209. for _, key := range keys {
  210. if err := jwt.Claims(key.Public(), &claims); err == nil {
  211. found = true
  212. break
  213. }
  214. }
  215. if !found {
  216. return nil, "", "", "", "", errs.Unauthorized("azure.authorizeToken; cannot validate azure token")
  217. }
  218. if err := claims.ValidateWithLeeway(jose.Expected{
  219. Audience: []string{p.Audience},
  220. Issuer: p.oidcConfig.Issuer,
  221. Time: time.Now(),
  222. }, 1*time.Minute); err != nil {
  223. return nil, "", "", "", "", errs.Wrap(http.StatusUnauthorized, err, "azure.authorizeToken; failed to validate azure token payload")
  224. }
  225. // Validate TenantID
  226. if claims.TenantID != p.TenantID {
  227. return nil, "", "", "", "", errs.Unauthorized("azure.authorizeToken; azure token validation failed - invalid tenant id claim (tid)")
  228. }
  229. re := azureXMSMirIDRegExp.FindStringSubmatch(claims.XMSMirID)
  230. if len(re) != 5 {
  231. return nil, "", "", "", "", errs.Unauthorized("azure.authorizeToken; error parsing xms_mirid claim - %s", claims.XMSMirID)
  232. }
  233. var subscription, group, name string
  234. identityObjectID := claims.ObjectID
  235. subscription, group, name = re[1], re[2], re[4]
  236. return &claims, name, group, subscription, identityObjectID, nil
  237. }
  238. // AuthorizeSign validates the given token and returns the sign options that
  239. // will be used on certificate creation.
  240. func (p *Azure) AuthorizeSign(ctx context.Context, token string) ([]SignOption, error) {
  241. _, name, group, subscription, identityObjectID, err := p.authorizeToken(token)
  242. if err != nil {
  243. return nil, errs.Wrap(http.StatusInternalServerError, err, "azure.AuthorizeSign")
  244. }
  245. // Filter by resource group
  246. if len(p.ResourceGroups) > 0 {
  247. var found bool
  248. for _, g := range p.ResourceGroups {
  249. if g == group {
  250. found = true
  251. break
  252. }
  253. }
  254. if !found {
  255. return nil, errs.Unauthorized("azure.AuthorizeSign; azure token validation failed - invalid resource group")
  256. }
  257. }
  258. // Filter by subscription id
  259. if len(p.SubscriptionIDs) > 0 {
  260. var found bool
  261. for _, s := range p.SubscriptionIDs {
  262. if s == subscription {
  263. found = true
  264. break
  265. }
  266. }
  267. if !found {
  268. return nil, errs.Unauthorized("azure.AuthorizeSign; azure token validation failed - invalid subscription id")
  269. }
  270. }
  271. // Filter by Azure AD identity object id
  272. if len(p.ObjectIDs) > 0 {
  273. var found bool
  274. for _, i := range p.ObjectIDs {
  275. if i == identityObjectID {
  276. found = true
  277. break
  278. }
  279. }
  280. if !found {
  281. return nil, errs.Unauthorized("azure.AuthorizeSign; azure token validation failed - invalid identity object id")
  282. }
  283. }
  284. // Template options
  285. data := x509util.NewTemplateData()
  286. data.SetCommonName(name)
  287. if v, err := unsafeParseSigned(token); err == nil {
  288. data.SetToken(v)
  289. }
  290. // Enforce known common name and default DNS if configured.
  291. // By default we'll accept the CN and SANs in the CSR.
  292. // There's no way to trust them other than TOFU.
  293. var so []SignOption
  294. if p.DisableCustomSANs {
  295. // name will work only inside the virtual network
  296. so = append(so,
  297. commonNameValidator(name),
  298. dnsNamesValidator([]string{name}),
  299. ipAddressesValidator(nil),
  300. emailAddressesValidator(nil),
  301. urisValidator(nil),
  302. )
  303. // Enforce SANs in the template.
  304. data.SetSANs([]string{name})
  305. }
  306. templateOptions, err := CustomTemplateOptions(p.Options, data, x509util.DefaultIIDLeafTemplate)
  307. if err != nil {
  308. return nil, errs.Wrap(http.StatusInternalServerError, err, "aws.AuthorizeSign")
  309. }
  310. return append(so,
  311. p,
  312. templateOptions,
  313. // modifiers / withOptions
  314. newProvisionerExtensionOption(TypeAzure, p.Name, p.TenantID),
  315. profileDefaultDuration(p.ctl.Claimer.DefaultTLSCertDuration()),
  316. // validators
  317. defaultPublicKeyValidator{},
  318. newValidityValidator(p.ctl.Claimer.MinTLSCertDuration(), p.ctl.Claimer.MaxTLSCertDuration()),
  319. newX509NamePolicyValidator(p.ctl.getPolicy().getX509()),
  320. p.ctl.newWebhookController(data, linkedca.Webhook_X509),
  321. ), nil
  322. }
  323. // AuthorizeRenew returns an error if the renewal is disabled.
  324. // NOTE: This method does not actually validate the certificate or check it's
  325. // revocation status. Just confirms that the provisioner that created the
  326. // certificate was configured to allow renewals.
  327. func (p *Azure) AuthorizeRenew(ctx context.Context, cert *x509.Certificate) error {
  328. return p.ctl.AuthorizeRenew(ctx, cert)
  329. }
  330. // AuthorizeSSHSign returns the list of SignOption for a SignSSH request.
  331. func (p *Azure) AuthorizeSSHSign(ctx context.Context, token string) ([]SignOption, error) {
  332. if !p.ctl.Claimer.IsSSHCAEnabled() {
  333. return nil, errs.Unauthorized("azure.AuthorizeSSHSign; sshCA is disabled for provisioner '%s'", p.GetName())
  334. }
  335. _, name, _, _, _, err := p.authorizeToken(token)
  336. if err != nil {
  337. return nil, errs.Wrap(http.StatusInternalServerError, err, "azure.AuthorizeSSHSign")
  338. }
  339. signOptions := []SignOption{}
  340. // Enforce host certificate.
  341. defaults := SignSSHOptions{
  342. CertType: SSHHostCert,
  343. }
  344. // Validated principals.
  345. principals := []string{name}
  346. // Only enforce known principals if disable custom sans is true.
  347. if p.DisableCustomSANs {
  348. defaults.Principals = principals
  349. } else {
  350. // Check that at least one principal is sent in the request.
  351. signOptions = append(signOptions, &sshCertOptionsRequireValidator{
  352. Principals: true,
  353. })
  354. }
  355. // Certificate templates.
  356. data := sshutil.CreateTemplateData(sshutil.HostCert, name, principals)
  357. if v, err := unsafeParseSigned(token); err == nil {
  358. data.SetToken(v)
  359. }
  360. templateOptions, err := CustomSSHTemplateOptions(p.Options, data, sshutil.DefaultIIDTemplate)
  361. if err != nil {
  362. return nil, errs.Wrap(http.StatusInternalServerError, err, "azure.AuthorizeSSHSign")
  363. }
  364. signOptions = append(signOptions, templateOptions)
  365. return append(signOptions,
  366. p,
  367. // Validate user SignSSHOptions.
  368. sshCertOptionsValidator(defaults),
  369. // Set the validity bounds if not set.
  370. &sshDefaultDuration{p.ctl.Claimer},
  371. // Validate public key
  372. &sshDefaultPublicKeyValidator{},
  373. // Validate the validity period.
  374. &sshCertValidityValidator{p.ctl.Claimer},
  375. // Require all the fields in the SSH certificate
  376. &sshCertDefaultValidator{},
  377. // Ensure that all principal names are allowed
  378. newSSHNamePolicyValidator(p.ctl.getPolicy().getSSHHost(), nil),
  379. // Call webhooks
  380. p.ctl.newWebhookController(data, linkedca.Webhook_SSH),
  381. ), nil
  382. }
  383. // assertConfig initializes the config if it has not been initialized
  384. func (p *Azure) assertConfig() {
  385. if p.config == nil {
  386. p.config = newAzureConfig(p.TenantID)
  387. }
  388. }