azure.go 17 KB

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