Esempio n. 1
0
        public static CmsSignedData Generate(IX509Store certificateStore, SignerInfo signerInfo, CmsProcessable content)
        {
            Asn1EncodableVector digestAlgs = new Asn1EncodableVector();

            digestAlgs.Add(signerInfo.DigestAlgorithm);

            DerObjectIdentifier contentTypeOid = new DerObjectIdentifier(CmsObjectIdentifiers.Data.Id);

            Asn1EncodableVector signerInfos = new Asn1EncodableVector();

            signerInfos.Add(signerInfo);

            Asn1Set certificates = CreateDerSetFromList(GetCertificatesFromStore(certificateStore));
            Asn1Set certrevlist  = null;

            ContentInfo encInfo = new ContentInfo(contentTypeOid, null);

            SignedData sd = new SignedData(
                new DerSet(digestAlgs),
                encInfo,
                certificates,
                certrevlist,
                new DerSet(signerInfos));

            ContentInfo contentInfo = new ContentInfo(CmsObjectIdentifiers.SignedData, sd);

            return(new CmsSignedData(content, contentInfo));
        }
Esempio n. 2
0
        public void Store_Local(DataReq store)
        {
            // getting published to - search results - patch

            SignedData signed = SignedData.Decode(store.Data);

            if (signed == null)
            {
                return;
            }

            G2Header embedded = new G2Header(signed.Data);

            // figure out data contained
            if (G2Protocol.ReadPacket(embedded))
            {
                if (embedded.Name == LocationPacket.Data)
                {
                    LocationData location = LocationData.Decode(signed.Data);

                    if (Utilities.CheckSignedData(location.Key, signed.Data, signed.Signature))
                    {
                        Process_LocationData(store, signed, location);
                    }
                    else
                    {
                        Debug.Assert(false);
                    }
                }
            }
        }
Esempio n. 3
0
        private async Task <object> DoInvokeImpl(InvocationInfo info)
        {
            using (_stateHelper.GetFuncWrapper())
            {
                var jsonRequest   = JsonRpcClientProcessor.GetJsonRpcRequest(info);
                var requestPacket = new OneSideSignedRequestPacket()
                {
                    JsonRpcRequest = Encoding.UTF8.GetBytes(jsonRequest.ToString()),
                    SentTime       = await _transport.GetNowTimeFunc().ConfigureAwait(false)
                };
                SignedData <OneSideSignedRequestPacket> signedRequestPacket;
                using (var tempPass = _clientCertPass.TempData)
                {
                    signedRequestPacket = new SignedData <OneSideSignedRequestPacket>(
                        requestPacket,
                        _clientCert,
                        tempPass.Data
                        );
                }
                var serverAnswerData = await _transport.ProcessSignedRequestPacket(
                    signedRequestPacket
                    ).ThrowIfCancelled(_cts.Token).ConfigureAwait(false);

                return(await JsonRpcClientProcessor.GetJsonRpcResult(
                           JObject.Parse(
                               Encoding.UTF8.GetString(
                                   serverAnswerData
                                   )
                               ),
                           info
                           ).ConfigureAwait(false));
            }
        }
 public AnyCredential(ServiceContext serviceContext, bool legacyContext)
 {
     if (legacyContext)
     {
         core.v2_0.credential.CredentialData credential =
             UnmarshalLegacyCredential(serviceContext);
         Legacy      = true;
         Bus         = credential.bus;
         Login       = credential.login;
         Session     = credential.session;
         Ticket      = credential.ticket;
         Hash        = credential.hash;
         LegacyChain = credential.chain;
     }
     else
     {
         CredentialData credential = UnmarshalCredential(serviceContext);
         Legacy  = false;
         Bus     = credential.bus;
         Login   = credential.login;
         Session = credential.session;
         Ticket  = credential.ticket;
         Hash    = credential.hash;
         Chain   = credential.chain;
     }
 }
Esempio n. 5
0
 private CmsSignedData(CmsSignedData c)
 {
     signedData      = c.signedData;
     contentInfo     = c.contentInfo;
     signedContent   = c.signedContent;
     signerInfoStore = c.signerInfoStore;
 }
Esempio n. 6
0
 public void TestCovariantSignedData()
 {
     var passBytes = Encoding.UTF8.GetBytes("TestPassword");
     var testCertificate =
         LightCertificatesHelper.GenerateSelfSignedCertificate(
             ELightCertificateSignType.Rsa,
             2048,
             ELightCertificateEncryptType.Rsa,
             2048,
             EPrivateKeysKeyDerivationFunction.ScryptDefault,
             Guid.NewGuid(),
             "TestCertificate",
             passBytes
         );
     var testB = new B()
     {
         Field1 = 1,
         Field2 = "sdasda",
         Field3 = Guid.NewGuid()
     };
     _output.WriteLine(testB.WriteObjectToJson());
     var testSignedData = new SignedData<B>(
         testB,
         testCertificate,
         passBytes
         );
     var signedData2 = testSignedData.To<A>();
     var testA = signedData2.GetValue();
     _output.WriteLine(testA.WriteObjectToJson());
 }
