Exemple #1
0
 /// <summary>
 /// Constructs a CodeSigner object.
 /// </summary>
 /// <param name="signerCertPath"> The signer's certificate path.
 ///                       It must not be {@code null}. </param>
 /// <param name="timestamp"> A signature timestamp.
 ///                  If {@code null} then no timestamp was generated
 ///                  for the signature. </param>
 /// <exception cref="NullPointerException"> if {@code signerCertPath} is
 ///                              {@code null}. </exception>
 public CodeSigner(CertPath signerCertPath, Timestamp timestamp)
 {
     if (signerCertPath == null)
     {
         throw new NullPointerException();
     }
     this.SignerCertPath_Renamed = signerCertPath;
     this.Timestamp_Renamed      = timestamp;
 }
Exemple #2
0
 /// <summary>
 /// Constructs a Timestamp.
 /// </summary>
 /// <param name="timestamp"> is the timestamp's date and time. It must not be null. </param>
 /// <param name="signerCertPath"> is the TSA's certificate path. It must not be null. </param>
 /// <exception cref="NullPointerException"> if timestamp or signerCertPath is null. </exception>
 public Timestamp(DateTime timestamp, CertPath signerCertPath)
 {
     if (timestamp == null || signerCertPath == null)
     {
         throw new NullPointerException();
     }
     this.Timestamp_Renamed      = new DateTime(timestamp.Ticks);        // clone
     this.SignerCertPath_Renamed = signerCertPath;
 }
Exemple #3
0
        /*
         * Convert an array of certificates to an array of code signers.
         * The array of certificates is a concatenation of certificate chains
         * where the initial certificate in each chain is the end-entity cert.
         *
         * @return An array of code signers or null if none are generated.
         */
        private CodeSigner[] ConvertCertArrayToSignerArray(java.security.cert.Certificate[] certs)
        {
            if (certs == null)
            {
                return(null);
            }

            try
            {
                // Initialize certificate factory
                if (Factory == null)
                {
                    Factory = CertificateFactory.GetInstance("X.509");
                }

                // Iterate through all the certificates
                int i = 0;
                IList <CodeSigner> signers = new List <CodeSigner>();
                while (i < certs.Length)
                {
                    IList <java.security.cert.Certificate> certChain = new List <java.security.cert.Certificate>();
                    certChain.Add(certs[i++]);                     // first cert is an end-entity cert
                    int j = i;

                    // Extract chain of certificates
                    // (loop while certs are not end-entity certs)
                    while (j < certs.Length && certs[j] is X509Certificate && ((X509Certificate)certs[j]).BasicConstraints != -1)
                    {
                        certChain.Add(certs[j]);
                        j++;
                    }
                    i = j;
                    CertPath certPath = Factory.GenerateCertPath(certChain);
                    signers.Add(new CodeSigner(certPath, null));
                }

                if (signers.Count == 0)
                {
                    return(null);
                }
                else
                {
                    return(signers.ToArray());
                }
            }
            catch (CertificateException)
            {
                return(null);                //TODO - may be better to throw an ex. here
            }
        }
Exemple #4
0
 /// <summary>
 /// Creates a {@code CertPathValidatorException} with the specified
 /// detail message, cause, certification path, index, and reason.
 /// </summary>
 /// <param name="msg"> the detail message (or {@code null} if none) </param>
 /// <param name="cause"> the cause (or {@code null} if none) </param>
 /// <param name="certPath"> the certification path that was in the process of
 /// being validated when the error was encountered </param>
 /// <param name="index"> the index of the certificate in the certification path
 /// that caused the error (or -1 if not applicable). Note that
 /// the list of certificates in a {@code CertPath} is zero based. </param>
 /// <param name="reason"> the reason the validation failed </param>
 /// <exception cref="IndexOutOfBoundsException"> if the index is out of range
 /// {@code (index < -1 || (certPath != null && index >=
 /// certPath.getCertificates().size()) } </exception>
 /// <exception cref="IllegalArgumentException"> if {@code certPath} is
 /// {@code null} and {@code index} is not -1 </exception>
 /// <exception cref="NullPointerException"> if {@code reason} is {@code null}
 ///
 /// @since 1.7 </exception>
 public CertPathValidatorException(String msg, Throwable cause, CertPath certPath, int index, Reason reason) : base(msg, cause)
 {
     if (certPath == null && index != -1)
     {
         throw new IllegalArgumentException();
     }
     if (index < -1 || (certPath != null && index >= certPath.Certificates.Count))
     {
         throw new IndexOutOfBoundsException();
     }
     if (reason == null)
     {
         throw new NullPointerException("reason can't be null");
     }
     this.CertPath_Renamed = certPath;
     this.Index_Renamed    = index;
     this.Reason_Renamed   = reason;
 }
        /// <summary>
        /// Validates the specified certification path using the specified
        /// algorithm parameter set.
        /// <para>
        /// The {@code CertPath} specified must be of a type that is
        /// supported by the validation algorithm, otherwise an
        /// {@code InvalidAlgorithmParameterException} will be thrown. For
        /// example, a {@code CertPathValidator} that implements the PKIX
        /// algorithm validates {@code CertPath} objects of type X.509.
        ///
        /// </para>
        /// </summary>
        /// <param name="certPath"> the {@code CertPath} to be validated </param>
        /// <param name="params"> the algorithm parameters </param>
        /// <returns> the result of the validation algorithm </returns>
        /// <exception cref="CertPathValidatorException"> if the {@code CertPath}
        /// does not validate </exception>
        /// <exception cref="InvalidAlgorithmParameterException"> if the specified
        /// parameters or the type of the specified {@code CertPath} are
        /// inappropriate for this {@code CertPathValidator} </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public abstract CertPathValidatorResult engineValidate(CertPath certPath, CertPathParameters params) throws CertPathValidatorException, java.security.InvalidAlgorithmParameterException;
        public abstract CertPathValidatorResult EngineValidate(CertPath certPath, CertPathParameters @params);
