예제 #1
0
파일: SignedTest.cs 프로젝트: dbrgn/pi-vote
        public void SignedDontVerifyTest()
        {
            Option option = new Option(new MultiLanguageString("Test"), new MultiLanguageString(string.Empty), new MultiLanguageString(string.Empty));

              Signed<Option> signed = new Signed<Option>(option, this.admin);

              Assert.IsTrue(signed.VerifySimple());
              Assert.IsFalse(signed.Verify(this.storage, DateTime.Now.AddYears(5)));

              byte[] data = signed.ToBinary();
              data[data.Length / 8]++;
              Signed<Option> badSigned = Serializable.FromBinary<Signed<Option>>(data);

              Assert.IsFalse(badSigned.VerifySimple());
              Assert.IsFalse(badSigned.Verify(this.storage));
        }
예제 #2
0
        /// <summary>
        /// Creates a new voting.
        /// </summary>
        /// <param name="votingParameters">Parameters for the voting.</param>
        /// <param name="authorities">List of authorities to oversee the voting.</param>
        public void CreateVoting(
            IRpcConnection connection,
            Signed<VotingParameters> signedVotingParameters,
            IEnumerable<AuthorityCertificate> authorities)
        {
            if (signedVotingParameters == null)
            throw new PiArgumentException(ExceptionCode.ArgumentNull, "Voting parameters cannot be null.");
              if (authorities == null)
            throw new PiArgumentException(ExceptionCode.ArgumentNull, "Authority list cannot be null.");

              VotingParameters votingParameters = signedVotingParameters.Value;

              if (!signedVotingParameters.Verify(CertificateStorage, votingParameters.VotingBeginDate))
              {
            if (!signedVotingParameters.VerifySimple())
            {
              Logger.Log(LogLevel.Warning,
            "Connection {0}: Admin {1} (unverified) tried to create voting {2} title {3} but the signature was wrong.",
            connection.Id,
            signedVotingParameters.Certificate.Id.ToString(),
            votingParameters.VotingId.ToString(),
            votingParameters.Title.Text);
            }
            else if (signedVotingParameters.Certificate.Validate(CertificateStorage, votingParameters.VotingBeginDate) != CertificateValidationResult.Valid)
            {
              Logger.Log(LogLevel.Warning,
            "Connection {0}: Admin {1} (unverified) tried to create voting {2} title {3} but his certificate status was {4}.",
            connection.Id,
            signedVotingParameters.Certificate.Id.ToString(),
            votingParameters.VotingId.ToString(),
            votingParameters.Title.Text,
            signedVotingParameters.Certificate.Validate(CertificateStorage, votingParameters.VotingBeginDate).ToString());
            }
            else
            {
              Logger.Log(LogLevel.Warning,
            "Connection {0}: Admin {1} (unverified) tried to create voting {2} title {3} but his signature was invalid.",
            connection.Id,
            signedVotingParameters.Certificate.Id.ToString(),
            votingParameters.VotingId.ToString(),
            votingParameters.Title.Text);
            }

            throw new PiSecurityException(ExceptionCode.InvalidSignature, "Invalid signature of voting authority.");
              }

              if (!(signedVotingParameters.Certificate is AdminCertificate))
              {
            Logger.Log(LogLevel.Warning,
              "Connection {0}: Admin {1} (verified) tried to create voting {2} title {3} but he is a {4}.",
              connection.Id,
              signedVotingParameters.Certificate.Id.ToString(),
              votingParameters.VotingId.ToString(),
              votingParameters.Title.Text,
              signedVotingParameters.Certificate.TypeText);
            throw new PiSecurityException(ExceptionCode.NoAuthorizedAdmin, "No authorized admin.");
              }

              if (!CertificateStorage.SignedRevocationLists
            .Any(signedCrl => signedCrl.Verify(CertificateStorage) &&
                          votingParameters.VotingBeginDate >= signedCrl.Value.ValidFrom &&
                          votingParameters.VotingBeginDate <= signedCrl.Value.ValidUntil))
              {
            Logger.Log(LogLevel.Info,
              "Connection {0}: Admin id {1} name {2} tried to create voting {3} title {4} but the voting begin date {5} was not covered by any CRL.",
              connection.Id,
              signedVotingParameters.Certificate.Id.ToString(),
              ((AdminCertificate)signedVotingParameters.Certificate).FullName,
              votingParameters.VotingId.ToString(),
              votingParameters.Title.Text,
              votingParameters.VotingBeginDate.ToString());
            throw new PiSecurityException(ExceptionCode.InvalidSignature, "Voting begin date not covered by CRL.");
              }

              if (votingParameters.P == null)
            throw new PiArgumentException(ExceptionCode.ArgumentNull, "P cannot be null.");
              if (votingParameters.Q == null)
            throw new PiArgumentException(ExceptionCode.ArgumentNull, "Q cannot be null.");
              if (votingParameters.F == null)
            throw new PiArgumentException(ExceptionCode.ArgumentNull, "F cannot be null.");
              if (votingParameters.G == null)
            throw new PiArgumentException(ExceptionCode.ArgumentNull, "G cannot be null.");
              if (!Prime.HasSufficientLength(votingParameters.P, BaseParameters.PrimeBits))
            throw new PiException(ExceptionCode.ArgumentNull, "P is not long enough");
              if (!Prime.HasSufficientLength(votingParameters.Q, BaseParameters.PrimeBits))
            throw new PiException(ExceptionCode.ArgumentNull, "Q is not long enough");
              if (!Prime.IsPrimeUnsure(votingParameters.P))
            throw new PiArgumentException(ExceptionCode.PIsNoPrime, "P is not prime.");
              if (!Prime.IsPrimeUnsure((votingParameters.P - 1) / 2))
            throw new PiArgumentException(ExceptionCode.PIsNoSafePrime, "P is no safe prime.");
              if (!Prime.IsPrimeUnsure(votingParameters.Q))
            throw new PiArgumentException(ExceptionCode.QIsNoPrime, "Q is not prime.");

              if (!votingParameters.AuthorityCount.InRange(3, 23))
            throw new PiArgumentException(ExceptionCode.AuthorityCountOutOfRange, "Authority count out of range.");
              if (!votingParameters.Thereshold.InRange(1, votingParameters.AuthorityCount - 1))
            throw new PiArgumentException(ExceptionCode.TheresholdOutOfRange, "Thereshold out of range.");

              foreach (Question question in votingParameters.Questions)
              {
            if (question.Options.Count() < 2)
              throw new PiArgumentException(ExceptionCode.OptionCountOutOfRange, "Option count out of range.");
            if (!question.MaxVota.InRange(1, question.Options.Count()))
              throw new PiArgumentException(ExceptionCode.MaxVotaOutOfRange, "Maximum vota out of range.");
              }

              if (votingParameters.AuthorityCount != authorities.Count())
            throw new PiArgumentException(ExceptionCode.AuthorityCountMismatch, "Authority count does not match number of provided authorities.");
              if (!authorities.All(authority => authority.Validate(CertificateStorage, votingParameters.VotingBeginDate) == CertificateValidationResult.Valid))
            throw new PiArgumentException(ExceptionCode.AuthorityInvalid, "Authority certificate invalid or not recognized.");

              MySqlCommand insertCommand = new MySqlCommand("INSERT INTO voting (Id, Parameters, Status) VALUES (@Id, @Parameters, @Status)", DbConnection);
              insertCommand.Parameters.AddWithValue("@Id", votingParameters.VotingId.ToByteArray());
              insertCommand.Parameters.AddWithValue("@Parameters", signedVotingParameters.ToBinary());
              insertCommand.Parameters.AddWithValue("@Status", (int)VotingStatus.New);
              insertCommand.ExecuteNonQuery();

              Logger.Log(LogLevel.Info, "Connection {0}: Voting id {1} title {2} is created.", connection.Id, votingParameters.VotingId.ToString(), votingParameters.Title.Text);

              VotingServerEntity voting = new VotingServerEntity(this, signedVotingParameters, CertificateStorage, this.serverCertificate);
              authorities.Foreach(authority => voting.AddAuthority(connection, authority));
              this.votings.Add(voting.Id, voting);
              voting.SendAuthorityActionRequiredMail(MailType.AuthorityCreateSharesGreen);
        }