Esempio n. 7
0
        /// <summary>
        /// ContentInfo constructor - with encapsulated content
        /// </summary>
        /// <param name="sigData">A ContentInfo containing a signedData object.</param>
        public CmsSignedData(
            ContentInfo sigData)
        {
            this.contentInfo = sigData;
            this.signedData  = SignedData.GetInstance(contentInfo.Content);

            //
            // this can happen if the signed message is sent simply to send a
            // certificate chain.
            //
            Asn1Encodable content = signedData.EncapContentInfo.Content;

            if (content != null)
            {
                if (content is Asn1OctetString)
                {
                    this.signedContent = new CmsProcessableByteArray(signedData.EncapContentInfo.ContentType,
                                                                     ((Asn1OctetString)content).GetOctets());
                }
                else
                {
                    this.signedContent = new Pkcs7ProcessableObject(signedData.EncapContentInfo.ContentType, content);
                }
            }
            else
            {
                this.signedContent = null;
            }
        }
        internal static CallChain UnmarshalCallChain(SignedData signed)
        {
            TypeCode chainTypeCode =
                OrbServices.GetSingleton().create_tc_for_type(typeof(CallChain));

            return((CallChain)InterceptorsInitializer.Codec.decode_value(signed.encoded, chainTypeCode));
        }
        public CallerChain MakeChainFor(string entity)
        {
            ConnectionImpl conn = (ConnectionImpl)GetCurrentConnection();

            if (conn == null)
            {
                Logger.Error("Não há conexão para executar a chamada MakeChainFor.");
                throw new NO_PERMISSION(NoLoginCode.ConstVal, CompletionStatus.Completed_No);
            }
            LoginInfo?myLogin = conn.Login;

            if (!myLogin.HasValue)
            {
                Logger.Error("Não há login para executar a chamada MakeChainFor.");
                throw new NO_PERMISSION(NoLoginCode.ConstVal, CompletionStatus.Completed_No);
            }

            try {
                AccessControl acs         = conn.Acs;
                SignedData    signedChain = acs.signChainFor(entity);
                CallChain     callChain   = CallerChainImpl.UnmarshalCallChain(signedChain);
                if (conn.Legacy)
                {
                    SignedCallChain legacySigned = conn.LegacyConverter.signChainFor(entity);
                    return(new CallerChainImpl(callChain.bus, callChain.caller, callChain.target,
                                               callChain.originators, signedChain, legacySigned));
                }
                return(new CallerChainImpl(callChain.bus, callChain.caller, callChain.target,
                                           callChain.originators, signedChain));
            }
            catch (GenericUserException e) {
                Logger.Error("Falha inesperada ao criar uma nova cadeia.", e);
                throw;
            }
        }
Esempio n. 10
0
        public void TestCovariantSignedData()
        {
            var passBytes       = Encoding.UTF8.GetBytes("TestPassword");
            var testCertificate =
                LightCertificatesHelper.GenerateSelfSignedCertificate(
                    ELightCertificateSignType.Rsa,
                    2048,
                    ELightCertificateEncryptType.Rsa,
                    2048,
                    EPrivateKeysKeyDerivationFunction.ScryptDefault,
                    Guid.NewGuid(),
                    "TestCertificate",
                    passBytes
                    );
            var testB = new B()
            {
                Field1 = 1,
                Field2 = "sdasda",
                Field3 = Guid.NewGuid()
            };

            _output.WriteLine(testB.WriteObjectToJson());
            var testSignedData = new SignedData <B>(
                testB,
                testCertificate,
                passBytes
                );
            var signedData2 = testSignedData.To <A>();
            var testA       = signedData2.GetValue();

            _output.WriteLine(testA.WriteObjectToJson());
        }
