예제 #1
0
        /// <summary>
        /// Creates <see cref="AcmeResponse"/> with headers
        /// </summary>
        /// <returns></returns>
        public AcmeResponse CreateResponse()
        {
            var resp = new AcmeResponse
            {
                StatusCode = 200, // OK
            };

            resp.Headers.Link.Add(new LinkHeader($"{Options.BaseAddress}directory", new LinkHeaderItem("rel", "index", true)));
            resp.Headers.ReplayNonce = NonceService.Create();
            return(resp);
        }
예제 #2
0
 /// <inheritdoc/>
 public AcmeResponse GetNonce(AcmeRequest request)
 {
     return(WrapAction((response) =>
     {
         response.Headers.ReplayNonce = NonceService.Create();
         if (request.Method == null ||
             !request.Method.Equals("head", StringComparison.CurrentCultureIgnoreCase))
         {
             response.StatusCode = 204; // No content
         }
     }, request));
 }
예제 #3
0
        public YobitClient(Uri baseAddress, string apiKey, string privateKey)
        {
            _apiKey       = apiKey ?? string.Empty;
            _privateKey   = (privateKey ?? string.Empty).ToSecureString();
            _nonceService = new NonceService(new NonceFileWriter(), new NonceFileReader());

            _httpClient.BaseAddress = baseAddress;
            //_httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            //_httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
            //_httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0");

            //_sha512PrivateKey = new HMACSHA512(Convert.FromBase64String(_privateKey));
            _sha512PrivateKey = new HMACSHA512(Encoding.ASCII.GetBytes(_privateKey.ToUnsecureString()));
        }
예제 #4
0
        private void Initialise(TArgument argument)
        {
            var context = new InitialiseProjectContext
            {
                PrivateVariables = new Dictionary <string, string>(),
                PublicVariables  = new Dictionary <string, string>()
            };

            context.PrivateVariables.Add("MsSql.SaPassword", NonceService.Generate());
            context.PrivateVariables.Add("Sitecore.License", CreateEncodedSitecoreLicense(argument));
            context.PrivateVariables.Add("Sitecore.TelerikEncryptionKey", NonceService.Generate());

            context.MetaData.Add("SitecoreVersion", Version);
            context.MetaData.Add(Constants.MetaData.SitecoreTopology, argument.Topology);

            context.WorkingPath    = argument.WorkingPath;
            context.SourceCodePath = argument.SourceCodePath;
            context.Name           = argument.Name;

            if (!string.IsNullOrEmpty(argument.DockerComposeTemplate))
            {
                context.DockerComposeFilePath = argument.DockerComposeTemplate;
            }
            else
            {
                context.DockerComposeFilePath =
                    Path.Join(TemplatePath, $"{argument.Topology}.template.docker-compose.yml");
            }

            if (!string.IsNullOrEmpty(argument.DockerComposeTemplate))
            {
                context.EnvironmentTemplateFilePath = argument.EnvironmentTemplate;
            }
            else
            {
                context.EnvironmentTemplateFilePath =
                    Path.Join(TemplatePath, $"{argument.Topology}.template.env");
            }

            DoInitialise(argument, context);

            InitialiseProjectPipeline.Execute(context);
        }
예제 #5
0
        protected override void DoInitialise(SitecoreInitialiseArgument argument, InitialiseProjectContext context)
        {
            var identityCertificatePassword = NonceService.Generate();

            var identityCertificate = _certificateService.CreateSelfSignedCertificate("dimmy.sitecore.plugin", "localhost");

            var x509IdentityCertificate2Export       = identityCertificate.Export(X509ContentType.Pfx, identityCertificatePassword);
            var x509IdentityCertificate2Base64String = Convert.ToBase64String(x509IdentityCertificate2Export);

            context.PublicVariables.Add("DevelopmentHelper.HookName", argument.DevelopmentHelperHookName);

            context.PrivateVariables.Add("Sitecore.AdminPassword", NonceService.Generate());
            context.PrivateVariables.Add("Sitecore.MediaRequestProtectionSharedSecret", NonceService.Generate());
            context.PrivateVariables.Add("Sitecore.Id.Secret", NonceService.Generate());
            context.PrivateVariables.Add("Sitecore.Id.CertificatePassword", identityCertificatePassword);
            context.PrivateVariables.Add("Sitecore.Id.Certificate", x509IdentityCertificate2Base64String);
            context.PrivateVariables.Add("Sitecore.Rep.ApiKey", NonceService.Generate());
            context.PrivateVariables.Add("Sitecore.Xc.Engine.Authoring.ClientId", NonceService.Generate());


            context.PublicVariables.Add("Sitecore.Id.HostName", argument.IdHostName);
            context.PublicVariables.Add("Sitecore.Cd.HostName", argument.CdHostName);
            context.PublicVariables.Add("Sitecore.Cm.HostName", argument.CmHostName);

            context.PublicVariables.Add("WindowsVersion", argument.WindowsVersion);

            context.PublicVariables.Add("Sitecore.Xc.GlobalTrustedConnection",
                                        argument.XcGlobalTrustedConnection.ToString());
            context.PublicVariables.Add("Sitecore.Xc.SharedTrustedConnection",
                                        argument.XcSharedTrustedConnection.ToString());

            context.PublicVariables.Add("Sitecore.Xc.Engine.GlobalDatabaseName", argument.XcEngineGlobalDatabaseName);
            context.PublicVariables.Add("Sitecore.Xc.Engine.SharedDatabaseName", argument.XcEngineSharedDatabaseName);

            context.PublicVariables.Add("Sitecore.Xc.Braintree.Environment", argument.XcBraintreeEnvironment);
            context.PublicVariables.Add("Sitecore.Xc.Braintree.MerchantId", argument.XcBraintreeMerchantId);
            context.PublicVariables.Add("Sitecore.Xc.Braintree.PublicKey", argument.XcBraintreePublicKey);
            context.PublicVariables.Add("Sitecore.Xc.Braintree.PrivateKey", argument.XcBraintreePrivateKey);
        }
