azure.go 16 KB

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