Esempio n. 11
0
        private void Process_VersionedFile(DataReq data, SignedData signed, VersionedFileHeader header)
        {
            Core.IndexKey(header.KeyID, ref header.Key);

            OpVersionedFile current = GetFile(header.KeyID);

            // if link loaded
            if (current != null)
            {
                // lower version
                if (header.Version < current.Header.Version)
                {
                    if (data != null && data.Source != null)
                    {
                        Store.Send_StoreReq(data.Source, data.LocalProxy, new DataReq(null, current.UserID, Service, DataType, current.SignedHeader));
                    }

                    return;
                }

                // higher version
                else if (header.Version > current.Header.Version)
                {
                    CacheFile(signed, header);
                }
            }

            // else load file, set new header after file loaded
            else
            {
                CacheFile(signed, header);
            }
        }
        public CallerChain ImportChain(byte[] token, string domain)
        {
            ConnectionImpl conn = (ConnectionImpl)GetCurrentConnection();

            if (conn == null)
            {
                throw new NO_PERMISSION(NoLoginCode.ConstVal, CompletionStatus.Completed_No);
            }
            AccessControl          acs    = conn.Acs;
            AsymmetricKeyParameter busKey = conn.BusKey;

            if (busKey == null)
            {
                throw new NO_PERMISSION(NoLoginCode.ConstVal, CompletionStatus.Completed_No);
            }
            byte[]     encryptedToken = Crypto.Encrypt(busKey, token);
            SignedData signedChain    = acs.signChainByToken(encryptedToken, domain);

            try {
                CallChain callChain = CallerChainImpl.UnmarshalCallChain(signedChain);
                return(new CallerChainImpl(callChain.bus, callChain.caller, callChain.target,
                                           callChain.originators, signedChain));
            }
            catch (GenericUserException e) {
                const string message = "Falha inesperada ao importar uma nova cadeia.";
                Logger.Error(message, e);
                throw new OpenBusInternalException(message, e);
            }
        }
Esempio n. 13
0
        private void EndDownload(object[] args)
        {
            SignedData          signedHeader = args[0] as SignedData;
            VersionedFileHeader header       = args[1] as VersionedFileHeader;

            CacheFile(signedHeader, header);
        }
 public CallerChain DecodeChain(byte[] encoded)
 {
     try {
         VersionedData[] versions = DecodeExportedVersions(encoded,
                                                           _magicTagCallChain);
         CallerChainImpl decodedChain = null;
         for (int i = 0; i < versions.Length; i++)
         {
             // Se houver duas versões, a versão atual virá antes da versão legacy.
             if (versions[i].version == ExportVersion.ConstVal)
             {
                 TypeCode signedDataTypeCode =
                     ORB.create_tc_for_type(typeof(SignedData));
                 SignedData exportedChain =
                     (SignedData)
                     _codec.decode_value(versions[i].encoded, signedDataTypeCode);
                 CallChain chain = CallerChainImpl.UnmarshalCallChain(exportedChain);
                 if (decodedChain == null)
                 {
                     decodedChain = new CallerChainImpl(chain.bus, chain.caller,
                                                        chain.target, chain.originators, exportedChain);
                 }
                 else
                 {
                     decodedChain.Signed.Chain = exportedChain;
                 }
             }
             if (versions[i].version == CurrentVersion.ConstVal)
             {
                 TypeCode exportedChainTypeCode =
                     ORB.create_tc_for_type(typeof(ExportedCallChain));
                 ExportedCallChain exportedChain =
                     (ExportedCallChain)
                     _codec.decode_value(versions[i].encoded, exportedChainTypeCode);
                 core.v2_0.services.access_control.CallChain chain =
                     CallerChainImpl.UnmarshalLegacyCallChain(exportedChain.signedChain);
                 if (decodedChain == null)
                 {
                     decodedChain = new CallerChainImpl(exportedChain.bus, chain.caller,
                                                        chain.target, chain.originators, exportedChain.signedChain);
                 }
                 else
                 {
                     decodedChain.Signed.LegacyChain = exportedChain.signedChain;
                 }
             }
         }
         if (decodedChain != null)
         {
             return(decodedChain);
         }
     }
     catch (GenericUserException e) {
         const string message =
             "Falha inesperada ao decodificar uma cadeia exportada.";
         Logger.Error(message, e);
         throw new InvalidEncodedStreamException(message, e);
     }
     throw new InvalidEncodedStreamException("Versão de cadeia incompatível.");
 }
Esempio n. 15
0
 private CmsSignedData(CmsSignedData c)
 {
     this.signedData      = c.signedData;
     this.contentInfo     = c.contentInfo;
     this.signedContent   = c.signedContent;
     this.signerInfoStore = c.signerInfoStore;
 }
 public static bool Validate(SignedData signedData)
 {
     //todo: Signature will be validated using parameter fields
     //now always return signature is valid
     //todo: add real implementation code
     return(true);
 }
