Ejemplo n.º 1
0
        public static bool HasLargeAttachments(MailItem mailItem)
        {
            using (var lcfm = new LocalCopyOfFileManager())
            {
                var tempfile = lcfm.GetLocalCopyOfFileTarget(Guid.NewGuid().ToString());
                mailItem.SaveAs(tempfile);

                foreach (Attachment attachment in mailItem.Attachments)
                {
                    try
                    {
                        var file = lcfm.GetLocalCopyOfFileTarget(attachment.FileName);
                        attachment.SaveAsFile(file);
                        var lah = new LargeAttachmentHelper(file);
                        if (lah.IsLargeAttachment)
                        {
                            return true;
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.LogError(e);
                    }
                }
                return false;
            }
        }
Ejemplo n.º 2
0
        public bool OpenActualDocumentFromPlaceHolder(Attachment attachment)
        {
            try
            {
                if (attachment.Size > (1024*5))
                {
                    Logger.LogTrace("Returning without doing anything as the file size is > 5k");
                    return false;
                }

                using (var lcfm = new LocalCopyOfFileManager())
                {
                    string filename = lcfm.GetLocalCopyOfFileTarget(attachment.FileName);
                    attachment.SaveAsFile(filename);

                    Logger.LogTrace("Saving placeholder file to " + filename);
                    var lah = new LargeAttachmentHelper(filename);
                    if (lah.IsLargeAttachment)
                    {
                        Logger.LogTrace("Opening actual file from" + lah.ActualPath);
                        var startInfo = new ProcessStartInfo();
                        startInfo.FileName = lah.ActualPath;
                        Process.Start(startInfo);
                        return true;
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                throw;
            }
        }
Ejemplo n.º 3
0
        public void TestCleanPdfExcludeAttachments()
        {
            var lcfm = new LocalCopyOfFileManager();
            var sourceFile = Path.Combine(TestRoot, "Comments_Bookmarks_Attachments_Markups.pdf");
            var testFile = lcfm.GetLocalCopyOfFileTarget(sourceFile);

            File.Copy(sourceFile, testFile, true);

            var attachment = new ProtectAttachment(FcsFileFactory.Create(testFile, "Comments_Bookmarks_Attachments_Markups"));

            var discoveryTask = new TaskDiscovery(attachment);
            discoveryTask.Execute(new CancellationToken());

            Assert.IsTrue(attachment.RiskAnalysis.DiscoveryResult.GetItemsForType(MetadataType.Attachments).Count > 0);
            Assert.IsTrue(attachment.RiskAnalysis.DiscoveryResult.GetItemsForType(MetadataType.Properties).Count > 0);
            Assert.IsTrue(attachment.RiskAnalysis.DiscoveryResult.GetItemsForType(MetadataType.Bookmarks).Count > 0);
            Assert.IsTrue(attachment.RiskAnalysis.DiscoveryResult.GetItemsForType(MetadataType.Markups).Count > 0);

            var task = new TaskCleanPdf(attachment, new TaskCleanOptions() { ExcludedMetadataTypes = new List<MetadataType>() { MetadataType.Attachments}});
            task.Execute(new CancellationToken());

            discoveryTask.Execute(new CancellationToken());
            Assert.IsTrue(attachment.RiskAnalysis.DiscoveryResult.GetItemsForType(MetadataType.Attachments).Count > 0);
            Assert.IsFalse(attachment.RiskAnalysis.High.ContainsKey(MetadataType.Properties));
            Assert.IsFalse(attachment.RiskAnalysis.High.ContainsKey(MetadataType.Bookmarks));
            Assert.IsFalse(attachment.RiskAnalysis.High.ContainsKey(MetadataType.Markups));

            Assert.IsFalse(attachment.RiskAnalysis.Medium.ContainsKey(MetadataType.Properties));
            Assert.IsFalse(attachment.RiskAnalysis.Medium.ContainsKey(MetadataType.Bookmarks));
            Assert.IsFalse(attachment.RiskAnalysis.Medium.ContainsKey(MetadataType.Markups));

            Assert.IsFalse(attachment.RiskAnalysis.Low.ContainsKey(MetadataType.Properties));
            Assert.IsFalse(attachment.RiskAnalysis.Low.ContainsKey(MetadataType.Bookmarks));
            Assert.IsFalse(attachment.RiskAnalysis.Low.ContainsKey(MetadataType.Markups));
        }
        public void TestGetTempFileRepeated()
        {
			using (LocalCopyOfFileManager fileManager = new LocalCopyOfFileManager())
			{
				string tesfile = fileManager.GetLocalCopyOfFileTarget(m_testFile);
				string testFilePath = string.Format(@"{0}\1\{1}", fileManager.ManagedFolder, m_testFile);
				Assert.AreEqual(testFilePath, tesfile,
				                "Expected the temporay file name to match the managed folder & the test file name");

				System.IO.File.Copy(m_testFilePathName, tesfile, true);
				Assert.AreEqual(true, System.IO.File.Exists(tesfile));

				string updateTestfile = fileManager.GetLocalCopyOfFileTarget(m_testFile);
				Assert.AreNotEqual(tesfile, updateTestfile,
				                   "Expected the file to return a new sub directory path for a file that may exist already in the temp folder");
				Assert.AreEqual(true, updateTestfile.Contains("\\2\\"));
			}
        }
        public void TestGetTempFileNameWithPath()
        {
			using (LocalCopyOfFileManager fileManager = new LocalCopyOfFileManager())
			{
				string tesfile = fileManager.GetLocalCopyOfFileTarget(m_testFilePathName);
				Assert.AreNotEqual("", fileManager.ManagedFolder.ToString(), "Expected file manager to have a temporay directory");
				Assert.AreEqual(true, System.IO.Directory.Exists(fileManager.ManagedFolder.ToString()),
				                "Expected the managed directory to exist");
				string testFilePath = string.Format(@"{0}\1\{1}", fileManager.ManagedFolder, m_testFile);

				Assert.AreEqual(testFilePath, tesfile,
				                "Expected the temporay file name to match the managed folder & the test file name");
			}
        }
Ejemplo n.º 6
0
        public ProtectAttachment(Microsoft.Office.Interop.Outlook.Attachment attachment)
            : this()
        {
            // 17470 [WS 8.0] Protect files is not enabled when .msg with no subject is attached through Right click->send To->Mail Recipient.ZenQ
            Name = attachment.DisplayName ?? "";

            var filename = string.Empty;
            filename = attachment.FileName.ToLower() == ".msg"
                           ? Guid.NewGuid().ToString() + ".msg"
                           : attachment.FileName;
            // --

            Index = attachment.Index.ToString(CultureInfo.InvariantCulture);
            var wsAttachment = attachment as WsAttachment;
            if (wsAttachment != null)
            {
                Id = wsAttachment.Id.ToString();
                RecordKey = wsAttachment.RecordKey;
            }
            _lcofm = new LocalCopyOfFileManager();
            filename = _lcofm.GetLocalCopyOfFileTarget(filename);
            attachment.SaveAsFile(filename);

            var lah = new LargeAttachmentHelper(filename);
            if (lah.IsLargeAttachment)
            {
                LargeAttachmentFileName = filename;
                var tempfile = _lcofm.GetLocalCopyOfFileTarget(Path.GetFileName(lah.ActualPath));
                System.IO.File.Copy(lah.ActualPath, tempfile, true);
                filename = tempfile;
                Name = Path.GetFileName(filename);
            }

            File = FcsFileFactory.Create(filename, Name);
            Position = attachment.Position;
            FileName = filename;
        }
Ejemplo n.º 7
0
        public void TestDocumentTracking()
        {
            var filenames = new List<string>()
                { 
                    "SupportsCleaning.doc",
                    "5DocStats2BuiltInProps.docx",
                    "హాయ్ .docx",
                    "SmallTextComplexDocument.doc",
                    "small.doc",
                    "final.docx",
                    "15Footnotes1Field5DocStats2BuiltInProps.docx"
                };

            filenames.ForEach(delegate(string x)
                {
                    var id = String.Empty;
                    try
                    {
                        var lcfm = new LocalCopyOfFileManager();
                        var sourceFile = Path.Combine(TestRoot, x);
                        Assert.IsTrue(File.Exists(sourceFile), String.Format("File does not exist [{0}]", sourceFile));

                        var testFile = lcfm.GetLocalCopyOfFileTarget(x);
                        File.Copy(sourceFile, testFile, true);
                        Assert.IsTrue(File.Exists(testFile), String.Format("File does not exist [{0}]", testFile));

                        var attachment = new ProtectAttachment(FcsFileFactory.Create(testFile, x));

                        var readyRedlineTask = new TaskReadyRedline(attachment);
                        readyRedlineTask.Execute(new CancellationToken());

                        var intelligentDocument = new IntelligentDocument();
                        intelligentDocument.SetFileName(attachment.FileName);
                        Assert.IsTrue(intelligentDocument.IsDocumentBeingTracked(), String.Format("Failed to add tracking id to test file [{0}]", x));
                        
                        id = intelligentDocument.GetDocumentTrackingId();
                        Assert.IsFalse(String.IsNullOrEmpty(id), String.Format("Failed to get tracking id for test file [{0}]", x));
                        Assert.IsFalse(String.IsNullOrEmpty(GetDocumentChecksum(id)), String.Format("Failed to get checksum for test file [{0}]", x));
                    }
                    finally
                    {
                        DeleteEntry(id);
                    }
                });
        }
Ejemplo n.º 8
0
        public void AddAttachment(WsMailItem mailItem, string sourceFile)
        {
            using (var lcfm = new LocalCopyOfFileManager())
            {
                string displayName = Path.GetFileName(sourceFile) + LargeAttachmentHelper.FileExtension;
                string destinationfile = lcfm.GetLocalCopyOfFileTarget(Path.GetFileName(sourceFile)) +
                                         LargeAttachmentHelper.FileExtension;

                Logger.LogInfo(
                    string.Format(
                        "Add Large Attachment. Source File = {0}, Target DisplayName = {1}, Target File = {2}",
                        sourceFile, displayName, destinationfile));

                var attachmentManager = new BigAttachmentsManager();
                attachmentManager.AddAttachmentPlaceHolder(sourceFile, destinationfile);
                attachmentManager.AddAttachmentToMessage(mailItem, displayName, destinationfile);
            }
        }
Ejemplo n.º 9
0
		private List<SendLinkInfo> GetFilesToUpload(IEnumerable<Attachment> processedAttachments, string id)
		{
			List<SendLinkInfo> files = new List<SendLinkInfo>();

			LocalCopyOfFileManager lcofm = new LocalCopyOfFileManager(false, GetWorkingDirectory(id));
			foreach (Attachment serviceAttachment in processedAttachments)
			{
				string displayName = serviceAttachment.Name;
				FileInfo tempFile = new FileInfo(lcofm.GetLocalCopyOfFileTarget(displayName));
				using (FileStream fs = new FileStream(tempFile.FullName, FileMode.Create))
				{
					fs.Write(serviceAttachment.Content, 0, serviceAttachment.Content.Length);
					fs.Close();
				}
				SendLinkInfo sendLinkInfo = new SendLinkInfo { ContentId = serviceAttachment.Id, DisplayName = displayName, FilePath = tempFile.FullName };
				files.Add(sendLinkInfo);
			}
			return files;
		}
Ejemplo n.º 10
0
        public void TestCleanStripsBinaryData()
        {
            var lcfm = new LocalCopyOfFileManager();
            var sourceFile = Path.Combine(TestRoot, "Small.doc");
            var testFile = lcfm.GetLocalCopyOfFileTarget(sourceFile);

            File.Copy(sourceFile, testFile, true);

            var attachment = new ProtectAttachment(FcsFileFactory.Create(testFile, "Small"));

            var discoveryTask = new TaskDiscovery(attachment);
            discoveryTask.Execute(new CancellationToken());

            Assert.IsTrue(attachment.RiskAnalysis.DiscoveryResult.GetItemsForType(MetadataType.DocumentStatistic).Count > 0);
            Assert.IsTrue(attachment.RiskAnalysis.DiscoveryResult.GetItemsForType(MetadataType.AttachedTemplate).Count > 0);

            var task = new TaskClean(attachment, new TaskCleanOptions());
            task.Execute(new CancellationToken());

            discoveryTask.Execute(new CancellationToken());
            Assert.IsFalse(attachment.RiskAnalysis.HasMetaData);

            new Workshare.API.Cleaning.OfficeApplicationCacheControl().ReleaseOfficeApplications();
        }
Ejemplo n.º 11
0
        public void TestCleanTrackChanges()
        {
            var lcfm = new LocalCopyOfFileManager();
            var sourceFile = Path.Combine(TestRoot, "SmallTextComplexDocument.doc");
            var testFile = lcfm.GetLocalCopyOfFileTarget(sourceFile);

            File.Copy(sourceFile, testFile, true);

            var attachment = new ProtectAttachment(FcsFileFactory.Create(testFile, "SmallTextComplexDocument"));

            var discoveryTask = new TaskDiscovery(attachment);
            discoveryTask.Execute(new CancellationToken());

            Assert.IsTrue(attachment.RiskAnalysis.DiscoveryResult.GetItemsForType(MetadataType.TrackedChange).Count > 0);

            var task = new TaskClean(attachment, new TaskCleanOptions());
            task.Execute(new CancellationToken());

            discoveryTask.Execute(new CancellationToken());
            Assert.IsNull(attachment.RiskAnalysis.DiscoveryResult.GetItemsForType(MetadataType.TrackedChange));
            Assert.IsNull(attachment.RiskAnalysis.DiscoveryResult.GetItemsForType(MetadataType.Comment));

            new Workshare.API.Cleaning.OfficeApplicationCacheControl().ReleaseOfficeApplications();
        }
Ejemplo n.º 12
0
        public void UnPackMessageFile(IProtectAttachment attachment, CancellationToken token)
        {
            if (!IsMsgFile(attachment.FileType))
                return;

            MessageItem message = _mapiUtils.GetItemFromMsgFile(attachment.FileName, false);

            Attachments attachments = message.Attachments;
            for (int i = 1; i <= attachments.Count; ++i)
            {
                if (token.IsCancellationRequested)
                    return;

                Attachment redemptionAttachment = attachments.Item(i);
                if (!MapiSignatureInspector.IsSignature(redemptionAttachment, (OlBodyFormat) message.BodyFormat))
                {
                    var lcfm = new LocalCopyOfFileManager();
                    string tempFile = lcfm.GetLocalCopyOfFileTarget(redemptionAttachment.FileName);
                    redemptionAttachment.SaveAsFile(tempFile);
                    var protectAttachment =
                        new ProtectAttachment(FcsFileFactory.Create(tempFile, redemptionAttachment.DisplayName), lcfm);
                    protectAttachment.Index = redemptionAttachment.Position.ToString();

                    attachment.Children.Add(protectAttachment);

                    if (protectAttachment.FileType == FileType.ZIP || IsMsgFile(protectAttachment.FileType))
                    {
                        UnPack(protectAttachment, token);
                    }
                    
                }

                Marshal.ReleaseComObject(redemptionAttachment);
            }

            Marshal.ReleaseComObject(attachments);
            Marshal.ReleaseComObject(message);
        }
Ejemplo n.º 13
0
        private void CreateZip(string password)
        {
            var lfm = new LocalCopyOfFileManager(true);
            string destination = lfm.GetLocalCopyOfFileTarget("Attachments.zip");
            var attachmentsToRemove = new List<IProtectAttachment>();

            bool hasLargeAttachment = false;
            using (FileStream stream = File.Create(destination))
            {
                var zipStream = new ZipOutputStream(stream);

                zipStream.SetLevel(9); //0-9, 9 being the highest level of compression

                zipStream.Password = password; // optional. Null is the same as not setting. Required if using AES.

                //// This setting will strip the leading part of the folder path in the entries, to
                //// make the entries relative to the starting folder.
                //// To include the full path for each entry up to the drive root, assign folderOffset = 0.
                //int folderOffset = folderName.Length + (folderName.EndsWith("\\") ? 0 : 1);

                foreach (var attachment in _attachments)
                {
                    var fi = new FileInfo(attachment.FileName);
                    string entryName = ZipEntry.CleanName(fi.Name);
                    var newEntry = new ZipEntry(entryName) {DateTime = fi.LastWriteTime};
                    newEntry.IsUnicodeText = true;
                    zipStream.PutNextEntry(newEntry);

                    using (var streamReader = File.OpenRead(attachment.FileName))
                    {
                        streamReader.CopyTo(zipStream);
                    }
                    attachment.Status = PropertyNames.RemovedAttachment;

                    if (!string.IsNullOrEmpty(attachment.LargeAttachmentFileName))
                        hasLargeAttachment = true;

                    attachmentsToRemove.Add(attachment);
                } 


                zipStream.IsStreamOwner = true; // Makes the Close also Close the underlying stream
                zipStream.Close();
            }

            _attachmentsZip = new ProtectAttachment(FcsFileFactory.Create(destination, "Attachments.zip"), lfm) { SupressDiscovery = true };    

            if (hasLargeAttachment)
            {
                var bam = new BigAttachmentsManager();
                bam.AddAttachmentPlaceHolder(destination, destination + ".wsl");
                _attachmentsZip.LargeAttachmentFileName = destination + ".wsl";
            }
                
            
            foreach (var attachment in attachmentsToRemove)
            {
                _attachmentsZip.Children.Add(attachment);
                _attachments.Remove(attachment);
            }

            _attachments.Add(_attachmentsZip);
        }
Ejemplo n.º 14
0
		//Not a test method, a couple of testmethods call it though.
		public void Test_04_TriggerSinglePolicy_WordAttachment_Helper(bool attachmentSwitch)
		{
			IContentScanner scannerService = GetContentScanner();

			using (LocalCopyOfFileManager lcofm = new LocalCopyOfFileManager())
			{
				Request request =
					CreateRequest_Email("", "some message body", "<html><body>some message body</body></html>",
										"Outlook", "*****@*****.**");

				//Going to call scan twice; once with an internal, then again with and external recip.
				//Internal first:
				AddEmailRecipient(request, "*****@*****.**", true);

				string filepath = lcofm.GetLocalCopyOfFileTarget("TriggerPolicy3.doc");
				File.Copy(Path.Combine(TESTPATH, "TriggerPolicy3.doc"), filepath);
				AddAttachment(request, filepath, attachmentSwitch, "application/msword");

				Response response =
					scannerService.Scan(request, null, ProcessLevel.Actions, RunAt.Client);

				AssertValid(response, ProcessLevel.Actions);

				Assert.AreEqual(1, response.ResolvedActions.Length, "Unexpected number of resolved actions.");
				Assert.AreEqual("Clean Action", response.ResolvedActions[0].Action.Name,
								"Unexpected value for action name.");
				Assert.AreEqual(2, response.Contents.Length, "Unexpected value for size of content collection");
				Assert.AreEqual(ClientEmailPolicyCount, response.Contents[0].PolicySets.Length,
								"Unexpected value for size of PolicySet collection");
				Assert.AreEqual(ClientEmailPolicyCount, response.Contents[1].PolicySets.Length,
								"Unexpected value for size of PolicySet collection");

				PolicySet policySet = response.Contents[0].PolicySets[1];

				//1st content item
				Assert.AreEqual(4, policySet.Policies.Length, "Unexpected value for size of Policy collection");
				Assert.IsFalse(policySet.Policies[0].Triggered, "Unexpected value for the Triggered flag");
				Assert.IsFalse(policySet.Policies[1].Triggered, "Unexpected value for the Triggered flag");
				Assert.IsFalse(policySet.Policies[2].Triggered, "Unexpected value for the Triggered flag");
				Assert.IsFalse(policySet.Policies[3].Triggered, "Unexpected value for the Triggered flag");

				//2nd content item
				policySet = response.Contents[1].PolicySets[1];
				Assert.AreEqual(4, policySet.Policies.Length,
								"Unexpected value for size of Policy collection");
				Assert.IsFalse(policySet.Policies[0].Triggered,
							  "Unexpected value for the Triggered flag");
				Assert.IsFalse(policySet.Policies[1].Triggered,
							   "Unexpected value for the Triggered flag");
				Assert.IsTrue(policySet.Policies[2].Triggered,
							   "Unexpected value for the Triggered flag");
				Assert.IsFalse(policySet.Policies[3].Triggered,
							   "Unexpected value for the Triggered flag");

				Assert.AreEqual("Policy3 - text in header", policySet.Policies[2].Name);

				Routing routing = policySet.Policies[2].Routing;
				Assert.AreEqual("To Internal Recipients", routing.Name, "Unexpected value for routing name.");

				//Do the same thing, with an external recip... this time we should get a PDF action and different
				//routing details.

				request =
					CreateRequest_Email("", "some message body", "<html><body>some message body</body></html>",
										"Outlook", "*****@*****.**");

				AddEmailRecipient(request, "*****@*****.**", false);

				string filepath2 = lcofm.GetLocalCopyOfFileTarget("TriggerPolicy3.doc");
				File.Copy(Path.Combine(TESTPATH, "TriggerPolicy3.doc"), filepath2);
				AddAttachment(request, filepath2, attachmentSwitch, "application/msword");

				response =
					scannerService.Scan(request, null, ProcessLevel.Actions,
						RunAt.Client);

				AssertValid(response, ProcessLevel.Actions);

				Assert.AreEqual(1, response.ResolvedActions.Length, "Unexpected number of resolved actions.");
				Assert.AreEqual("PDF Action", response.ResolvedActions[0].Action.Name,
								"Unexpected value for action name.");
				Assert.AreEqual(2, response.Contents.Length, "Unexpected value for size of content collection");
				Assert.AreEqual(ClientEmailPolicyCount, response.Contents[0].PolicySets.Length,
								"Unexpected value for size of PolicySet collection");
				Assert.AreEqual(ClientEmailPolicyCount, response.Contents[1].PolicySets.Length,
								"Unexpected value for size of PolicySet collection");

				policySet = response.Contents[0].PolicySets[1];

				//1st content item
				Assert.AreEqual(4, policySet.Policies.Length, "Unexpected value for size of Policy collection");
				Assert.IsFalse(policySet.Policies[0].Triggered, "Unexpected value for the Triggered flag");
				Assert.IsFalse(policySet.Policies[1].Triggered, "Unexpected value for the Triggered flag");
				Assert.IsFalse(policySet.Policies[2].Triggered, "Unexpected value for the Triggered flag");
				Assert.IsFalse(policySet.Policies[3].Triggered, "Unexpected value for the Triggered flag");

				//2nd content item
				policySet = response.Contents[1].PolicySets[1];
				Assert.AreEqual(4, policySet.Policies.Length,
								"Unexpected value for size of Policy collection");
				Assert.IsFalse(policySet.Policies[0].Triggered,
							  "Unexpected value for the Triggered flag");
				Assert.IsFalse(policySet.Policies[1].Triggered,
							   "Unexpected value for the Triggered flag");
				Assert.IsTrue(policySet.Policies[2].Triggered,
							   "Unexpected value for the Triggered flag");
				Assert.IsFalse(policySet.Policies[3].Triggered,
							   "Unexpected value for the Triggered flag");
				Assert.AreEqual("Policy3 - text in header", policySet.Policies[2].Name);

				routing = policySet.Policies[2].Routing;
				Assert.AreEqual("To External Recipients", routing.Name, "Unexpected value for routing name.");
			}
		}
Ejemplo n.º 15
0
		public void Test_05_TriggerSinglePolicy_PDFAttachment()
		{
			IContentScanner scannerService = GetContentScanner();

			using (LocalCopyOfFileManager lcofm = new LocalCopyOfFileManager())
			{
				Request request =
					CreateRequest_Email("", "some message body", "<html><body>some message body</body></html>",
										"Outlook", "*****@*****.**");

				AddEmailRecipient(request, "*****@*****.**", false);

				string filepath = lcofm.GetLocalCopyOfFileTarget("TestPDF.pdf");
				File.Copy(Path.Combine(TESTPATH, "TestPDF.pdf"), filepath);
				AddAttachment(request, filepath, false, "application/msword");
				request.Attachments[0].ContentType = "application/pdf";

				Response response =
					scannerService.Scan(request, null, ProcessLevel.Actions, RunAt.Client);

				AssertValid(response, ProcessLevel.Actions);

				Assert.AreEqual(1, response.ResolvedActions.Length, "Unexpected number of resolved actions.");
				Assert.AreEqual("Alert Action", response.ResolvedActions[0].Action.Name,
								"Unexpected value for action name.");
				Assert.AreEqual(2, response.Contents.Length, "Unexpected value for size of content collection");
				Assert.AreEqual(ClientEmailPolicyCount, response.Contents[0].PolicySets.Length,
								"Unexpected value for size of PolicySet collection");
				Assert.AreEqual(ClientEmailPolicyCount, response.Contents[1].PolicySets.Length,
								"Unexpected value for size of PolicySet collection");

				PolicySet policySet = response.Contents[0].PolicySets[1];

				//1st content item
				Assert.AreEqual(4, policySet.Policies.Length, "Unexpected value for size of Policy collection");
				Assert.IsFalse(policySet.Policies[0].Triggered, "Unexpected value for the Triggered flag");
				Assert.IsFalse(policySet.Policies[1].Triggered, "Unexpected value for the Triggered flag");
				Assert.IsFalse(policySet.Policies[2].Triggered, "Unexpected value for the Triggered flag");
				Assert.IsFalse(policySet.Policies[3].Triggered, "Unexpected value for the Triggered flag");

				//2nd content item
				policySet = response.Contents[1].PolicySets[1];
				Assert.AreEqual(4, policySet.Policies.Length,
								"Unexpected value for size of Policy collection");
				Assert.IsFalse(policySet.Policies[0].Triggered,
							  "Unexpected value for the Triggered flag");
				Assert.IsFalse(policySet.Policies[1].Triggered,
							   "Unexpected value for the Triggered flag");
				Assert.IsFalse(policySet.Policies[2].Triggered,
							   "Unexpected value for the Triggered flag");
				Assert.IsTrue(policySet.Policies[3].Triggered,
							   "Unexpected value for the Triggered flag");

				Assert.AreEqual("Policy4 - PDF Alerts", policySet.Policies[3].Name);

				Routing routing = policySet.Policies[3].Routing;
				Assert.AreEqual("To External Recipients", routing.Name, "Unexpected value for routing name.");
			}
		}
Ejemplo n.º 16
0
        public static bool IsLargeAttachmentFile(Attachment attachment)
        {
            if (Path.HasExtension(attachment.FileName) && Path.GetExtension(attachment.FileName).ToLower() == ".wsl")
            {
                using (var lcfm = new LocalCopyOfFileManager())
                {
                    var tempFile = lcfm.GetLocalCopyOfFileTarget(attachment.FileName);
                    attachment.SaveAsFile(tempFile);

                    var lah = new LargeAttachmentHelper(tempFile);
                    return lah.IsLargeAttachment;
                }
            }
            return false;
        }
Ejemplo n.º 17
0
        private string GetProposedFileName(string filename, string newExtension, bool delete = false)
        {
            var lcofm = new LocalCopyOfFileManager(delete);
            string proposedFilename = lcofm.GetLocalCopyOfFileTarget(filename ?? string.Empty);

            if (!string.IsNullOrEmpty(newExtension))
            {
                proposedFilename = Path.ChangeExtension(proposedFilename, newExtension);
            }

            return proposedFilename;
        }
Ejemplo n.º 18
0
		public void Test15_TotalAttachmentSize()
		{
			PolicyItem item = new PolicyItem("AttachSize", File.ReadAllBytes(Path.Combine(TESTPATH, "Attachment Size Policy Set.runtimepolicy")));
			item.RestrictedTargets = new RunAt[] { RunAt.Client };
			GetPolicyCache().Add(item);

			IContentScanner scannerService = GetContentScanner();

			using (LocalCopyOfFileManager lcofm = new LocalCopyOfFileManager())
			{
				Request request =
					CreateRequest_Email("", "some message body", "<html><body>some message body</body></html>",
										"Outlook", "*****@*****.**");

				List<CustomProperty> props = new List<CustomProperty>(request.Properties);
				props.Add(new CustomProperty(RequestAdaptor.PassContentAsFileProperty, string.Empty));

				request.Properties = props.ToArray();

				AddEmailRecipient(request, "*****@*****.**", true);

				string filepath = lcofm.GetLocalCopyOfFileTarget("TriggerPolicy3.doc");
				File.Copy(Path.Combine(TESTPATH, "TriggerPolicy3.doc"), filepath);
				AddAttachment(request, filepath, true, "application/msword");

				string filepath2 = lcofm.GetLocalCopyOfFileTarget("TriggerPolicy2.doc");
				File.Copy(Path.Combine(TESTPATH, "TriggerPolicy2.doc"), filepath2);
				AddAttachment(request, filepath2, true, "application/msword");

				scannerService.TotalAttachmentSize = 48L;

				Response response =
					scannerService.Scan(request, null, ProcessLevel.Expressions, RunAt.Client);

				Assert.AreEqual("TriggerPolicy3.doc", response.Contents[1].DisplayName,
								"Should be the friendly name only.  Not the full path");
				Assert.IsNull(response.Contents[1].Content, "Content should be empty as its passed by file");

				foreach (ContentItem contentItem in response.Contents)
				{
					foreach (PolicySet policySet in contentItem.PolicySets)
					{
						if (policySet.Name == "Attachment Size Policy Set")
						{
							foreach (Policy policy in policySet.Policies)
							{
								if (policy.Name == "Attachment Size Policy")
								{
									Assert.IsTrue(policy.Triggered);
								}
							}
						}
					}
				}
			}
			GetPolicyCache().Remove(item.UniqueId);
		}
Ejemplo n.º 19
0
        internal void UpdateProxyAttachments(IProxy mailItem, Workshare.PolicyContent.Attachment[] processedAttachments)
		{
			using (LocalCopyOfFileManager lcofm = new LocalCopyOfFileManager())
			{
				for (int i = 0; i < processedAttachments.Length; ++i)
				{
					//Write processed file to disk
					Workshare.PolicyContent.Attachment serviceAttachment = processedAttachments[i];
				    string tempFileName = lcofm.GetLocalCopyOfFileTarget(serviceAttachment.Name);
                    File.Copy(serviceAttachment.FileName, tempFileName);

					//Find the matching proxy attachment
					if (0 != mailItem.ContainsAttachment(serviceAttachment.Id))
					{
						//Update existing attachment
						NotesProxy.Attachment proxyAttachment = mailItem.GetAttachmentById(serviceAttachment.Id) as NotesProxy.Attachment;
						FileInfo oldFile = new FileInfo(proxyAttachment.GetFileName());
						File.Delete(oldFile.FullName);

						//Copy processed file to original location
						string oldPath = oldFile.DirectoryName;
                        string newFile = Path.Combine(oldFile.DirectoryName, Path.GetFileName(tempFileName));
						File.Copy(tempFileName, newFile, true);

						//Update proxy attachment info
						proxyAttachment.SetFileName(newFile);
						proxyAttachment.SetDisplayName(serviceAttachment.Name);
						proxyAttachment.SetProcessStatus(AttachmentProcessStatus.ProcessStatus_Update);

                        File.Delete(tempFileName);
					}
					else
					{
						//Create a new copy before LCFM deletes the file
						string newFile = Path.Combine(GetWorkshareWorkingDirectory(), serviceAttachment.Name);
                        File.Copy(tempFileName, newFile, true);

						//Add attachment to proxy
						NotesProxy.Attachment proxyAttachment = new NotesProxy.Attachment();
						proxyAttachment.SetFileName(newFile);
						proxyAttachment.SetDisplayName(serviceAttachment.Name);
						proxyAttachment.SetProcessStatus(AttachmentProcessStatus.ProcessStatus_New);
						proxyAttachment.SetContentId(serviceAttachment.Id);
						proxyAttachment.SetContentItemIndex(-1);
						mailItem.AddAttachment(proxyAttachment);

                        File.Delete(tempFileName);
					}
				}
			}
		}
Ejemplo n.º 20
0
		public void ScanAttachment_IgnoreExpressionDetails()
		{
			IContentScanner scannerService = GetContentScanner();
			IContentEnforcer enforceService = GetContentEnforcer(null);

			using (LocalCopyOfFileManager lcofm = new LocalCopyOfFileManager())
			{
				Request request =
					CreateRequest_Email("", "some message body", "<html><body>some message body</body></html>",
										"Outlook", "*****@*****.**");

				List<CustomProperty> props = new List<CustomProperty>(request.Properties);
				props.Add(new CustomProperty(RequestAdaptor.PassContentAsFileProperty, string.Empty));
				props.Add(new CustomProperty(RemovableDeviceRequestPropertyKeys.IgnoreExpressionDetail,
												true.ToString()));
				request.Properties = props.ToArray();

				AddEmailRecipient(request, "*****@*****.**", true);

				string filepath = lcofm.GetLocalCopyOfFileTarget("TriggerPolicy3.doc");
				File.Copy(Path.Combine(TESTPATH, "TriggerPolicy3.doc"), filepath);
				AddAttachment(request, filepath, true, "application/msword");

				string filepath2 = lcofm.GetLocalCopyOfFileTarget("doc13.doc");
				File.Copy(Path.Combine(TESTPATH, "doc13.doc"), filepath2);
				AddAttachment(request, filepath2, true, "application/msword");


				Response response =
					scannerService.Scan(request, null, ProcessLevel.Actions, RunAt.Client);

				Assert.AreEqual("TriggerPolicy3.doc", response.Contents[1].DisplayName,
								"Should be the friendly name only.  Not the full path");
				Assert.IsNull(response.Contents[1].Content, "Content should be empty as its passed by file");


				//Expecting to see zero item arrays where the expressiondetails would normally live.
				Assert.IsTrue(ExpressionDetailIsEmpty(response.Contents));

				if (response.ResolvedActions != null)
				{
					foreach (ResolvedAction ra in response.ResolvedActions)
					{
						Assert.IsTrue(ExpressionDetailIsEmpty(ra.Contents));
					}
				}

				//When said property is missing, expect usual behavior; nonempty expression detail collections.
				props.RemoveAll(delegate(CustomProperty cp)
									{
										return cp.Name == RemovableDeviceRequestPropertyKeys.IgnoreExpressionDetail;
									});
				request.Properties = props.ToArray();

				response = scannerService.Scan(request, null, ProcessLevel.Actions, RunAt.Client);

				//Expecting to see NON-zero item arrays where the expressiondetails would normally live.
				Assert.IsFalse(ExpressionDetailIsEmpty(response.Contents));

				if (response.ResolvedActions != null)
				{
					foreach (ResolvedAction ra in response.ResolvedActions)
					{
						Assert.IsFalse(ExpressionDetailIsEmpty(ra.Contents));
					}
				}
			}
		}
Ejemplo n.º 21
0
		public void Test_08_ZippedUpContents_ClientEmail()
		{
			IContentScanner scannerService = GetContentScanner();

			using (LocalCopyOfFileManager lcofm = new LocalCopyOfFileManager())
			{
				Request request =
					CreateRequest_Email("", "some message body", "<html><body>some message body</body></html>",
										"Outlook", "*****@*****.**");

				AddEmailRecipient(request, "*****@*****.**", true);

				string filepath = lcofm.GetLocalCopyOfFileTarget("SomeWordDocs.zip");
				File.Copy(Path.Combine(TESTPATH, "SomeWordDocs.zip"), filepath);
				AddAttachment(request, filepath, false, "application/msword");

				Response response =
					scannerService.Scan(request, null, ProcessLevel.Actions, RunAt.Client);

				AssertValid(response, ProcessLevel.Actions);

				Assert.AreEqual(5, response.Contents.Length, "Unexpected content length");
				Assert.AreEqual("Email", response.Contents[0].ContentType, "Unexpected content type");
				Assert.AreEqual("ZIP", response.Contents[1].ContentType, "Unexpected content type");
				Assert.AreEqual("WordDocument", response.Contents[2].ContentType, "Unexpected content type");
				Assert.AreEqual("WordDocument", response.Contents[3].ContentType, "Unexpected content type");
				Assert.AreEqual("WordDocument", response.Contents[4].ContentType, "Unexpected content type");
			}
		}
Ejemplo n.º 22
0
		public void ScanAndEnforceByFileWithinAZip()
		{
			//setup
			IContentScanner scannerService = GetContentScanner();
			IContentEnforcer enforceService = GetContentEnforcer(null);

			using (LocalCopyOfFileManager lcofm = new LocalCopyOfFileManager())
			{
				Request request =
					CreateRequest_Email("", "some message body", "<html><body>some message body</body></html>",
										"Outlook", "*****@*****.**");

				List<CustomProperty> props = new List<CustomProperty>(request.Properties);
				props.Add(new CustomProperty(RequestAdaptor.PassContentAsFileProperty, string.Empty));

				request.Properties = props.ToArray();

				AddEmailRecipient(request, "*****@*****.**", true);

				string filepath = lcofm.GetLocalCopyOfFileTarget("TriggerPolicy3.zip");
				File.Copy(Path.Combine(TESTPATH, "TriggerPolicy3.zip"), filepath);
				AddAttachment(request, filepath, true, "application/zip");

				//execute
				Response response =
					scannerService.Scan(request, null, ProcessLevel.Actions, RunAt.Client);

				Assert.IsFalse(Array.Exists(response.Contents, toTest => toTest.Content != null),
							   "Document is returned in the response as a byte stream");

				//expecting 4 content items; email, zip, and two files in that order
				Assert.AreEqual(4, response.Contents.Length);
				Assert.AreEqual("Email", response.Contents[0].ContentType);
				Assert.AreEqual("ZIP", response.Contents[1].ContentType);
				Assert.AreEqual("WordDocument", response.Contents[2].ContentType);
				Assert.AreEqual("WordDocument", response.Contents[3].ContentType);

			Assert.IsTrue(Path.GetFileName(response.Contents[2].Name) == "TriggerPolicy3 - Copy.doc" || Path.GetFileName(response.Contents[3].Name) == "TriggerPolicy3 - Copy.doc", "Name property not set correctly");
			Assert.IsTrue(Path.GetFileName(response.Contents[2].Name) == "TriggerPolicy3 - Copy - Copy.doc" || Path.GetFileName(response.Contents[3].Name) == "TriggerPolicy3 - Copy - Copy.doc", "Name property not set correctly");

			CustomProperty dataSource = Array.Find(response.Contents[2].Properties, toTest => toTest.Name == ContentItemAdaptor.ContentDataSourceKey);
				Assert.IsNotNull(dataSource);
			Assert.IsTrue(File.Exists(dataSource.Value), "File {0} should be a valid file with the content item", dataSource.Value);

			dataSource = Array.Find(response.Contents[3].Properties, toTest => toTest.Name == ContentItemAdaptor.ContentDataSourceKey);
				Assert.IsNotNull(dataSource);
			Assert.IsTrue(File.Exists(dataSource.Value), "File {0} should be a valid file with the content item", dataSource.Value);


				EnforceResponse result = enforceService.Enforce(request, response);
				//assert
			Assert.IsTrue(Array.Exists(result.ModifiedRequest.Properties, toTest => toTest.Name == RequestAdaptor.PassContentAsFileProperty),
					"Pass content as file key is missing");

				Assert.IsFalse(Array.Exists(result.ModifiedRequest.Attachments, toTest => toTest.Content != null),
							   "Document is returned in the modified response as a byte stream");
			}
		}
Ejemplo n.º 23
0
		public void ScanAndEnforceByFile()
		{
			//setup
			IContentScanner scannerService = GetContentScanner();
			IContentEnforcer enforceService = GetContentEnforcer(null);

			using (LocalCopyOfFileManager lcofm = new LocalCopyOfFileManager())
			{
				Request request =
					CreateRequest_Email("", "some message body", "<html><body>some message body</body></html>",
										"Outlook", "*****@*****.**");

				List<CustomProperty> props = new List<CustomProperty>(request.Properties);
				props.Add(new CustomProperty(RequestAdaptor.PassContentAsFileProperty, string.Empty));

				request.Properties = props.ToArray();

				AddEmailRecipient(request, "*****@*****.**", true);

				string filepath = lcofm.GetLocalCopyOfFileTarget("TriggerPolicy3.doc");
				File.Copy(Path.Combine(TESTPATH, "TriggerPolicy3.doc"), filepath);
				AddAttachment(request, filepath, true, "application/msword");

				//execute
				Response response =
					scannerService.Scan(request, null, ProcessLevel.Actions, RunAt.Client);

			Assert.IsFalse(Array.Exists<ContentItem>(response.Contents, delegate(ContentItem toTest) { return toTest.Content != null; }),
					"Document is returned in the response as a byte stream");

				EnforceResponse result = enforceService.Enforce(request, response);
				//assert
			Assert.IsTrue(Array.Exists<CustomProperty>(result.ModifiedRequest.Properties, delegate(CustomProperty toTest) { return toTest.Name == RequestAdaptor.PassContentAsFileProperty; }),
					"Pass content as file key is missing");

			Assert.IsFalse(Array.Exists<Attachment>(result.ModifiedRequest.Attachments, delegate(Attachment toTest) { return toTest.Content != null;  }),
					"Document is returned in the modified response as a byte stream");
			}
		}
Ejemplo n.º 24
0
		protected string GetProposedFileName(string filename, string newExtension, string id, bool delete = false)
		{
			LocalCopyOfFileManager lcofm = new LocalCopyOfFileManager(delete, GetWorkingDirectory(id));
            string proposedFilename = lcofm.GetLocalCopyOfFileTarget(filename ?? string.Empty);   //.GetValidFileName(filename ?? string.Empty, false);

            if (!string.IsNullOrEmpty(newExtension))
            {
                proposedFilename = Path.ChangeExtension(proposedFilename, newExtension);
            }

            return proposedFilename;
		}
Ejemplo n.º 25
0
		public void Test_06_NoPoliciesAreApplicable()
		{
			IContentScanner scannerService = GetContentScanner();

			using (LocalCopyOfFileManager lcofm = new LocalCopyOfFileManager())
			{
				Request request =
					CreateRequest_Email("", "some message body", "<html><body>some message body</body></html>",
										"Outlook", "*****@*****.**");

				AddEmailRecipient(request, "*****@*****.**", false);

				string filepath = lcofm.GetLocalCopyOfFileTarget("TriggerPolicy2.doc");
				File.Copy(Path.Combine(TESTPATH, "TriggerPolicy2.doc"), filepath);
				AddAttachment(request, filepath, false, "application/msword");

				//Passing a request with no violations , when there are suitable polcies (ie matching policytypes)
				Response response =
					scannerService.Scan(request, null, ProcessLevel.Actions, RunAt.Client);

				Assert.IsNull(response.ResolvedActions, "No triggered policies - there should not be any actions.");

				Assert.IsNotNull(response.Contents, "We should not have violations, but still expect meaningful contents in the response.");

				foreach (ContentItem contentItem in response.Contents)
				{
					foreach (PolicySet ps in contentItem.PolicySets)
					{
						foreach (Policy p in ps.Policies)
						{
							Assert.IsFalse(p.Triggered, "None of these policies should have been triggered.");
						}
					}
				}

				Assert.IsNotNull(response.Routing, "We should not have violations, but still expect meaningful routing info in the response.");

				//Passing a request with no violations, but this time with a different policy type.  
				//We have not added and NetMon policies to the cache.
				request.PolicyType = PolicyType.NetMon.ToString();

				response =
					scannerService.Scan(request, null, ProcessLevel.Actions, RunAt.Client);

				Assert.IsNull(response.ResolvedActions, "No triggered policies - there should not be any actions.");

				Assert.IsNull(response.Contents, "No policies match the specified category - the should not be any contents.");

				Assert.IsNull(response.Routing, "No policies match the specified category - the should not be any routing info.");

			}
		}
Ejemplo n.º 26
0
		public void ScanAttachment_FilePathOnly_MaintainDisplayNameInAttachments()
		{
			IContentScanner scannerService = GetContentScanner();
			IContentEnforcer enforceService = GetContentEnforcer(null);

			using (LocalCopyOfFileManager lcofm = new LocalCopyOfFileManager())
			{
				Request request =
					CreateRequest_Email("", "some message body", "<html><body>some message body</body></html>",
										"Outlook", "*****@*****.**");

				List<CustomProperty> props = new List<CustomProperty>(request.Properties);
				props.Add(new CustomProperty(RequestAdaptor.PassContentAsFileProperty, string.Empty));

				request.Properties = props.ToArray();

				AddEmailRecipient(request, "*****@*****.**", true);

				string filepath = lcofm.GetLocalCopyOfFileTarget("TriggerPolicy3.doc");
				File.Copy(Path.Combine(TESTPATH, "TriggerPolicy3.doc"), filepath);
				AddAttachment(request, filepath, true, "application/msword");

				string filepath2 = lcofm.GetLocalCopyOfFileTarget("doc13.doc");
				File.Copy(Path.Combine(TESTPATH, "doc13.doc"), filepath2);
				AddAttachment(request, filepath2, true, "application/msword");

				Response response =
					scannerService.Scan(request, null, ProcessLevel.Actions, RunAt.Client);

				Assert.AreEqual("TriggerPolicy3.doc", response.Contents[1].DisplayName,
								"Should be the friendly name only.  Not the full path");
				Assert.IsNull(response.Contents[1].Content, "Content should be empty as its passed by file");
			}
		}
Ejemplo n.º 27
0
		public void Test_09_ZippedUpContents_MTA()
		{
			IContentScanner scannerService = GetContentScanner();

			using (LocalCopyOfFileManager lcofm = new LocalCopyOfFileManager())
			{
				Request request =
					CreateRequest_Email_MTA("", "some message body", "<html><body>some message body</body></html>",
											"*****@*****.**");

				AddEmailRecipient(request, "*****@*****.**", true);

				string filepath = lcofm.GetLocalCopyOfFileTarget("SomeWordDocs.zip");
				File.Copy(Path.Combine(TESTPATH, "SomeWordDocs.zip"), filepath);
				AddAttachment(request, filepath, false, "application/msword");

				Response response =
					scannerService.Scan(request, null, ProcessLevel.Actions, RunAt.Server);

				AssertValid(response, ProcessLevel.Actions);

				Assert.AreEqual(PolicyType.Mta.ToString(), response.PolicyType, "Policy Type should have been set.");

				Assert.AreEqual(5, response.Contents.Length, "Unexpected content length");
				Assert.AreEqual("Email", response.Contents[0].ContentType, "Unexpected content type");
				Assert.AreEqual("ZIP", response.Contents[1].ContentType, "Unexpected content type");
				Assert.AreEqual("WordDocument", response.Contents[2].ContentType, "Unexpected content type");
				Assert.AreEqual("WordDocument", response.Contents[3].ContentType, "Unexpected content type");
				Assert.AreEqual("WordDocument", response.Contents[4].ContentType, "Unexpected content type");

				Assert.AreEqual(1, response.ResolvedActions.Length, "Unexpected amount");
				Assert.AreEqual("MTA_Block Action", response.ResolvedActions[0].Action.Name, "Unexpected name");

				Assert.IsFalse(response.Contents[0].PolicySets[0].Policies[0].Triggered);
				Assert.IsFalse(response.Contents[1].PolicySets[0].Policies[0].Triggered);
				Assert.IsTrue(response.Contents[2].PolicySets[0].Policies[0].Triggered);
				Assert.IsTrue(response.Contents[3].PolicySets[0].Policies[0].Triggered);
				Assert.IsTrue(response.Contents[4].PolicySets[0].Policies[0].Triggered);

				Assert.AreEqual("Policy3 - text in header", response.Contents[2].PolicySets[0].Policies[0].Name);
				Assert.AreEqual("Policy3 - text in header", response.Contents[3].PolicySets[0].Policies[0].Name);
				Assert.AreEqual("Policy3 - text in header", response.Contents[4].PolicySets[0].Policies[0].Name);
			}
		}