예제 #3
0
        /// <summary>
        /// Add a sign check.
        /// </summary>
        /// <param name="signedSignCheck">Signed sign check.</param>
        public void AddSignatureRequestSignCheck(
            IRpcConnection connection,
            Signed<SignatureRequestSignCheck> signedSignCheck)
        {
            if (!signedSignCheck.Verify(CertificateStorage))
              {
            if (signedSignCheck.VerifySimple())
            {
              Logger.Log(LogLevel.Warning,
            "Connection {0}: Server id {1} (unverified) tried to add a sign check, but his certificate status was {2}.",
            connection.Id,
            signedSignCheck.Certificate.Id.ToString(),
            signedSignCheck.Certificate.Validate(CertificateStorage).Text());
            }
            else
            {
              Logger.Log(LogLevel.Warning,
            "Connection {0}: Server id {1} (unverified) tried to add a sign check, but the signature was invalid.",
            connection.Id,
            signedSignCheck.Certificate.Id.ToString());
            }

            throw new PiSecurityException(ExceptionCode.InvalidSignature, "Signature on sign check invalid.");
              }

              if (!(signedSignCheck.Certificate is ServerCertificate))
              {
            Logger.Log(LogLevel.Warning,
              "Connection {0}: Server id {1} (verified) tried to add a sign check, but he is not a server.",
              connection.Id,
              signedSignCheck.Certificate.Id.ToString());
            throw new PiSecurityException(ExceptionCode.SignCheckNotFromServer, "Signature on sign check not from server.");
              }

              var signCheck = signedSignCheck.Value;
              Signed<SignatureResponse> signatureResponse = null;
              var status = GetSignatureResponseStatus(signCheck.Certificate.Id, out signatureResponse);

              if (status != SignatureResponseStatus.Pending)
              {
            Logger.Log(LogLevel.Warning,
              "Connection {0}: Notary id {1} (unverified) tried to a sign check to id {2}, but its status was {3}.",
              connection.Id,
              signCheck.Cookie.Certificate.Id.ToString(),
              signCheck.Certificate.Id.ToString(),
              status.ToString());
            throw new PiException(ExceptionCode.SignCheckResponseStateMismatch, "Signature response status mismatch.");
              }

              if (!signCheck.Cookie.Verify(CertificateStorage))
              {
            if (signCheck.Cookie.VerifySimple())
            {
              Logger.Log(LogLevel.Warning,
            "Connection {0}: Notary id {1} (unverified) tried to a sign check to id {2}, but his certificate status was {3}.",
            connection.Id,
            signCheck.Cookie.Certificate.Id.ToString(),
            signCheck.Certificate.Id.ToString(),
            signCheck.Cookie.Certificate.Validate(CertificateStorage).Text());
            }
            else
            {
              Logger.Log(LogLevel.Warning,
            "Connection {0}: Notary id {1} (unverified) tried to a sign check to id {2}, but the signature was invalid.",
            connection.Id,
            signCheck.Cookie.Certificate.Id.ToString(),
            signCheck.Certificate.Id.ToString());
            }

            throw new PiSecurityException(ExceptionCode.SignCheckCookieSignatureInvalid, "Signature on sign check cookie invalid.");
              }

              if (!(signCheck.Cookie.Certificate is AuthorityCertificate ||
            signCheck.Cookie.Certificate is NotaryCertificate))
              {
            Logger.Log(LogLevel.Warning,
              "Connection {0}: Notary id {1} (unverified) tried to a sign check to id {2}, but he is not an authority or notary.",
              connection.Id,
              signCheck.Cookie.Certificate.Id.ToString(),
              signCheck.Certificate.Id.ToString());
            throw new PiSecurityException(ExceptionCode.SignCheckCookieNotFromNotary, "Signature on sign check cookie not from notary.");
              }

              Signed<SignCheckCookie> dbCookie = null;

              var reader = DbConnection.ExecuteReader(
            "SELECT Cookie FROM signcheckcookie WHERE NotaryId = @NotaryId",
            "@NotaryId",
            signCheck.Cookie.Certificate.Id.ToByteArray());

              if (reader.Read())
              {
            dbCookie = Serializable.FromBinary<Signed<SignCheckCookie>>(reader.GetBlob(0));
            reader.Close();
              }
              else
              {
            reader.Close();
            throw new PiSecurityException(ExceptionCode.SignCheckCookieNotFound, "Sign check cookie not found.");
              }

              if (dbCookie.Certificate.Fingerprint != signCheck.Cookie.Certificate.Fingerprint)
            throw new PiSecurityException(ExceptionCode.SignCheckCookieFingerprintMismatch, "Fingerprint on sign check cookie does not match.");
              if (!dbCookie.Value.Randomness.Equal(signCheck.Cookie.Value.Randomness))
            throw new PiSecurityException(ExceptionCode.SignCheckCookieRandomnessMismatch, "Randomness of sign check cookie does not match.");

              MySqlCommand insertCommand = new MySqlCommand("INSERT INTO signcheck (CertificateId, Value) VALUES (@CertificateId, @Value)", DbConnection);
              insertCommand.Parameters.AddWithValue("@CertificateId", signedSignCheck.Value.Certificate.Id.ToByteArray());
              insertCommand.Parameters.AddWithValue("@Value", signedSignCheck.ToBinary());
              insertCommand.ExecuteNonQuery();

              Logger.Log(LogLevel.Info,
            "Connection {0}: Notary {1}, {2} has signed signature request {3}",
            connection.Id,
            signCheck.Cookie.Certificate.Id.ToString(),
            signCheck.Cookie.Certificate.FullName,
            signCheck.Certificate.Id.ToString());
        }
