azure.go 13 KB

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