azure.go 17 KB

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