예제 #4
0
        public byte[] SetSignCheckCookie(
            IRpcConnection connection,
            Signed<SignCheckCookie> signedCookie)
        {
            if (!signedCookie.Verify(CertificateStorage))
              {
            if (signedCookie.VerifySimple())
            {
              Logger.Log(LogLevel.Warning,
            "Connection {0}: Notary id {1} (unverified) tried to set his sign check cookie, but his certificate status was {2}.",
            connection.Id,
            signedCookie.Certificate.Id.ToString(),
            signedCookie.Certificate.Validate(CertificateStorage).Text());
            }
            else
            {
              Logger.Log(LogLevel.Warning,
            "Connection {0}: Notary id {1} (unverified) tried to set his sign check cookie, but the signature was invalid.",
            connection.Id,
            signedCookie.Certificate.Id.ToString());
            }

            throw new PiSecurityException(ExceptionCode.InvalidSignature, "Invalid signature.");
              }

              if (!(signedCookie.Certificate is AuthorityCertificate ||
            signedCookie.Certificate is NotaryCertificate))
              {
            Logger.Log(LogLevel.Warning,
              "Connection {0}: Notary id {0} (verified) tried to set his sign check cookie, but he is no authority or notary.",
              connection.Id,
              signedCookie.Certificate.Id.ToString());
            throw new PiSecurityException(ExceptionCode.SignCheckCookieNotFromNotary, "Not from proper authority or notary.");
              }

              this.DbConnection.ExecuteNonQuery(
            "DELETE FROM signcheckcookie WHERE NotaryId = @NotaryId",
            "@NotaryId",
            signedCookie.Certificate.Id.ToByteArray());

              var rng = RandomNumberGenerator.Create();
              byte[] code = new byte[32];
              rng.GetBytes(code);
              byte[] encryptedCode = signedCookie.Certificate.Encrypt(code);

              MySqlCommand insertCommand = new MySqlCommand(
            "INSERT INTO signcheckcookie (NotaryId, Cookie, Code, Expires) VALUES (@NotaryId, @Cookie, @Code, @Expires)",
            this.DbConnection);
              insertCommand.Parameters.AddWithValue("@NotaryId", signedCookie.Certificate.Id.ToByteArray());
              insertCommand.Parameters.AddWithValue("@Cookie", signedCookie.ToBinary());
              insertCommand.Parameters.AddWithValue("@Code", code);
              insertCommand.Parameters.AddWithValue("@Expires", DateTime.Now.AddMinutes(15).ToString("yyyy-MM-dd HH:mm:ss"));
              insertCommand.ExecuteNonQuery();

              Logger.Log(LogLevel.Info,
            "Connection {0}: Notary id {1} (verified) has set his sign check cookie with code {2}.",
            connection.Id,
            signedCookie.Certificate.Id.ToString(),
            code.ToHexString());

              return encryptedCode;
        }