Exemple #6
0
        static async Task Main(string[] args)
        {
            var app = new CommandLineApplication();

            app.HelpOption("-h|--help");
            var optionUrl         = app.Option("-u|--url <URL>", "The server url to request", CommandOptionType.SingleValue).IsRequired();
            var optionConnections = app.Option <int>("-c|--connections <N>", "Total number of HTTP connections to open. Default is 10.", CommandOptionType.SingleValue);
            var optionWarmup      = app.Option <int>("-w|--warmup <N>", "Duration of the warmup in seconds. Default is 5.", CommandOptionType.SingleValue);
            var optionDuration    = app.Option <int>("-d|--duration <N>", "Duration of the test in seconds. Default is 5.", CommandOptionType.SingleValue);
            var optionHeaders     = app.Option("-H|--header <HEADER>", "HTTP header to add to request, e.g. \"User-Agent: edge\"", CommandOptionType.MultipleValue);
            var optionVersion     = app.Option("-v|--version <1.0,1.1,2.0>", "HTTP version, e.g. \"2.0\". Default is 1.1", CommandOptionType.SingleValue);
            var optionCertPath    = app.Option("-t|--cert <filepath>", "The path to a cert pfx file.", CommandOptionType.SingleValue);
            var optionCertPwd     = app.Option("-p|--certpwd <password>", "The password for the cert pfx file.", CommandOptionType.SingleValue);

            app.OnExecuteAsync(async cancellationToken =>
            {
                Console.WriteLine("Http Client");
                Console.WriteLine($"args: {string.Join(" ", args)}");

                ServerUrl = optionUrl.Value();

                WarmupTimeSeconds = optionWarmup.HasValue()
                    ? int.Parse(optionWarmup.Value())
                    : 5;

                ExecutionTimeSeconds = optionDuration.HasValue()
                    ? int.Parse(optionDuration.Value())
                    : 5;

                Connections = optionConnections.HasValue()
                    ? int.Parse(optionConnections.Value())
                    : 10;

                Headers = new List <string>(optionHeaders.Values);

                if (!optionVersion.HasValue())
                {
                    Version = HttpVersion.Version11;
                }
                else
                {
                    switch (optionVersion.Value())
                    {
                    case "1.0": Version = HttpVersion.Version10; break;

                    case "1.1": Version = HttpVersion.Version11; break;

                    case "2.0": Version = HttpVersion.Version20; break;

                    default:
                        Console.WriteLine("Unkown HTTP version: {0}", optionVersion.Value());
                        break;
                    }
                }

                if (optionCertPath.HasValue())
                {
                    CertPath = optionCertPath.Value();
                    Console.WriteLine("CerPath: " + CertPath);
                    CertPassword = optionCertPwd.Value();
                    if (CertPath.StartsWith("http", StringComparison.OrdinalIgnoreCase))
                    {
                        Console.WriteLine($"Downloading cert from: {CertPath}");
                        var httpClientHandler = new HttpClientHandler
                        {
                            ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator,
                            AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
                        };

                        var httpClient = new System.Net.Http.HttpClient(httpClientHandler);
                        var bytes      = await httpClient.GetByteArrayAsync(CertPath);
                        Certificate    = new X509Certificate2(bytes, CertPassword);
                        Console.WriteLine("Cert Thumb: " + Certificate.Thumbprint);
                    }
                    else
                    {
                        Console.WriteLine($"Using cert from: {CertPath}");
                        Certificate = new X509Certificate2(CertPath, CertPassword);
                    }
                }

                await RunAsync();
            });

            await app.ExecuteAsync(args);
        }