Esempio n. 17
0
    public static CmsSignedData ReplaceSigners(CmsSignedData signedData, SignerInformationStore signerInformationStore)
    {
        CmsSignedData cmsSignedData = new CmsSignedData(signedData);

        cmsSignedData.signerInfoStore = signerInformationStore;
        Asn1EncodableVector asn1EncodableVector  = new Asn1EncodableVector();
        Asn1EncodableVector asn1EncodableVector2 = new Asn1EncodableVector();

        foreach (SignerInformation signer in signerInformationStore.GetSigners())
        {
            asn1EncodableVector.Add(Helper.FixAlgID(signer.DigestAlgorithmID));
            asn1EncodableVector2.Add(signer.ToSignerInfo());
        }
        Asn1Set      asn1Set      = new DerSet(asn1EncodableVector);
        Asn1Set      asn1Set2     = new DerSet(asn1EncodableVector2);
        Asn1Sequence asn1Sequence = (Asn1Sequence)signedData.signedData.ToAsn1Object();

        asn1EncodableVector2 = new Asn1EncodableVector(asn1Sequence[0], asn1Set);
        for (int i = 2; i != asn1Sequence.Count - 1; i++)
        {
            asn1EncodableVector2.Add(asn1Sequence[i]);
        }
        asn1EncodableVector2.Add(asn1Set2);
        cmsSignedData.signedData  = SignedData.GetInstance(new BerSequence(asn1EncodableVector2));
        cmsSignedData.contentInfo = new ContentInfo(cmsSignedData.contentInfo.ContentType, cmsSignedData.signedData);
        return(cmsSignedData);
    }
Esempio n. 18
0
        public void TestAuth()
        {
            var(privateRSAParameters, publicRSAParameters) = GenerateRSAKey();
            TestAddUser("adam", publicRSAParameters);
            var signedData = new SignedData
            {
                Content   = Encoding.UTF8.GetBytes(DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString()),
                PublicKey = publicRSAParameters
            };

            signedData.GenerateSignedData(privateRSAParameters);
            Assert.AreEqual(HttpStatusCode.OK, TestAuthSendRequest(signedData));

            signedData.Content = Encoding.UTF8.GetBytes((DateTimeOffset.UtcNow.ToUnixTimeSeconds() + 40).ToString());
            signedData.GenerateSignedData(privateRSAParameters);
            Assert.AreEqual(HttpStatusCode.OK, TestAuthSendRequest(signedData));

            var badSignedData = (SignedData)signedData.Clone();

            badSignedData.SHA256Hash[0] = 0;
            Assert.AreEqual(HttpStatusCode.Unauthorized, TestAuthSendRequest(badSignedData));

            badSignedData = (SignedData)signedData.Clone();
            badSignedData.Signature[0] = 0;
            Assert.AreEqual(HttpStatusCode.Unauthorized, TestAuthSendRequest(badSignedData));

            badSignedData = (SignedData)signedData.Clone();
            badSignedData.PublicKey.Modulus[0] = 0;
            Assert.AreEqual(HttpStatusCode.Unauthorized, TestAuthSendRequest(badSignedData));
        }
Esempio n. 19
0
        public static bool Validate(SignedData signedData)
        {
            AsymmetricKeyParameter publicKeyParameter = decodePublicKeyParameter(signedData.subjectPublicKeyInfo);
            AlgorithmIdentifier    signatureAlgorithm = decodeSignatureAlgorithm(signedData.signatureAlgorithm);
            var verifier = new Asn1VerifierFactory(signatureAlgorithm, publicKeyParameter);

            return(verify(verifier, signatureAlgorithm, signedData.signedData, signedData.signatureValue));
        }
Esempio n. 20
0
 /// <summary>
 /// ContentInfo with detached signature, digests precomputed in hashes.
 /// </summary>
 /// <param name="hashes">A map of precomputed digests for content indexed by name of hash.</param>
 /// <param name="sigData">A ContentInfo containing a signedData object.</param>
 public CmsSignedData(
     IDictionary <DerObjectIdentifier, byte[]> hashes,
     ContentInfo sigData)
 {
     this.hashes      = hashes;
     this.contentInfo = sigData;
     this.signedData  = SignedData.GetInstance(contentInfo.Content);
 }
Esempio n. 21
0
 /// <summary>
 /// ContentInfo constructor - with detached signature.
 /// </summary>
 /// <param name="signedContent">The content that was signed.</param>
 /// <param name="sigData">A ContentInfo containing a signedData object.</param>
 public CmsSignedData(
     ICmsTypedData signedContent,
     ContentInfo sigData)
 {
     this.signedContent = signedContent;
     this.contentInfo   = sigData;
     this.signedData    = SignedData.GetInstance(contentInfo.Content);
 }
Esempio n. 22
0
 public CmsSignedData(
     IDictionary hashes,
     ContentInfo sigData)
 {
     this.hashes      = hashes;
     this.contentInfo = sigData;
     this.signedData  = SignedData.GetInstance(contentInfo.Content);
 }