예제 #6
0
        /// <summary>
        /// Wraps controller action
        /// </summary>
        /// <param name="action">Action</param>
        /// <param name="request">ACME request. If presents wrapper validates JWS</param>
        /// <returns></returns>
        public AcmeResponse WrapAction(Action <AcmeResponse> action, AcmeRequest request, bool UseJwk = false)
        {
            var response = CreateResponse();

            try
            {
                Logger.Info("Request {method} {path} {token}", request.Method, request.Path, request.Token);

                if (request.Method == "POST")
                {
                    #region Check JWS
                    IAccount account = null;

                    // Parse JWT
                    var token  = request.Token;
                    var header = token.GetProtected();
                    try
                    {
                        if (token == null)
                        {
                            throw new Exception("JSON Web Token is empty");
                        }
                    }
                    catch (Exception e)
                    {
                        throw new AcmeException(ErrorType.Unauthorized, "Cannot parse JSON Web Token", System.Net.HttpStatusCode.Unauthorized, e);
                    }

                    if (header.Url == null)
                    {
                        throw new MalformedException("The JWS header MUST have 'url' field");
                    }

                    /// The "jwk" and "kid" fields are mutually exclusive. Servers MUST
                    /// reject requests that contain both.
                    if (header.Key != null && header.KeyID != null)
                    {
                        throw new MalformedException("The JWS header contains both mutually exclusive fields 'jwk' and 'kid'");
                    }

                    if (UseJwk)
                    {
                        if (header.Key == null)
                        {
                            throw new AcmeException(ErrorType.IncorrectResponse, "JWS MUST contain 'jwk' field", System.Net.HttpStatusCode.BadRequest);
                        }
                        if (!token.Verify())
                        {
                            throw new AcmeException(ErrorType.Unauthorized, "JWS signature is invalid", System.Net.HttpStatusCode.Unauthorized);
                        }

                        account = AccountService.FindByPublicKey(header.Key);
                        // If a server receives a POST or POST-as-GET from a deactivated account, it MUST return an error response with status
                        // code 401(Unauthorized) and type "urn:ietf:params:acme:error:unauthorized"
                    }
                    else
                    {
                        if (header.KeyID == null)
                        {
                            throw new AcmeException(ErrorType.IncorrectResponse, "JWS MUST contain 'kid' field", System.Net.HttpStatusCode.BadRequest);
                        }

                        account = AccountService.GetById(GetIdFromLink(header.KeyID));

                        if (!token.Verify(account.Key.GetPublicKey()))
                        {
                            throw new AcmeException(ErrorType.Unauthorized, "JWS signature is invalid", System.Net.HttpStatusCode.Unauthorized);
                        }

                        // Once an account is deactivated, the server MUST NOT accept further
                        // requests authorized by that account's key
                        // https://tools.ietf.org/html/rfc8555#section-7.3.6
                    }
                    if (account != null)
                    {
                        AssertAccountStatus(account);
                    }
                    #endregion

                    #region Check Nonce

                    // The "nonce" header parameter MUST be carried in the protected header of the JWS.
                    var nonce = request.Token.GetProtected().Nonce
                                ?? throw new MalformedException("The 'nonce' header parameter doesn't present in the protected header of the JWS");
                    NonceService.Validate(nonce);

                    #endregion
                }

                // Invoke action
                action.Invoke(response);
            }
            catch (AcmeException e)
            {
                response.StatusCode = (int)e.StatusCode;
                Error error = e;
                response.Content = error;
                Logger.Error(e);
            }
            catch (Exception e)
            {
                response.StatusCode = 500; // Internal Server Error
                Error error = e;
                response.Content = error;
                Logger.Error(e);
            }

            Logger.Info("Response {@response}", response);

            return(response);
        }