Exemple #7
0
 /// <summary>
 /// Creates a {@code CertPathValidatorException} with the specified
 /// detail message, cause, certification path, and index.
 /// </summary>
 /// <param name="msg"> the detail message (or {@code null} if none) </param>
 /// <param name="cause"> the cause (or {@code null} if none) </param>
 /// <param name="certPath"> the certification path that was in the process of
 /// being validated when the error was encountered </param>
 /// <param name="index"> the index of the certificate in the certification path
 /// that caused the error (or -1 if not applicable). Note that
 /// the list of certificates in a {@code CertPath} is zero based. </param>
 /// <exception cref="IndexOutOfBoundsException"> if the index is out of range
 /// {@code (index < -1 || (certPath != null && index >=
 /// certPath.getCertificates().size()) } </exception>
 /// <exception cref="IllegalArgumentException"> if {@code certPath} is
 /// {@code null} and {@code index} is not -1 </exception>
 public CertPathValidatorException(String msg, Throwable cause, CertPath certPath, int index) : this(msg, cause, certPath, index, BasicReason.UNSPECIFIED)
 {
 }
Exemple #8
0
        static async Task Main(string[] args)
        {
            var app = new CommandLineApplication();

            app.HelpOption("-h|--help");
            var optionUrl         = app.Option("-u|--url <URL>", "The server url to request. If --har is used, this becomes the new based url for the .HAR file.", CommandOptionType.SingleValue);
            var optionConnections = app.Option <int>("-c|--connections <N>", "Total number of HTTP connections to open. Default is 10.", CommandOptionType.SingleValue);
            var optionWarmup      = app.Option <int>("-w|--warmup <N>", "Duration of the warmup in seconds. Default is 5.", CommandOptionType.SingleValue);
            var optionDuration    = app.Option <int>("-d|--duration <N>", "Duration of the test in seconds. Default is 5.", CommandOptionType.SingleValue);
            var optionHeaders     = app.Option("-H|--header <HEADER>", "HTTP header to add to request, e.g. \"User-Agent: edge\"", CommandOptionType.MultipleValue);
            var optionVersion     = app.Option("-v|--version <1.0,1.1,2.0>", "HTTP version, e.g. \"2.0\". Default is 1.1", CommandOptionType.SingleValue);
            var optionCertPath    = app.Option("-t|--cert <filepath>", "The path to a cert pfx file.", CommandOptionType.SingleValue);
            var optionCertPwd     = app.Option("-p|--certpwd <password>", "The password for the cert pfx file.", CommandOptionType.SingleValue);
            var optionFormat      = app.Option("-f|--format <format>", "The format of the output, e.g., text, json. Default is text.", CommandOptionType.SingleValue);
            var optionQuiet       = app.Option("-q|--quiet", "When set, nothing is rendered on stsdout but the results.", CommandOptionType.NoValue);
            var optionCookies     = app.Option("-c|--cookies", "When set, cookies are ignored.", CommandOptionType.NoValue);
            var optionHar         = app.Option("-h|--har <filename>", "A .har file representing the urls to request.", CommandOptionType.SingleValue);
            var optionHarNoDelay  = app.Option("--har-no-delay", "when set, delays between HAR requests are not followed.", CommandOptionType.NoValue);
            var optionScript      = app.Option("-s|--script <filename>", "A .js script file altering the current client.", CommandOptionType.SingleValue);
            var optionLocal       = app.Option("-l|--local", "Ignore requests outside of the main domain.", CommandOptionType.NoValue);

            app.OnValidate(ctx =>
            {
                if (!optionHar.HasValue() && !optionUrl.HasValue())
                {
                    return(new ValidationResult($"The --{optionUrl.LongName} field is required."));
                }

                return(ValidationResult.Success);
            });

            app.OnExecuteAsync(async cancellationToken =>
            {
                NoHarDelay = optionHarNoDelay.HasValue();

                SendCookies = !optionCookies.HasValue();

                Quiet = optionQuiet.HasValue();

                Local = optionLocal.HasValue();

                Log("Http Client");

                ServerUrl = optionUrl.Value();

                if (optionHar.HasValue())
                {
                    var harFilename = optionHar.Value();

                    if (harFilename.StartsWith("http", StringComparison.OrdinalIgnoreCase))
                    {
                        Console.WriteLine($"Downloading har file {harFilename}");
                        var tempFile = Path.GetTempFileName();

                        using (var downloadStream = await _httpClient.GetStreamAsync(harFilename))
                            using (var fileStream = File.Create(tempFile))
                            {
                                await downloadStream.CopyToAsync(fileStream);
                            }

                        harFilename = tempFile;
                    }

                    if (!File.Exists(harFilename))
                    {
                        Console.WriteLine($"HAR file not found: '{Path.GetFullPath(harFilename)}'");
                        return;
                    }

                    Timelines = TimelineFactory.FromHar(harFilename);

                    var baseUri   = Timelines.First().Uri;
                    var serverUri = String.IsNullOrEmpty(ServerUrl) ? baseUri : new Uri(ServerUrl);

                    // Substitute the base url with the one provided

                    foreach (var timeline in Timelines)
                    {
                        if (baseUri.Host == timeline.Uri.Host || timeline.Uri.Host.EndsWith("." + baseUri.Host))
                        {
                            timeline.Uri = new UriBuilder(serverUri.Scheme, serverUri.Host, serverUri.Port, timeline.Uri.AbsolutePath, timeline.Uri.Query).Uri;
                        }
                    }

                    if (Local)
                    {
                        Timelines = Timelines.Where(x => String.Equals(x.Uri.Host, baseUri.Host, StringComparison.OrdinalIgnoreCase)).ToArray();
                    }
                }
                else
                {
                    Timelines = new[] { new Timeline {
                                            Method = "GET", Uri = new Uri(ServerUrl)
                                        } };
                }

                ServerUrl = optionUrl.Value();

                Format = optionFormat.HasValue() ? optionFormat.Value() : "text";

                WarmupTimeSeconds = optionWarmup.HasValue()
                    ? int.Parse(optionWarmup.Value())
                    : 5;

                ExecutionTimeSeconds = optionDuration.HasValue()
                    ? int.Parse(optionDuration.Value())
                    : 5;

                Connections = optionConnections.HasValue()
                    ? int.Parse(optionConnections.Value())
                    : 10;

                Headers = new List <string>(optionHeaders.Values);

                if (!optionVersion.HasValue())
                {
                    Version = HttpVersion.Version11;
                }
                else
                {
                    switch (optionVersion.Value())
                    {
                    case "1.0": Version = HttpVersion.Version10; break;

                    case "1.1": Version = HttpVersion.Version11; break;

                    case "2.0": Version = HttpVersion.Version20; break;

                    default:
                        Log("Unkown HTTP version: {0}", optionVersion.Value());
                        break;
                    }
                }

                if (optionCertPath.HasValue())
                {
                    CertPath = optionCertPath.Value();
                    Log("CerPath: " + CertPath);
                    CertPassword = optionCertPwd.Value();
                    if (CertPath.StartsWith("http", StringComparison.OrdinalIgnoreCase))
                    {
                        Log($"Downloading certificate: {CertPath}");
                        var httpClientHandler = new HttpClientHandler
                        {
                            ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator,
                            AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
                        };

                        var httpClient = new HttpClient(httpClientHandler);
                        var bytes      = await httpClient.GetByteArrayAsync(CertPath);
                        Certificate    = new X509Certificate2(bytes, CertPassword);
                    }
                    else
                    {
                        Log($"Reading certificate: {CertPath}");
                        Certificate = new X509Certificate2(CertPath, CertPassword);
                    }

                    Log("Certificate Thumbprint: " + Certificate.Thumbprint);
                }

                if (optionScript.HasValue())
                {
                    var scriptFilename = optionScript.Value();

                    if (scriptFilename.StartsWith("http", StringComparison.OrdinalIgnoreCase))
                    {
                        Console.WriteLine($"Downloading script file {scriptFilename}");
                        var tempFile = Path.GetTempFileName();

                        using (var downloadStream = await _httpClient.GetStreamAsync(scriptFilename))
                            using (var fileStream = File.Create(tempFile))
                            {
                                await downloadStream.CopyToAsync(fileStream);
                            }

                        scriptFilename = tempFile;
                    }

                    if (!File.Exists(scriptFilename))
                    {
                        Console.WriteLine($"Script file not found: '{Path.GetFullPath(scriptFilename)}'");
                        return;
                    }

                    Script = File.ReadAllText(scriptFilename);
                }

                await RunAsync();
            });

            await app.ExecuteAsync(args);
        }