예제 #5
0
        /// <summary>
        /// Sets a signature response.
        /// </summary>
        /// <param name="signatureRequestId">Id of the corresponding request.</param>
        /// <param name="signedSignatureResponse">Signed signature response.</param>
        public void SetSignatureResponse(
            IRpcConnection connection,
            Signed<SignatureResponse> signedSignatureResponse)
        {
            if (!signedSignatureResponse.Verify(CertificateStorage))
              {
            if (signedSignatureResponse.VerifySimple())
            {
              Logger.Log(LogLevel.Warning,
            "Connection {0}: CA id {1} (unverified) tried to set a signature response, but his certificate status was {2}.",
            connection.Id,
            signedSignatureResponse.Certificate.Id.ToString(),
            signedSignatureResponse.Certificate.Validate(CertificateStorage).Text());
            }
            else
            {
              Logger.Log(LogLevel.Warning,
            "Connection {0}: CA id {1} (unverified) tried to set a signature response, but the signature was invalid.",
            connection.Id,
            signedSignatureResponse.Certificate.Id.ToString());
            }

            throw new PiSecurityException(ExceptionCode.InvalidSignature, "Signature response has invalid signature.");
              }

              if (!(signedSignatureResponse.Certificate is CACertificate))
              {
            Logger.Log(LogLevel.Warning,
              "Connection {0}: CA id {1} (unverified) tried to set a signature response, but it's not a CA.",
              connection.Id,
              signedSignatureResponse.Certificate.Id.ToString());
            throw new PiSecurityException(ExceptionCode.SignatureResponseNotFromCA, "Signature response not from proper CA.");
              }

              SignatureResponse signatureResponse = signedSignatureResponse.Value;

              MySqlCommand replaceCommand = new MySqlCommand("REPLACE INTO signatureresponse (Id, Value) VALUES (@Id, @Value)", DbConnection);
              replaceCommand.Parameters.AddWithValue("@Id", signatureResponse.SubjectId.ToByteArray());
              replaceCommand.Parameters.AddWithValue("@Value", signedSignatureResponse.ToBinary());
              replaceCommand.ExecuteNonQuery();

              Logger.Log(LogLevel.Info, "Connection {0}: Signature response for certificate id {1} stored on behalf of CA id {2}.", connection.Id, signatureResponse.SubjectId.ToString(), signedSignatureResponse.Certificate.Id.ToString());

              if (signatureResponse.Status == SignatureResponseStatus.Accepted)
              {
            if (CertificateStorage.Has(signatureResponse.SubjectId))
            {
              Certificate certificate = CertificateStorage.Get(signatureResponse.SubjectId);
              certificate.AddSignature(signatureResponse.Signature);
              CertificateStorage.Add(certificate);
            }

            Secure<SignatureRequestInfo> secureSignatureRequestInfo = GetSignatureRequestInfo(signatureResponse.SubjectId);
            SignatureRequestInfo signatureRequestInfo = secureSignatureRequestInfo.Value.Decrypt(this.serverCertificate);
            if (!signatureRequestInfo.EmailAddress.IsNullOrEmpty())
            {
              SendMail(
            signatureRequestInfo.EmailAddress,
            MailType.VoterRequestApproved,
            signatureRequestInfo.EmailAddress,
            secureSignatureRequestInfo.Certificate.Id.ToString(),
            CertificateTypeText(secureSignatureRequestInfo.Certificate, Language.English),
            CertificateTypeText(secureSignatureRequestInfo.Certificate, Language.German),
            CertificateTypeText(secureSignatureRequestInfo.Certificate, Language.French));
            }
              }
              else
              {
            Secure<SignatureRequestInfo> secureSignatureRequestInfo = GetSignatureRequestInfo(signatureResponse.SubjectId);
            SignatureRequestInfo signatureRequestInfo = secureSignatureRequestInfo.Value.Decrypt(this.serverCertificate);
            if (!signatureRequestInfo.EmailAddress.IsNullOrEmpty())
            {
              SendMail(
            signatureRequestInfo.EmailAddress,
            MailType.VoterRequestDeclined,
            signatureRequestInfo.EmailAddress,
            secureSignatureRequestInfo.Certificate.Id.ToString(),
            CertificateTypeText(secureSignatureRequestInfo.Certificate, Language.English),
            CertificateTypeText(secureSignatureRequestInfo.Certificate, Language.German),
            CertificateTypeText(secureSignatureRequestInfo.Certificate, Language.French),
            signatureResponse.Reason);
            }
              }
        }