Esempio n. 23
0
 public static bool Validate(SignedData signedData)
 {
     return(NetCoreSignatureValidator.Validate(signedData));
     //return NeoVMCoreSignatureValidator.Validate(signedData);
     //todo: Signature will be validated using parameter fields
     //now always return signature is valid
     //todo: add real implementation code
 }
Esempio n. 24
0
 public CmsSignedData(
     CmsProcessable signedContent,
     ContentInfo sigData)
 {
     this.signedContent = signedContent;
     this.contentInfo   = sigData;
     this.signedData    = SignedData.GetInstance(contentInfo.Content);
 }
Esempio n. 25
0
 public CmsSignedData(ContentInfo sigData)
 {
     contentInfo = sigData;
     signedData  = SignedData.GetInstance(contentInfo.Content);
     if (signedData.EncapContentInfo.Content != null)
     {
         signedContent = new CmsProcessableByteArray(((Asn1OctetString)signedData.EncapContentInfo.Content).GetOctets());
     }
 }
 internal CallerChainImpl(string busId, LoginInfo caller, string target,
                          LoginInfo[] originators, SignedData signed, SignedCallChain legacySigned)
     : this(busId, target)
 {
     Originators = originators;
     Caller      = caller;
     Signed      = new AnySignedChain(signed, legacySigned);
     Legacy      = false;
 }
Esempio n. 27
0
        public void CreateSign()
        {
            byte[] data = File.ReadAllBytes(Path.Combine(_settings.PackagePath, _manifestFilename));

            X509Certificate2 certificate       = new X509Certificate2(_settings.CertificatePath, _settings.CertificatePassword, X509KeyStorageFlags.Exportable);
            X509Certificate2 intermCertificate = new X509Certificate2(_settings.IntermCertificatePath);

            var privKey = SecurityUtils.GetRsaKeyPair(certificate.GetRSAPrivateKey()).Private;
            var cert    = SecurityUtils.FromX509Certificate(certificate);
            var interm  = SecurityUtils.FromX509Certificate(intermCertificate);

            CmsProcessableByteArray content   = new CmsProcessableByteArray(data);
            CmsSignedDataGenerator  generator = new CmsSignedDataGenerator();

            generator.AddSigner(privKey, cert, CmsSignedGenerator.EncryptionRsa, CmsSignedGenerator.DigestSha256);

            CmsSignedData signedContent = generator.Generate(content, false);
            var           si            = signedContent.GetSignerInfos();
            var           signer        = si.GetSigners().Cast <SignerInformation>().First();

            SignerInfo signerInfo = signer.ToSignerInfo();

            Asn1EncodableVector digestAlgorithmsVector = new Asn1EncodableVector();

            digestAlgorithmsVector.Add(new AlgorithmIdentifier(
                                           algorithm: new DerObjectIdentifier(_oidSHA256),
                                           parameters: DerNull.Instance));

            // Construct SignedData.encapContentInfo
            ContentInfo encapContentInfo = new ContentInfo(
                contentType: new DerObjectIdentifier(_oidPKCS7IdData),
                content: null);

            Asn1EncodableVector certificatesVector = new Asn1EncodableVector();

            certificatesVector.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(cert.GetEncoded())));
            certificatesVector.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(interm.GetEncoded())));

            // Construct SignedData.signerInfos
            Asn1EncodableVector signerInfosVector = new Asn1EncodableVector();

            signerInfosVector.Add(signerInfo.ToAsn1Object());

            // Construct SignedData
            SignedData signedData = new SignedData(
                digestAlgorithms: new DerSet(digestAlgorithmsVector),
                contentInfo: encapContentInfo,
                certificates: new BerSet(certificatesVector),
                crls: null,
                signerInfos: new DerSet(signerInfosVector));

            ContentInfo contentInfo = new ContentInfo(
                contentType: new DerObjectIdentifier(_oidPKCS7IdSignedData),
                content: signedData);

            File.WriteAllBytes(Path.Combine(_settings.PackagePath, _signatureFilename), contentInfo.GetDerEncoded());
        }
Esempio n. 28
0
 protected override void Unpack(Unpacker unpacker)
 {
     base.Unpack(unpacker);
     AccountId    = unpacker.UnpackLong();
     ChainId      = unpacker.UnpackInt();
     ChainIndex   = unpacker.UnpackUInt();
     KeyIndex     = unpacker.UnpackShort();
     Attachements = new SignedData <Attachements>((u) => new Attachements(u), unpacker);
 }
Esempio n. 29
0
 public ClientAttachementsRequestMessage(Attachements attachements, short keyIndex, Key accountKey) : this()
 {
     SetRequestCode();
     Attachements = new SignedData <Attachements>(attachements, accountKey);
     KeyIndex     = keyIndex;
     AccountId    = attachements.AccountId;
     ChainId      = attachements.ChainId;
     ChainIndex   = attachements.ChainIndex;
 }
Esempio n. 30
0
        public void TestAddUserToGroup()
        {
            var(privateRSAParameters, publicRSAParameters) = GenerateRSAKey();
            TestAddUser("adam", publicRSAParameters);
            var signedData = new SignedData
            {
                Content   = Encoding.UTF8.GetBytes(DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString()),
                PublicKey = publicRSAParameters
            };

            signedData.GenerateSignedData(privateRSAParameters);
            var authData = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(signedData)));
            var request  = new HttpRequestMessage(HttpMethod.Post, EndPoint + "api/group");

            request.Headers.Add("Authorization", $"Bearer {authData}");
            request.Content = new StringContent(JsonConvert.SerializeObject(new Group {
                GroupName = "test"
            }),
                                                Encoding.UTF8, "application/json");
            var response = HttpClient.SendAsync(request).Result;

            response.EnsureSuccessStatusCode();
            var group = JsonConvert.DeserializeObject <Group>(response.Content.ReadAsStringAsync().Result);

            request = new HttpRequestMessage(HttpMethod.Get, EndPoint + "api/invite/create/" + group.GroupId);
            request.Headers.Add("Authorization", $"Bearer {authData}");
            response = HttpClient.SendAsync(request).Result;
            response.EnsureSuccessStatusCode();
            var inviteLink =
                JsonConvert.DeserializeObject <GroupInviteLink>(response.Content.ReadAsStringAsync().Result);

            var(privateRSAParameters2, publicRSAParameters2) = GenerateRSAKey();
            TestAddUser("charles", publicRSAParameters2);
            signedData = new SignedData
            {
                Content   = Encoding.UTF8.GetBytes(DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString()),
                PublicKey = publicRSAParameters2
            };
            signedData.GenerateSignedData(privateRSAParameters2);
            authData = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(signedData)));
            request  = new HttpRequestMessage(HttpMethod.Get,
                                              EndPoint + $"api/invite/enter/{inviteLink.GroupInviteLinkId}/{inviteLink.InviteCode}");
            request.Headers.Add("Authorization", $"Bearer {authData}");
            response = HttpClient.SendAsync(request).Result;
            response.EnsureSuccessStatusCode();
            var inviteLink2 = JsonConvert.DeserializeObject <GroupInviteLink>(response.Content.ReadAsStringAsync().Result);

            Assert.AreEqual(group.GroupId, inviteLink2.GroupId);


            request = new HttpRequestMessage(HttpMethod.Get,
                                             EndPoint + $"api/group/1");
            request.Headers.Add("Authorization", $"Bearer {authData}");
            response = HttpClient.SendAsync(request).Result;
            Console.WriteLine(response.Content.ReadAsStringAsync().Result);
        }
Esempio n. 31
0
        private HttpStatusCode TestAuthSendRequest(SignedData signedData)
        {
            var authData = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(signedData)));
            var request  = new HttpRequestMessage(HttpMethod.Get, EndPoint + "api/user/" + 1);

            request.Headers.Add("Authorization", $"Bearer {authData}");
            var response = HttpClient.SendAsync(request).Result;

            return(response.StatusCode);
        }
Esempio n. 32
0
        private void CachePost(SignedData signedHeader, PostHeader header)
        {
            if (Core.InvokeRequired)
                Debug.Assert(false);

            if (header.ParentID == 0 && header.SourceID != header.TargetID)
            {
                Network.UpdateLog("Board", "Post made to board other than source's");
                return;
            }

            if (!File.Exists(GetPostPath(header)))
            {
                DownloadPost(signedHeader, header);
                return;
            }

            // check if current version loaded
            OpPost post = GetPost(header);

            if (post != null && post.Header.Version >= header.Version )
            {
                UpdateGui(post);
                return;
            }

            // put into map
            OpBoard board = GetBoard(header.TargetID);

            if (board == null)
            {
                board = new OpBoard(header.Target);
                BoardMap.SafeAdd(header.TargetID, board);
            }

            PostUID uid = new PostUID(header);

            post = new OpPost();
            post.Header = header;
            post.SignedHeader = signedHeader.Encode(Network.Protocol);
            post.Ident = header.TargetID.GetHashCode() ^ uid.GetHashCode();
            post.Unique = Loading;

            // remove previous version of file, if its different
            OpPost prevPost = board.GetPost(uid);

            if (prevPost != null && GetPostPath(prevPost.Header) != GetPostPath(header))
                try { File.Delete(GetPostPath(prevPost.Header)); }
                catch { }

            board.Posts.SafeAdd(uid,  post);

            // update replies
            if (post.Header.ParentID == 0)
                board.UpdateReplies(post);
            else
            {
                PostUID parentUid = new PostUID(board.UserID, post.Header.ProjectID, post.Header.ParentID);
                OpPost parentPost = board.GetPost(parentUid);

                if (parentPost != null)
                {
                    board.UpdateReplies(parentPost);
                    UpdateGui(post);
                }
            }

            lock (SaveHeaders)
                if (!SaveHeaders.Contains(header.TargetID))
                    SaveHeaders.Add(header.TargetID);

            ushort replies = 0;
            if (SavedReplyCount.SafeTryGetValue(post.Ident, out replies))
            {
                post.Replies = replies;
                SavedReplyCount.SafeRemove(post.Ident);
            }

            UpdateGui(post);

            if (Core.NewsWorthy(header.TargetID, header.ProjectID, true))
                Core.MakeNews(ServiceIDs.Board, "Board updated by " + Core.GetName(header.SourceID), header.SourceID, 0, false);
        }