예제 #6
0
        /// <summary>
        /// Deposit a ballot.
        /// </summary>
        /// <param name="ballot">Ballot in signed envleope.</param>
        /// <returns>Vote receipt signed by the server.</returns>
        public Signed<VoteReceipt> Vote(
            IRpcConnection connection,
            Signed<Envelope> signedEnvelope)
        {
            if (signedEnvelope == null)
            throw new ArgumentNullException("ballot");

              if (Status != VotingStatus.Voting)
              {
            Logger.Log(LogLevel.Warning,
              "Connection {0}: Voter id {1} (unverified) tried to vote, but status was {2}.",
              connection.Id,
              signedEnvelope.Certificate.Id.ToString(),
              Status.ToString());
            throw new PiArgumentException(ExceptionCode.WrongStatusForOperation, "Wrong status for operation.");
              }

              if (!signedEnvelope.Verify(this.certificateStorage))
              {
            if (signedEnvelope.VerifySimple())
            {
              Logger.Log(LogLevel.Warning,
            "Connection {0}: Voter id {1} (unverified) tried to vote, but his certificate had state {2}.",
            connection.Id,
            signedEnvelope.Certificate.Id.ToString(),
            signedEnvelope.Certificate.Validate(this.certificateStorage).Text());
            }
            else
            {
              Logger.Log(LogLevel.Warning,
            "Connection {0}: Voter id {1} (unverified) tried to vote, but the signature on envelope was invalid.",
            connection.Id,
            signedEnvelope.Certificate.Id.ToString());
            }

            throw new PiArgumentException(ExceptionCode.VoteSignatureNotValid, "Vote signature not valid.");
              }

              if (!(signedEnvelope.Certificate is VoterCertificate))
              {
            Logger.Log(LogLevel.Warning,
              "Connection {0}: Voter id {1} (verified) tried to vote, but his certificate was not a voter certificate.",
              connection.Id,
              signedEnvelope.Certificate.Id.ToString());
            throw new PiArgumentException(ExceptionCode.NoVoterCertificate, "Not a voter certificate.");
              }

              if (Parameters.GroupId != ((VoterCertificate)signedEnvelope.Certificate).GroupId)
              {
            Logger.Log(LogLevel.Warning,
              "Connection {0}: Voter id {1} (verified) tried to vote, but his group id was {2} when it should have been {3}.",
              connection.Id,
              signedEnvelope.Certificate.Id.ToString(),
              ((VoterCertificate)signedEnvelope.Certificate).GroupId,
              Parameters.GroupId);
            throw new PiArgumentException(ExceptionCode.BadGroupIdInCertificate, "Wrong group id in certificate.");
              }

              var envelope = signedEnvelope.Value;

              if (envelope.Date.Subtract(DateTime.Now).TotalHours < -1d ||
              envelope.Date.Subtract(DateTime.Now).TotalHours > 1d)
              {
            Logger.Log(LogLevel.Warning,
              "Connection {0}: Voter id {1} (verified) tried to vote, but the envelope was created at {2} and pushed at {3}.",
              connection.Id,
              signedEnvelope.Certificate.Id.ToString(),
              envelope.Date.ToString(),
              DateTime.Now.ToString());
            throw new PiArgumentException(ExceptionCode.InvalidEnvelopeBadDateTime, "Invalid envelope. Date out of range.");
              }

              if (envelope.VoterId != signedEnvelope.Certificate.Id)
              {
            Logger.Log(LogLevel.Warning,
              "Connection {0}: Voter id {1} (verified) tried to vote, but the envelope voter id did not match his certificate.",
              connection.Id,
              signedEnvelope.Certificate.Id.ToString());
            throw new PiArgumentException(ExceptionCode.InvalidEnvelopeBadVoterId, "Invalid envelope. Voter id does not match.");
              }

              if (envelope.Ballots.Count != Parameters.Questions.Count())
              {
            Logger.Log(LogLevel.Warning,
              "Connection {0}: Voter id {1} (verified) tried to vote, but there were {2} ballots in the envelope for {3} questions.",
              connection.Id,
              signedEnvelope.Certificate.Id.ToString(),
              envelope.Ballots.Count,
              Parameters.Questions.Count());
            throw new PiArgumentException(ExceptionCode.InvalidEnvelopeBadBallotCount, "Invalid envelope. Ballot count does not match.");
              }

              for (int questionIndex = 0; questionIndex < parameters.Questions.Count(); questionIndex++)
              {
            var ballot = envelope.Ballots[questionIndex];
            var question = parameters.Questions.ElementAt(questionIndex);

            if (ballot.SumProves.Count != parameters.ProofCount)
            {
              Logger.Log(LogLevel.Warning,
            "Connection {0}: Voter id {1} (verified) tried to vote, but there were {2} sum proofs present where there sould have been {3}.",
            connection.Id,
            signedEnvelope.Certificate.Id.ToString(),
            ballot.SumProves.Count,
            parameters.ProofCount);
              throw new PiArgumentException(ExceptionCode.InvalidEnvelopeBadProofCount, "Invalid envelope. Number of sum prooves does not match.");
            }

            if (ballot.Votes.Count != question.Options.Count())
            {
              Logger.Log(LogLevel.Warning,
            "Connection {0}: Voter id {1} (verified) tried to vote, but there were {2} votes present for {3} options.",
            connection.Id,
            signedEnvelope.Certificate.Id.ToString(),
            ballot.Votes.Count,
            question.Options.Count());
              throw new PiArgumentException(ExceptionCode.InvalidEnvelopeBadVoteCount, "Invalid envelope. Vote count does not match.");
            }

            if (ballot.Votes.Any(vote => vote.RangeProves.Count != parameters.ProofCount))
            {
              Logger.Log(LogLevel.Warning,
            "Connection {0}: Voter id {1} (verified) tried to vote, but there was the wrong number of range proofs on a vote.",
            connection.Id,
            signedEnvelope.Certificate.Id.ToString());
              throw new PiArgumentException(ExceptionCode.InvalidEnvelopeBadProofCount, "Invalid envelope. Number of range prooves does not match.");
            }
              }

              bool hasVoted = DbConnection.ExecuteHasRows(
            "SELECT count(*) FROM envelope WHERE VotingId = @VotingId AND VoterId = @VoterId",
            "@VotingId", Id.ToByteArray(),
            "@VoterId", signedEnvelope.Certificate.Id.ToByteArray());
              if (hasVoted)
            throw new PiArgumentException(ExceptionCode.AlreadyVoted, "Voter has already voted.");

              MySqlTransaction transaction = DbConnection.BeginTransaction();

              MySqlCommand indexCommand = new MySqlCommand(
            "SELECT max(EnvelopeIndex) + 1 FROM envelope WHERE VotingId = @VotingId",
            DbConnection,
            transaction);
              indexCommand.Add("@VotingId", Id.ToByteArray());
              object indexObject = indexCommand.ExecuteScalar();
              int envelopeIndex = indexObject == DBNull.Value ? 1 : Convert.ToInt32(indexObject);

              MySqlCommand insertCommand = new MySqlCommand(
            "INSERT INTO envelope (VotingId, EnvelopeIndex, VoterId, Value) VALUES (@VotingId, @EnvelopeIndex, @VoterId, @Value)",
            DbConnection,
            transaction);
              insertCommand.Add("@VotingId", Id.ToByteArray());
              insertCommand.Add("@VoterId", signedEnvelope.Certificate.Id.ToByteArray());
              insertCommand.Add("@Value", signedEnvelope.ToBinary());
              insertCommand.Add("@EnvelopeIndex", envelopeIndex);
              insertCommand.ExecuteNonQuery();

              transaction.Commit();

              Logger.Log(LogLevel.Info,
            "Connection {0}: Envelope for certificate id {1} on voting id {2} stored.",
            connection.Id,
            signedEnvelope.Certificate.Id.ToString(),
            Id.ToString());

              VoteReceipt voteReceipt = new VoteReceipt(Parameters, signedEnvelope);

              return new Signed<VoteReceipt>(voteReceipt, this.serverCertificate);
        }
예제 #7
0
        /// <summary>
        /// Deposit a share part from authorities.
        /// </summary>
        /// <param name="signedSharePart">Share part.</param>
        public void DepositShares(
            IRpcConnection connection,
            Signed<SharePart> signedSharePart)
        {
            if (signedSharePart == null)
            throw new ArgumentNullException("shares");

              if (Status != VotingStatus.New)
              {
            Logger.Log(LogLevel.Warning,
              "Connection {0}: Authority id {1} (unverified) tried to deposit shares, but the status was {2}.",
              connection.Id,
              signedSharePart.Certificate.Id.ToString(),
              Status.ToString());
            throw new PiArgumentException(ExceptionCode.WrongStatusForOperation, "Wrong status for operation.");
              }

              SharePart sharePart = signedSharePart.Value;

              Certificate certificate = GetAuthority(sharePart.AuthorityIndex);

              if (!signedSharePart.Verify(this.certificateStorage, Parameters.VotingBeginDate))
              {
            if (signedSharePart.VerifySimple())
            {
              Logger.Log(LogLevel.Warning,
            "Connection {0}: Authority id {1} (unverified) tried to deposit shares, but his certificate had state {2}.",
            connection.Id,
            signedSharePart.Certificate.Id.ToString(),
            signedSharePart.Certificate.Validate(this.certificateStorage, Parameters.VotingBeginDate).Text());
            }
            else
            {
              Logger.Log(LogLevel.Warning,
            "Connection {0}: Authority id {1} (unverified) tried to deposit shares, but the signature was invalid.",
            connection.Id,
            signedSharePart.Certificate.Id.ToString());
            }

            throw new PiSecurityException(ExceptionCode.InvalidSignature, "Bad signature.");
              }

              if (!signedSharePart.Certificate.IsIdentic(certificate))
              {
            Logger.Log(LogLevel.Warning,
              "Connection {0}: Authority id {1} (verified) tried to deposit shares, but his certificate did not match id {2} for authority index {3}.",
              connection.Id,
              signedSharePart.Certificate.Id.ToString(),
              certificate.Id.ToString(),
              sharePart.AuthorityIndex);
            throw new PiSecurityException(ExceptionCode.NoAuthorizedAuthority, "Not signed by proper authority.");
              }

              bool exists = DbConnection.ExecuteHasRows(
            "SELECT count(*) FROM sharepart WHERE VotingId = @VotingId AND AuthorityIndex = @AuthorityIndex",
            "@VotingId", Id.ToByteArray(),
            "@AuthorityIndex", sharePart.AuthorityIndex);

              if (exists)
              {
            Logger.Log(LogLevel.Warning,
              "Connection {0}: uthority id {1} (verified) tried to deposit shares, these were already present.",
              connection.Id,
              signedSharePart.Certificate.Id.ToString());
            throw new PiArgumentException(ExceptionCode.AuthorityHasAlreadyDeposited, "Authority has already deposited shares.");
              }

              MySqlCommand insertCommand = new MySqlCommand("INSERT INTO sharepart (VotingId, AuthorityIndex, Value) VALUES (@VotingId, @AuthorityIndex, @Value)", DbConnection);
              insertCommand.Add("@VotingId", Id.ToByteArray());
              insertCommand.Add("@AuthorityIndex", sharePart.AuthorityIndex);
              insertCommand.Add("@Value", signedSharePart.ToBinary());
              insertCommand.ExecuteNonQuery();

              Logger.Log(LogLevel.Info,
            "Connection {0}: Shares for certificate id {1} on voting id {2} stored.",
            connection.Id,
            signedSharePart.Certificate.Id.ToString(), Id.ToString());

              long depositedSharePartCount = (long)DbConnection.ExecuteScalar(
            "SELECT count(*) FROM sharepart WHERE VotingId = @VotingId",
            "@VotingId", Id.ToByteArray());

              SendAdminAuthorityActivityMail(certificate, "deposited shares");

              if (depositedSharePartCount == this.parameters.AuthorityCount)
              {
            Status = VotingStatus.Sharing;
              }
        }