Esempio n. 33
0
        void DownloadPost(SignedData signed, PostHeader header)
        {
            if (!Utilities.CheckSignedData(header.Source, signed.Data, signed.Signature))
                return;

            FileDetails details = new FileDetails(ServiceID, 0, header.FileHash, header.FileSize, new PostUID(header).ToBytes());

            Core.Transfers.StartDownload(header.TargetID, details, GetPostPath(header), new EndDownloadHandler(EndDownload), new object[] { signed, header });
        }
Esempio n. 34
0
        private void Process_PostHeader(DataReq data, SignedData signed, PostHeader header)
        {
            Core.IndexKey(header.SourceID, ref header.Source);
            Core.IndexKey(header.TargetID, ref header.Target);

            PostUID uid = new PostUID(header);

            OpPost current = GetPost(header.TargetID, uid);

            // if link loaded
            if (current != null)
            {
                // lower version, send update
                if (header.Version < current.Header.Version)
                {
                    if (data != null && data.Source != null)
                        Store.Send_StoreReq(data.Source, data.LocalProxy, new DataReq(null, header.TargetID, ServiceID, 0, current.SignedHeader));

                    return;
                }

                // higher version
                else if (header.Version > current.Header.Version)
                {
                    CachePost(signed, header);
                }

                // equal version do nothing
            }

            // else load file, set new header after file loaded
            else
                CachePost(signed, header);
        }
Esempio n. 35
0
        private void Process_ProjectData(OpTrust trust, SignedData signed, ProjectData project)
        {
            if (!Utilities.CheckSignedData(trust.File.Key, signed.Data, signed.Signature))
                return;

            if (project.ID != 0 && !ProjectNames.SafeContainsKey(project.ID))
                ProjectNames.SafeAdd(project.ID, project.Name);

            trust.AddProject(project.ID, true);

            if (project.ID == 0)
            {
                trust.Name = project.UserName;
                Core.IndexName(trust.UserID, trust.Name);
            }

            OpLink link = trust.GetLink(project.ID);
        }
Esempio n. 36
0
        private void Process_VersionedFile(DataReq data, SignedData signed, VersionedFileHeader header)
        {
            Core.IndexKey(header.KeyID, ref header.Key);

            OpVersionedFile current = GetFile(header.KeyID);

            // if link loaded
            if (current != null)
            {
                // lower version
                if (header.Version < current.Header.Version)
                {
                    if (data != null && data.Source != null)
                        Store.Send_StoreReq(data.Source, data.LocalProxy, new DataReq(null, current.UserID, Service, DataType, current.SignedHeader));

                    return;
                }

                // higher version
                else if (header.Version > current.Header.Version)
                {
                    CacheFile(signed, header);
                }
            }

            // else load file, set new header after file loaded
            else
                CacheFile(signed, header);
        }
Esempio n. 37
0
        private void Download(SignedData signed, VersionedFileHeader header)
        {
            if (!Utilities.CheckSignedData(header.Key, signed.Data, signed.Signature))
            {
                Debug.Assert(false);
                return;
            }

            FileDetails details = new FileDetails(Service, DataType, header.FileHash, header.FileSize, null);

            Core.Transfers.StartDownload(header.KeyID, details, GetFilePath(header), new EndDownloadHandler(EndDownload), new object[] { signed, header } );
        }