예제 #8
0
        /// <summary>
        /// Deposit partial deciphers from an authority.
        /// </summary>
        /// <param name="signedPartialDecipherList">Partial decipher list.</param>
        public void DepositPartialDecipher(
            IRpcConnection connection,
            Signed<PartialDecipherList> signedPartialDecipherList)
        {
            if (signedPartialDecipherList == null)
            throw new ArgumentNullException("partialDecipherContainer");

              if (Status != VotingStatus.Deciphering)
              {
            Logger.Log(LogLevel.Warning, "Authority id {0} (unverified) tried to deposit his partial decipher, but the status was {1}.", signedPartialDecipherList.Certificate.Id.ToString(), Status.ToString());
            throw new InvalidOperationException("Wrong status for operation.");
              }

              PartialDecipherList partialDecipherList = signedPartialDecipherList.Value;

              Certificate certificate = GetAuthority(partialDecipherList.AuthorityIndex);

              if (!signedPartialDecipherList.Verify(this.certificateStorage, Parameters.VotingBeginDate))
              {
            if (signedPartialDecipherList.VerifySimple())
            {
              Logger.Log(LogLevel.Warning, "Authority id {0} (unverified) tried to deposit his partial decipher, but his certificate had state {1}.", signedPartialDecipherList.Certificate.Id.ToString(), signedPartialDecipherList.Certificate.Validate(this.certificateStorage, Parameters.VotingBeginDate).Text());
            }
            else
            {
              Logger.Log(LogLevel.Warning, "Authority id {0} (unverified) tried to deposit his partial decipher, but the signature was invalid.", signedPartialDecipherList.Certificate.Id.ToString());
            }

            throw new PiArgumentException(ExceptionCode.InvalidSignature, "Bad signature.");
              }

              if (!signedPartialDecipherList.Certificate.IsIdentic(certificate))
              {
            Logger.Log(LogLevel.Warning, "Authority id {0} (verified) tried to deposit his partial decipher, but his certificate did not match id {1} for authority index {2}.", signedPartialDecipherList.Certificate.Id.ToString(), certificate.Id.ToString(), partialDecipherList.AuthorityIndex);
            throw new PiArgumentException(ExceptionCode.AuthorityInvalid, "Not signed by proper authority.");
              }

              if (partialDecipherList.PartialDeciphers.Count < 4)
              {
            Logger.Log(LogLevel.Warning, "Authority id {0} (verified) tried to deposit his partial decipher, but there were only {1} parts instead of 4.", signedPartialDecipherList.Certificate.Id.ToString(), partialDecipherList.PartialDeciphers.Count);
            throw new PiArgumentException(ExceptionCode.AuthorityCountMismatch, "Your Pi-Vote client is outdated.");
              }

              bool exists = DbConnection.ExecuteHasRows(
            "SELECT count(*) FROM deciphers WHERE VotingId = @VotingId AND AuthorityIndex = @AuthorityIndex",
            "@VotingId", Id.ToByteArray(),
            "@AuthorityIndex", partialDecipherList.AuthorityIndex);
              if (exists)
            throw new ArgumentException("Authority has already deposited shares.");

              MySqlCommand insertCommand = new MySqlCommand("INSERT INTO deciphers (VotingId, AuthorityIndex, Value) VALUES (@VotingId, @AuthorityIndex, @Value)", DbConnection);
              insertCommand.Add("@VotingId", Id.ToByteArray());
              insertCommand.Add("@AuthorityIndex", partialDecipherList.AuthorityIndex);
              insertCommand.Add("@Value", signedPartialDecipherList.ToBinary());
              insertCommand.ExecuteNonQuery();

              Logger.Log(LogLevel.Info, "Connection {0}: Partical deciphers for certificate id {1} on voting id {2} stored.", connection.Id, signedPartialDecipherList.Certificate.Id.ToString(), Id.ToString());

              long depositedShareResponseCount = (long)DbConnection.ExecuteScalar(
            "SELECT count(*) FROM deciphers WHERE VotingId = @VotingId",
            "@VotingId", Id.ToByteArray());

              SendAdminAuthorityActivityMail(certificate, "deposited partial deciphers");

              if (depositedShareResponseCount == this.parameters.Thereshold + 1)
              {
            Status = VotingStatus.Finished;
              }
        }
예제 #9
0
파일: SignedTest.cs 프로젝트: dbrgn/pi-vote
        public void SignedVerifyTest()
        {
            Option option = new Option(new MultiLanguageString("Test"), new MultiLanguageString(string.Empty), new MultiLanguageString(string.Empty));

              Signed<Option> signed = new Signed<Option>(option, this.admin);

              Assert.IsTrue(signed.VerifySimple());
              Assert.IsTrue(signed.Verify(this.storage));

              Assert.IsTrue(signed.Value.ToBinary().Equal(option.ToBinary()));
        }