Esempio n. 38
0
        private void CacheFile(SignedData signedHeader, VersionedFileHeader header)
        {
            if (Core.InvokeRequired)
                Debug.Assert(false);

            try
            {
                // check if file exists
                string path = "";
                if (header.FileHash != null)
                {
                    path = GetFilePath(header);
                    if (!File.Exists(path))
                    {
                        Download(signedHeader, header);
                        return;
                    }
                }

                // get file
                OpVersionedFile prevFile = GetFile(header.KeyID);

                if (prevFile != null)
                    if (header.Version < prevFile.Header.Version)
                        return; // dont update with older version

                OpVersionedFile newFile = new OpVersionedFile(header.Key);

                // set new header
                newFile.Header = header;
                newFile.SignedHeader = signedHeader.Encode(Network.Protocol);
                newFile.Unique = !Network.Established;

                FileMap.SafeAdd(header.KeyID, newFile);

                RunSaveHeaders = true;

                if(FileAquired != null)
                    FileAquired.Invoke(newFile);

                // delete old file - do after aquired event so invoked (storage) can perform clean up operation
                if (prevFile != null && prevFile.Header.FileHash != null)
                {
                    string oldPath = GetFilePath(prevFile.Header);
                    if (path != oldPath && File.Exists(oldPath))
                        try { File.Delete(oldPath); }
                        catch { }
                }
            }
            catch (Exception ex)
            {
                Core.Network.UpdateLog("VersionedFile", "Error caching data " + ex.Message);
            }
        }
Esempio n. 39
0
        private void Process_UplinkReq(DataReq data, SignedData signed, UplinkRequest request)
        {
            Core.IndexKey(request.KeyID, ref request.Key);
            Core.IndexKey(request.TargetID, ref request.Target);

            if (!Utilities.CheckSignedData(request.Key, signed.Data, signed.Signature))
                return;

            OpTrust requesterTrust = GetTrust(request.KeyID);

            if (requesterTrust != null && requesterTrust.Loaded && requesterTrust.File.Header.Version > request.LinkVersion)
                return;

            // check if target in linkmap, if not add
            OpTrust targetTrust = GetTrust(request.TargetID);

            if (targetTrust == null)
            {
                targetTrust = new OpTrust(new OpVersionedFile(request.Target) );
                TrustMap.SafeAdd(request.TargetID, targetTrust);
            }

            if (targetTrust.Loaded && targetTrust.File.Header.Version > request.TargetVersion)
                return;

            request.Signed = signed.Encode(Network.Protocol); // so we can send it in results / save, later on

            // check for duplicate requests
            OpLink targetLink = targetTrust.GetLink(request.ProjectID);

            if (targetLink != null)
            {
                foreach (UplinkRequest compare in targetLink.Requests)
                    if (Utilities.MemCompare(compare.Signed, request.Signed))
                        return;
            }
            else
            {
                targetTrust.AddProject(request.ProjectID, true);
                targetLink = targetTrust.GetLink(request.ProjectID);
            }

            // add
            targetLink.Requests.Add(request);

            // if target is marked as linked or focused, update link of target and sender
            if (targetTrust.Loaded && (targetTrust.InLocalLinkTree || Core.KeepData.SafeContainsKey(targetTrust.UserID)))
            {
                if (targetTrust.File.Header.Version < request.TargetVersion)
                    Cache.Research(targetTrust.UserID);

                if (requesterTrust == null)
                {
                    requesterTrust = new OpTrust(new OpVersionedFile(request.Key));
                    TrustMap.SafeAdd(request.KeyID, requesterTrust);
                }

                // once new version of requester's link file has been downloaded, interface will be updated
                if (!requesterTrust.Loaded || (requesterTrust.File.Header.Version < request.LinkVersion))
                    Cache.Research(requesterTrust.UserID);
            }

            RunSaveUplinks = true;
        }
Esempio n. 40
0
        private void Process_LinkData(OpTrust trust, SignedData signed, LinkData linkData)
        {
            if (!Utilities.CheckSignedData(trust.File.Key, signed.Data, signed.Signature))
                return;

            Core.IndexKey(linkData.TargetID, ref linkData.Target);

            uint project = linkData.Project;

            OpLink localLink = trust.GetLink(project);

            if (localLink == null)
                return;

            OpTrust targetTrust = GetTrust(linkData.TargetID, false);

            if (targetTrust == null)
            {
                targetTrust = new OpTrust(new OpVersionedFile(linkData.Target));
                TrustMap.SafeAdd(linkData.TargetID, targetTrust);
            }

            targetTrust.AddProject(project, false);
            OpLink targetLink = targetTrust.GetLink(project);

            if (linkData.Uplink)
            {
                localLink.Uplink = targetLink;

                targetLink.Downlinks.Add(localLink);

                // always know a link's trust structure to the top
                if (!targetTrust.Loaded)
                    Cache.Research(targetTrust.UserID);

                //if (targetLink.Uplink == null)
                //    AddRoot(targetLink);
            }

            else
            {
                if (linkData.Title != null)
                    localLink.Titles[targetLink.UserID] = linkData.Title;

                localLink.Confirmed.Add(targetLink.UserID);
            }
        }