Importando blacklist no ISA Server 2006 automaticamente

O Import de blacklist no ISA Server 2006 pode ser “automatizado” desde que montado com os scripts corretos e com o download de uma blacklist confiavel.

Abaixo o procedimento:
(Pacote montado pode ser solicitado para envio por e-mail)

1 – Criando a bat de importaçao
No ISA Server 2006, Criar em c:\Blacklist um arquivo .bat e edita-lo conforme abaixo (nome sugerido: Execute-Import-In-Isa-2006.bat):

.\ISA_Fill_Domain_Name_Set.vbs ADV .\BL\adv\domains
.\ISA_Fill_URL_Set.vbs ADV .\BL\adv\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs aggressive .\BL\aggressive\domains
.\ISA_Fill_URL_Set.vbs aggressive .\BL\aggressive\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs alcohol .\BL\alcohol\domains
.\ISA_Fill_URL_Set.vbs alcohol .\BL\alcohol\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs anonvpn .\BL\anonvpn\domains
.\ISA_Fill_URL_Set.vbs anonvpn .\BL\anonvpn\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs automobile .\BL\automobile\domains
.\ISA_Fill_URL_Set.vbs automobile .\BL\automobile\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs chat .\BL\chat\domains
.\ISA_Fill_URL_Set.vbs chat .\BL\chat\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs costtraps .\BL\costtraps\domains
.\ISA_Fill_URL_Set.vbs costtraps .\BL\costtraps\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs dating .\BL\dating\domains
.\ISA_Fill_URL_Set.vbs dating .\BL\dating\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs downloads .\BL\downloads\domains
.\ISA_Fill_URL_Set.vbs downloads .\BL\downloads\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs drugs .\BL\drugs\domains
.\ISA_Fill_URL_Set.vbs drugs .\BL\drugs\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs dynamic .\BL\dynamic\domainsr
.\ISA_Fill_URL_Set.vbs dynamic .\BL\dynamic\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs education .\BL\education\domains
.\ISA_Fill_URL_Set.vbs education .\BL\education\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs finance .\BL\finance\domains
.\ISA_Fill_URL_Set.vbs finance .\BL\finance\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs fortunetelling .\BL\fortunetelling\domains
.\ISA_Fill_URL_Set.vbs fortunetelling .\BL\fortunetelling\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs forum .\BL\forum\domains
.\ISA_Fill_URL_Set.vbs forum .\BL\forum\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs gamble .\BL\gamble\domains
.\ISA_Fill_URL_Set.vbs gamble .\BL\gamble\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs government .\BL\government\domains
.\ISA_Fill_URL_Set.vbs government .\BL\government\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs hacking .\BL\hacking\domains
.\ISA_Fill_URL_Set.vbs hacking .\BL\hacking\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs hobby .\BL\hobby\domains
.\ISA_Fill_URL_Set.vbs hobby .\BL\hobby\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs homestyle .\BL\homestyle\domains
.\ISA_Fill_URL_Set.vbs homestyle .\BL\homestyle\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs hospitals .\BL\hospitals\domains
.\ISA_Fill_URL_Set.vbs hospitals .\BL\hospitals\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs imagehosting .\BL\imagehosting\domains
.\ISA_Fill_URL_Set.vbs imagehosting .\BL\imagehosting\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs isp .\BL\isp\domains
.\ISA_Fill_URL_Set.vbs isp .\BL\isp\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs jobsearch .\BL\jobsearch\domains
.\ISA_Fill_URL_Set.vbs jobsearch .\BL\jobsearch\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs library .\BL\library\domains
.\ISA_Fill_URL_Set.vbs library .\BL\library\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs military .\BL\military\domains
.\ISA_Fill_URL_Set.vbs military .\BL\military\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs models .\BL\models\domains
.\ISA_Fill_URL_Set.vbs models .\BL\models\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs movies .\BL\movies\domains
.\ISA_Fill_URL_Set.vbs movies .\BL\movies\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs music .\BL\music\domains
.\ISA_Fill_URL_Set.vbs music .\BL\music\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs news .\BL\news\domains
.\ISA_Fill_URL_Set.vbs news .\BL\news\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs podcasts .\BL\podcasts\domains
.\ISA_Fill_URL_Set.vbs podcasts .\BL\podcasts\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs politics .\BL\politics\domains
.\ISA_Fill_URL_Set.vbs politics .\BL\politics\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs recreation .\BL\recreation\domains
.\ISA_Fill_URL_Set.vbs recreation .\BL\recreation\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs radiotv .\BL\radiotv\domains
.\ISA_Fill_URL_Set.vbs radiotv .\BL\radiotv\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs redirector .\BL\redirector\domains
.\ISA_Fill_URL_Set.vbs redirector .\BL\redirector\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs religion .\BL\religion\domains
.\ISA_Fill_URL_Set.vbs religion .\BL\religion\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs remotecontrol .\BL\remotecontrol\domains
.\ISA_Fill_URL_Set.vbs remotecontrol .\BL\remotecontrol\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs ringtones .\BL\ringtones\domains
.\ISA_Fill_URL_Set.vbs ringtones .\BL\ringtones\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs science .\BL\science\domains
.\ISA_Fill_URL_Set.vbs science .\BL\science\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs searchengines .\BL\searchengines\domains
.\ISA_Fill_URL_Set.vbs searchengines .\BL\searchengines\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs sex .\BL\sex\domains
.\ISA_Fill_URL_Set.vbs sex .\BL\sex\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs shopping .\BL\shopping\domains
.\ISA_Fill_URL_Set.vbs shopping .\BL\shopping\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs socialnet .\BL\socialnet\domains
.\ISA_Fill_URL_Set.vbs socialnet .\BL\socialnet\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs spyware .\BL\spyware\domains
.\ISA_Fill_URL_Set.vbs spyware .\BL\spyware\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs tracker .\BL\tracker\domains
.\ISA_Fill_URL_Set.vbs tracker .\BL\tracker\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs updatesites .\BL\updatesites\domains
.\ISA_Fill_URL_Set.vbs updatesites .\BL\updatesites\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs urlshortener .\BL\urlshortener\domains
.\ISA_Fill_URL_Set.vbs urlshortener .\BL\urlshortener\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs violence .\BL\violence\domains
.\ISA_Fill_URL_Set.vbs violence .\BL\violence\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs warez .\BL\warez\domains
.\ISA_Fill_URL_Set.vbs warez .\BL\warez\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs weapons .\BL\weapons\domains
.\ISA_Fill_URL_Set.vbs weapons .\BL\weapons\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs webmail .\BL\webmail\domains
.\ISA_Fill_URL_Set.vbs webmail .\BL\webmail\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs webphone .\BL\webphone\domains
.\ISA_Fill_URL_Set.vbs webphone .\BL\webphone\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs webradio .\BL\webradio\domains
.\ISA_Fill_URL_Set.vbs webradio .\BL\webradio\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs webtv .\BL\webtv\domains
.\ISA_Fill_URL_Set.vbs webtv .\BL\webtv\urls /prependstar

.\ISA_Fill_Domain_Name_Set.vbs porn .\BL\porn\domains
.\ISA_Fill_URL_Set.vbs porn .\BL\porn\urls /prependstar

2 – No ISA Server 2006, Criar em c:\Blacklist o primeiro arquivo .vbs obrigatoriamente com o nome: ISA_Fill_URL_Set.vbs

'*************************************************************************************
' Script Name: ISA_Fill_URL_Set.vbs
' Version: 1.3
' Author: Jason Fossen ( www.ISAscripts.org )
'Last Updated: 10.Jun.2008
' Purpose: Automatically update an ISA Server URL Set with URLs; for example,
' these could be URLs of spammers, pornographers, hacking sites, etc.
' Arguments: First arg is name of URL Set, in double-quotes if necessary. The
' second arg is the HTTP URL, local full path, or file name (if in same
' folder as script) of a text file containing the URL data. This file,
' if it contains comments, must use #-marks or semicolons to denote comments.
' Each line must be just one URL.
' This script is compatible with the lists at www.urlblacklist.com and
' with other similarly-formatted lists of URLs. The file with URLs can
' use either Windows-style or UNIX-style newlines, both work fine.
' Note: The fastest way to see that the URL Set had been filled correctly
' is to close and open the ISA MMC console again, not by refreshing.
' Works on both ISA Standard and Enterprise editions.
' Thanks to Alexander Willacker for the /*pendstar switches!
' Legal: Public Domain. Modify and redistribute freely. No rights reserved.
' SCRIPT PROVIDED "AS IS" WITHOUT WARRANTIES OR GUARANTEES OF ANY KIND.
' USE AT YOUR OWN RISK. Test on non-production servers first!
'*************************************************************************************

Option Explicit
On Error Resume Next

ReDim aURLsArray(0) 'Array of URLs to be added to the URL Set.
Dim sUrlSetName 'Name of URL Set to be created and/or updated.
Dim bUseLocalURLsFile 'If true, use local file. If false, get URLs from http URL.
Dim sURLsFilePath 'An HTTP URL or a local filesystem path to a file of URLs.
Dim oFPC 'See MakeIsaObjects()
Dim oIsaArray 'See MakeIsaObjects()
Dim bAppendStar : bAppendStar = False 'Assume that a trailing asterisk should not be added.
Dim bPrependStar : bPrependStar = False 'Assume that a leading asterisk & dot should not be added.

Dim oFileSystem : Set oFileSystem = WScript.CreateObject("Scripting.FileSystemObject")
Call CatchAnyErrorsAndQuit("Problems creating the FileSystemObject.")

'*************************************************************************************
' Main()
'*************************************************************************************
Call ProcessCommandLineArguments()
Call CreateIsaObjects()
Call MakeArrayOfURLs()
Call CreateUrlSet()
Call EmptyTheUrlSet()
Call CreateNewURLs()

'*************************************************************************************
' Procedures
'*************************************************************************************

Sub ProcessCommandLineArguments()
On Error Resume Next
'
' First arg...
'
sUrlSetName = WScript.Arguments.Item(0)
Dim sArg : sArg = LCase(sUrlSetName)
If (WScript.Arguments.Count = 0) Or (WScript.Arguments.Count > 4) Or (sArg = "/?")_
Or (sArg = "-?") Or (sArg = "/h") Or (sArg = "/help") Or (sArg = "--help") Then
Call ShowHelpAndQuit()
End If

'
' Second arg...
'
sURLsFilePath = WScript.Arguments.Item(1)

If InStr(LCase(sURLsFilePath), "http://") = 0 Then
bUseLocalURLsFile = True 'Use a local text file.
Else
bUseLocalURLsFile = False 'Use an http URL.
End If

'
' Check to see whether a trailing asterisk should be added if not already present.
'
For Each sArg In WScript.Arguments
If LCase(sArg) = "/appendstar" Then bAppendStar = True
Next

'
' Check to see whether a leading asterisk should be added if not already present.
'
For Each sArg In WScript.Arguments
If LCase(sArg) = "/prependstar" Then bPrependStar = True
Next

On Error Goto 0
End Sub

Sub CreateIsaObjects()
'This sub is just a placeholder for something to add later on...
Set oFPC = CreateObject("FPC.Root")
Set oIsaArray = oFPC.GetContainingArray
Call CatchAnyErrorsAndQuit("Problems connecting to ISA Server or ISA Array.")
End Sub

Sub MakeArrayOfURLs()
If bUseLocalURLsFile Then
If Not ParseInputFile(sURLsFilePath, aURLsArray) Then
Err.Raise -1
Call CatchAnyErrorsAndQuit("Problems reading the local URLs file: " & sURLsFilePath)
End If
Else 'Get the URLs file from the http URL...
Dim sUrlText : sUrlText = HttpGetText(sURLsFilePath)
If InStr(sUrlText, "GET-Error!") 0 Then ' "GET-Error!" would be returned by HttpGetText() function, not the web server.
Err.Raise -1
Call CatchAnyErrorsAndQuit("Problems getting URLs file from " & sUrlToURLsFile)
End If

If oFileSystem.FileExists("URLs-downloaded-from-url.txt") Then
oFileSystem.DeleteFile "URLs-downloaded-from-url.txt", True 'Delete prior URLs file, if it exists.
End If

If Not AppendToFile(sUrlText, "URLs-downloaded-from-url.txt") Then
Err.Raise -1
Call CatchAnyErrorsAndQuit("Problems writing to the URLs-downloaded-from-url.txt file.")
End If

If Not ParseInputFile("URLs-downloaded-from-url.txt", aURLsArray) Then
Err.Raise -1
Call CatchAnyErrorsAndQuit("Problems reading file: URLs-downloaded-from-url.txt")
End If
End If

End Sub

Sub CreateUrlSet()
On Error Resume Next
Dim cUrlSets 'FPCUrlSets collection.
Dim oUrlSet 'FPCUrlSet object.

'Set oFPC = CreateObject("FPC.Root")
'Set oIsaArray = oFPC.GetContainingArray
Set cUrlSets = oIsaArray.RuleElements.UrlSets

Set oUrlSet = cUrlSets.Add(sUrlSetName)

If Err.Number = -2147024713 Then
Err.Clear 'Already exists, so ignore error.
Else
cUrlSets.Save
End If

Call CatchAnyErrorsAndQuit("Problems recreating URL Set named " & sUrlSetName)
On Error Goto 0
End Sub

Sub EmptyTheUrlSet()
'Note: Clear the URL Set instead of deleting it because it may be used in rules already.
Dim cUrlSets 'FPCUrlSets collection.
Dim cUrlSet 'FPCUrlSet collection.
Dim sURL

'Set oFPC = CreateObject("FPC.Root")
'Set oIsaArray = oFPC.GetContainingArray
Set cUrlSet = oIsaArray.RuleElements.UrlSets.Item(sUrlSetName)

For Each sURL In cUrlSet
cUrlSet.Remove(sURL)
Next

cUrlSet.Save

Call CatchAnyErrorsAndQuit("Problems emptying URL Set named " & sUrlSetName)
End Sub

Sub CreateNewURLs()
On Error Resume Next
Dim cURLs 'FPCURLSets collection.
Dim oURL 'FPCURL object.
Dim cUrlSet 'FPCUrlSet collection.
Dim cUrlSets 'FPCUrlSets collection.
Dim sIPaddress, sMask, sURL, sURLName, sLeftChar

Set cUrlSet = oIsaArray.RuleElements.UrlSets.Item(sUrlSetName)

For Each sURL In aURLsArray
If Len(sURL) 0 Then
sLeftChar = Left(sURL,1)
If (sLeftChar "#") And (sLeftChar ";") And (sLeftChar "<") Then

If bAppendStar Then
'It might seem strange, but appending an asterisk to the end seems not to interfere with any
'other matching, and is probably the behavior most admins want anyway. It even works fine
'when you get entries like "www.domain.com*" and "www.domain.com/folder/file.html*".

sURL = sURL & "*" 'Append an asterisk to the end.
sURL = Replace(sURL, "**", "*") 'Correct if last char was already an asterisk.
End If

cUrlSet.Add(sURL)

If Err.Number = -2147024713 Then Err.Clear 'URL already added, so ignore error.
'WScript.Echo sURL & " was added." 'For debugging...

If bPrependStar Then
'Blocking devil.com will not block www.devil.com and vice versa. So every Domain
'should be added as *.devil.com and devil.com

sURL = "*." & sURL 'Preppend an asterisk & dot at the beginning.
sURL = Replace(sURL, "*.*.", "*.") 'Correct if first chars were already an asterisk & dot.

cUrlSet.Add(sURL)

If Err.Number = -2147024713 Then Err.Clear 'URL already added, so ignore error.
'WScript.Echo sURL & " was added." 'For debugging...

End If
End If
End If
Next

cUrlSet.Save

Call CatchAnyErrorsAndQuit("Problems creating new URL objects in " & sUrlSetName)
On Error Goto 0
End Sub

Sub CatchAnyErrorsAndQuit(sMessage)
Dim oStdErr
If Err.Number 0 Then
Set oStdErr = WScript.StdErr 'Write to standard error stream.
oStdErr.WriteLine vbCrLf
oStdErr.WriteLine ">>>>>> ERROR: " & sMessage
oStdErr.WriteLine "Error Number: " & Err.Number
oStdErr.WriteLine " Description: " & Err.Description
oStdErr.WriteLine "Error Source: " & Err.Source
oStdErr.WriteLine " Script Name: " & WScript.ScriptName
oStdErr.WriteLine vbCrLf
WScript.Quit Err.Number
End If
End Sub

Sub ShowHelpAndQuit()
Dim sUsage : sUsage = vbCrLf
sUsage = sUsage & vbCrLf
sUsage = sUsage & "ISA_FILL_URL_SET.VBS UrlSetName FilePath [/appendstar] [/prependstar]" & vbCrLf
sUsage = sUsage & vbCrLf
sUsage = sUsage & "Creates or updates an ISA Server URL Set (`UrlSet`)" & vbCrLf
sUsage = sUsage & "with the URLs from a text file (`FilePath`) obtained from" & vbCrLf
sUsage = sUsage & "either an HTTP URL or a local filesystem path." & vbCrLf
sUsage = sUsage & vbCrLf
sUsage = sUsage & " UrlSet Name of URL Set to be created or" & vbCrLf
sUsage = sUsage & " updated with URL entries. " & vbCrLf
sUsage = sUsage & vbCrLf
sUsage = sUsage & " FilePath A full HTTP URL or local filesystem path" & vbCrLf
sUsage = sUsage & " to a text file containing URLs. All" & vbCrLf
sUsage = sUsage & " comments must start with # or ;. Examples" & vbCrLf
sUsage = sUsage & " might be `filename.txt`, `c:\filename.txt`," & vbCrLf
sUsage = sUsage & " or `http://www.fqdn.com/filename.asp`." & vbCrLf
sUsage = sUsage & vbCrLf
sUsage = sUsage & " /appendstar Optional. Will automatically append an asterisk" & vbCrLf
sUsage = sUsage & " to every URL imported (which is probably what" & vbCrLf
sUsage = sUsage & " you want). Don't worry, this doesn't break" & vbCrLf
sUsage = sUsage & " URL matching when no path, or a full path, is" & vbCrLf
sUsage = sUsage & " specified in the URL, e.g., isascripts.org* and" & vbCrLf
sUsage = sUsage & " isascripts.org/index.html* still match fine." & vbCrLf
sUsage = sUsage & vbCrLf
sUsage = sUsage & " /prependstar Optional. Will automatically prepend an asterisk & dot" & vbCrLf
sUsage = sUsage & " to every URL imported. (e.g. Blocking devil.com will" & vbcrlf
sUsage = sUsage & " not block www.devil.com and vice versa. So every Domain" & vbcrlf
sUsage = sUsage & " will be added as *.devil.com and devil.com" & vbCrLf
sUsage = sUsage & vbCrLf
sUsage = sUsage & "Note that all URLs defined in the URL Set are deleted" & vbCrLf
sUsage = sUsage & "prior to importing the URLs from the text file. If necessary," & vbCrLf
sUsage = sUsage & "the URL Set object will be created first. Place double-quotes" & vbCrLf
sUsage = sUsage & "around the UrlSet and FilePath arguments if they contain" & vbCrLf
sUsage = sUsage & "any space characters. When providing an HTTP URL, the downloaded" & vbCrLf
sUsage = sUsage & "file will be saved as 'URLs-downloaded-from-url.txt` in the " & vbCrLf
sUsage = sUsage & "same folder as the script; it will be overwritten whenever a URL" & vbCrLf
sUsage = sUsage & "path is used again." & vbCrLf
sUsage = sUsage & vbCrLf
sUsage = sUsage & "Public domain. No rights reserved. SCRIPT PROVIDED ""AS IS"" WITHOUT WARRANTIES" & vbCrLf
sUsage = sUsage & "OR GUARANTEES OF ANY KIND. USE AT YOUR OWN RISK. ( www.ISAscripts.org )" & vbCrLf
sUsage = sUsage & vbCrLf

WScript.Echo sUsage
WScript.Quit
End Sub

'*************************************************************************************
' Functions
'*************************************************************************************

Function IsIpAddress(sInput)
'Regular expression would be more accurate, but slower...quick-n-dirty will do since
'having a "*.dottedIPaddress" URL doesn't break anything if an IP address sneaks by...

IsIpAddress = False

Dim sEnd
sInput = LCase(sInput)
sEnd = Right(sInput,1) 'This will catch 98% of cases, so it's faster than RegEx.
If (sEnd = "m") Or (sEnd = "u") Or (sEnd = "l") Or (sEnd = "v") Or (sEnd = "g")_
Or (sEnd = "t") Or (sEnd = "z") Or (sEnd = "o") Or (sEnd = "e") Or (sEnd = "s")_
Or (sEnd = "r") Or (sEnd = "n") Or (sEnd = "c") Or (sEnd = "k") Or (sEnd = "e") Then Exit Function

Dim aArray, x
aArray = Split(sInput,".")
If UBound(aArray) 3 Then Exit Function

If Not (IsNumeric(aArray(0)) And IsNumeric(aArray(1)) And IsNumeric(aArray(2)) And IsNumeric(aArray(3))) Then Exit Function

IsIpAddress = True
End Function

Function HttpGetText(sURL)
On Error Resume Next

If Not IsObject(oHTTP) Then Dim oHTTP : Set oHTTP = WScript.CreateObject("Microsoft.XMLHTTP")

oHTTP.Open "GET", sURL, False 'False = Script waits until the full HTTP response is received.
oHTTP.Send 'Send the HTTP command as defined with the Open method.

If Err.Number = 0 Then
HttpGetText = oHTTP.ResponseText
HttpGetText = Replace(HttpGetText, vbLf, vbCrLf) 'Flip UNIX new lines to DOS, if necessary.
Else
HttpGetText = "GET-Error! Error Number: " & Err.Number
End If
End Function

'*********************************************************************************
' Script Name: Parse_Input_File.vbs
' Version: 1.1
' Author: Jason Fossen
'Last Updated: 29.Mar.2004
' Purpose: Sorts lines of a text file into an array.
' Usage: Function returns true if no problems, false otherwise. Pass global
' variable of an array into second argument of function; this will be
' resized and populated with lines from text file. Blank and empty
' trailing lines from file, if any, are excluded from the array. The
' array global variable must be declared with "ReDim", not just "Dim".
' The file can be passed in with full path or just the file name if
' the file is in the same folder as the script.
' Note: You must declare the global array variable with "ReDim" before
' passing it into the function; make it of size one because it
' will be ReDim-ed without preservation again anyway.
' Legal: Public Domain. Modify and redistribute freely. No rights reserved.
' Use at your own risk. Do not run on networks for which you do not
' have prior written permission to do so. Script provided "AS IS".
'*********************************************************************************

Function ParseInputFile(ByVal sFile, ByRef aArray)
On Error Resume Next
Const ForReading = 1
Const OpenUsingDefault = -2
Dim sCurrentFolder, oFileSystem, oInputFile, i, iCurrentSize
Dim iPreserveCounter, oFile, oTextStream, iLineCount, sLine

'Expand environmental variables, if any.
If InStr(sFile, "%") 0 Then
If Not IsObject(oWshShell) Then Set oWshShell = WScript.CreateObject("WScript.Shell")
sFile = oWshShell.ExpandEnvironmentStrings(sFile)
End If

'Assume input file is in current folder if a full path is not given.
If InStr(sFile, "\") = 0 Then
sCurrentFolder = WScript.ScriptFullName
sCurrentFolder = Left(sCurrentFolder, InstrRev(sCurrentFolder, "\"))
sFile = sCurrentFolder & sFile
End If

'Verify that file exists and is readable, return false if not.
If Not IsObject(oFileSystem) Then Set oFileSystem = WScript.CreateObject("Scripting.FileSystemObject")
Set oFile = oFileSystem.GetFile(sFile)
Set oTextStream = oFile.OpenAsTextStream(ForReading, OpenUsingDefault)
If Err.Number 0 Then
'WScript.Echo "Problem opening " & sFile & " (" & Err.Description & ")"
ParseInputFile = False
Exit Function
End If

'Count the number of lines in file, not including an empty line at the very end (if present).
iLineCount = 0
Do While Not oTextStream.AtEndOfStream
oTextStream.SkipLine
iLineCount = iLineCount + 1
Loop

'ReDim the array to be equal to expected size of the input from file.
If iLineCount 0 Then
ReDim aArray(iLineCount - 1)
oTextStream.Close
Set oTextStream = Nothing
Else 'The input file was empty!
ReDim aArray(0)
'aArray(0) = "" 'Assign default here if desired.
oTextStream.Close
Set oTextStream = Nothing
Set oFile = Nothing
Set oFileSystem = Nothing
If Err.Number = 0 Then
ParseInputFile = True
Else
ParseInputFile = False
End If
Exit Function
End If

'Read each line of file into an element of the array, excluding blank lines.
Set oTextStream = oFile.OpenAsTextStream(ForReading, OpenUsingDefault)
i = 0
iPreserveCounter = 0
Do While Not oTextStream.AtEndOfStream
sLine = Trim(oTextStream.ReadLine) 'Note the trimming here.
If Len(sLine) 0 Then
aArray(i) = sLine
i = i + 1
Else
iPreserveCounter = iPreserveCounter + 1 'Keep track of blank lines.
End If
Loop
oTextStream.Close
Set oTextStream = Nothing

'If there were blank lines in the file, trim the array of empty elements.
If iPreserveCounter 0 Then
iCurrentSize = UBound(aArray)
ReDim Preserve aArray(iCurrentSize - iPreserveCounter)
End If

Set oFile = Nothing
Set oFileSystem = Nothing

If Err.Number = 0 Then
ParseInputFile = True
Else
ParseInputFile = False
End If
End Function

'**********************************************************************************
' Script Name: Append_To_File.vbs
' Version: 1.3
' Author: Jason Fossen
'Last Updated: 28.Jul.2004
' Purpose: Function to append line(s) to the end of a text file.
' If the file does not exist, it will be created. If the full
' path to the file is not supplied, it is assumed to be in the
' same folder as the script. Function returns true if no
' errors, false otherwise.
' Notes: Because this function would repeatedly open and close the file,
' this function is not appropriate for writing many lines to a single
' file one line at a time. Many megs of text can be appended in one shot.
' Legal: Public Domain. Modify and redistribute freely. No rights reserved.
'**********************************************************************************

Function AppendToFile(sData, sFile)
On Error Resume Next

Const ForAppending = 8 'Request NTFS appending permission.
Const ForOverWriting = 2 'Request NTFS writing permission.
Const ForReading = 1 'Request NTFS read permission.
Const OpenAsASCII = 0 'ASCII text format.
Const OpenAsUnicode = -1 'Unicode text format.
Const OpenUsingDefault = -2 'ASCII is default for FAT32, Unicode default for NTFS.

Dim sCurrentFolder, oTextStream

'Create FileSystemObject if it doesn't exist yet.
If Not IsObject(oFileSystem) Then Set oFileSystem = WScript.CreateObject("Scripting.FileSystemObject")

'Expand any environmental variables to their full paths.
If InStr(sFile, "%") 0 Then
If Not IsObject(oWshShell) Then Set oWshShell = WScript.CreateObject("WScript.Shell")
sFile = oWshShell.ExpandEnvironmentStrings(sFile)
End If

'Use current folder of script for output file path, if not path is given.
If InStr(sFile, "\") = 0 Then
sCurrentFolder = WScript.ScriptFullName
sCurrentFolder = Left(sCurrentFolder, InstrRev(sCurrentFolder, "\"))
sFile = sCurrentFolder & sFile
End If

'Get output file if it exists, or create one if it doesn't.
If Not oFileSystem.FileExists(sFile) Then
Set oTextStream = oFileSystem.CreateTextFile(sFile)
Else
Set oFile = oFileSystem.GetFile(sFile)
Set oTextStream = oFile.OpenAsTextStream(ForAppending, OpenUsingDefault)
End If

'Must write data to a new line, so check the column number first.
If oTextStream.Column = 1 Then
oTextStream.Write(sData)
Else
oTextStream.WriteBlankLines(1)
oTextStream.Write(sData)
End If

oTextStream.Close

If Err.Number = 0 Then
AppendToFile = True
Else
AppendToFile = False
End If
End Function

'END OF SCRIPT************************************************************************

3 – No ISA Server 2006, Criar em c:\Blacklist o segundo arquivo .vbs obrigatoriamente com o nome: ISA_Fill_Domain_Name_Set.vbs

'*************************************************************************************
' Script Name: ISA_Fill_Domain_Name_Set.vbs
' Version: 1.2
' Author: Jason Fossen ( www.ISAscripts.org )
'Last Updated: 18.Feb.2008
' Purpose: Automatically update an ISA Server Domain Name Set with domains; for example,
' these could be domains of spammers, pornographers, hacking sites, etc.
' Arguments: First arg is name of Domain Name Set, in double-quotes if necessary. The
' second arg is the HTTP URL, local full path, or file name (if in same
' folder as script) of a text file containing the domain data. This file,
' if it contains comments, must use #-marks or semicolons to denote comments.
' Each line must be just a domain name, but if IP addresses are in the list, they
' will be ignored automatically. This script is compatible with, but does not
' require or depend on, the lists at:
' http://urlblacklist.com
' http://www.squidguard.org/blacklists/
' It also works if a listed domain begins or ends with a period, or begins
' with "*." as a wildcard. The file with the domains can use either
' Windows-style or UNIX-style newlines, it's compatible with both. Note that
' each domain will be added twice: once with a prepended "*." and another
' without the leading "*." wildcard, since ISA won't match on just the plain
' domain name in a URL if the domain has "*." prepended to it in the set.
' Note: Depending on the speed of the ISA box, importing a 10MB file with 500,000
' domains can take between two and four hours. This is a bottleneck imposed
' by ISA, not the Windows Script Host or VBScript. Hence, schedule your
' imports during off-peak hours and run the script with the Start command
' to launch it with a lower multi-tasking priority; for example, like this:
' "start /belownormal cscript.exe ImportBlacklist.vbs Bad-Sites domains"
' Note: The fastest way to see that the Domain Name Set had been filled correctly
' is to close and open the ISA MMC console again, not by refreshing.
' Works on both ISA Standard and Enterprise.
' Legal: Public Domain. Modify and redistribute freely. No rights reserved.
' SCRIPT PROVIDED "AS IS" WITHOUT WARRANTIES OR GUARANTEES OF ANY KIND.
' USE AT YOUR OWN RISK. Test on non-production servers first!
'*************************************************************************************

Option Explicit
On Error Resume Next

ReDim aDomainsArray(0) 'Array of Domains to be added to the Domain Name Set.
Dim sDomainNameSetName 'Name of Domain Name Set to be created and/or updated.
Dim bUseLocalDomainsFile 'If true, use local file. If false, get domains from http URL.
Dim sDomainsFilePath 'An HTTP URL or a local filesystem path to a file of domains.
Dim oFPC 'See MakeIsaObjects()
Dim oIsaArray 'See MakeIsaObjects()

Dim oFileSystem : Set oFileSystem = WScript.CreateObject("Scripting.FileSystemObject")
Call CatchAnyErrorsAndQuit("Problems creating the FileSystemObject.")

'*************************************************************************************
' Main()
'*************************************************************************************
Call ProcessCommandLineArguments()
Call CreateIsaObjects()
Call MakeArrayOfDomains()
Call CreateDomainNameSet()
Call EmptyTheDomainNameSet()
Call CreateNewDomains()

'*************************************************************************************
' Procedures
'*************************************************************************************

Sub ProcessCommandLineArguments()
On Error Resume Next
'
' First arg...
'
sDomainNameSetName = WScript.Arguments.Item(0)
Dim sArg : sArg = LCase(sDomainNameSetName)
If (WScript.Arguments.Count = 0) Or (WScript.Arguments.Count => 3) Or (sArg = "/?")_
Or (sArg = "-?") Or (sArg = "/h") Or (sArg = "/help") Or (sArg = "--help") Then
Call ShowHelpAndQuit()
End If

'
' Second arg...
'
sDomainsFilePath = WScript.Arguments.Item(1)

If InStr(LCase(sDomainsFilePath), "http://") = 0 Then
bUseLocalDomainsFile = True 'Use a local text file.
Else
bUseLocalDomainsFile = False 'Use an http URL.
End If
On Error Goto 0
End Sub

Sub CreateIsaObjects()
'This sub is just a placeholder for something to add later on...
Set oFPC = CreateObject("FPC.Root")
Set oIsaArray = oFPC.GetContainingArray
Call CatchAnyErrorsAndQuit("Problems connecting to ISA Server or ISA Array.")
End Sub

Sub MakeArrayOfDomains()
If bUseLocalDomainsFile Then
If Not ParseInputFile(sDomainsFilePath, aDomainsArray) Then
Err.Raise -1
Call CatchAnyErrorsAndQuit("Problems reading the local domains file: " & sDomainsFilePath)
End If
Else 'Get the domains file from the http URL...
Dim sUrlText : sUrlText = HttpGetText(sDomainsFilePath)
If InStr(sUrlText, "GET-Error!") 0 Then ' "GET-Error!" would be returned by HttpGetText() function, not the web server.
Err.Raise -1
Call CatchAnyErrorsAndQuit("Problems getting domains file from " & sUrlToDomainsFile)
End If

If oFileSystem.FileExists("domains-downloaded-from-url.txt") Then
oFileSystem.DeleteFile "domains-downloaded-from-url.txt", True 'Delete prior domains file, if it exists.
End If

If Not AppendToFile(sUrlText, "domains-downloaded-from-url.txt") Then
Err.Raise -1
Call CatchAnyErrorsAndQuit("Problems writing to the domains-downloaded-from-url.txt file.")
End If

If Not ParseInputFile("domains-downloaded-from-url.txt", aDomainsArray) Then
Err.Raise -1
Call CatchAnyErrorsAndQuit("Problems reading file: domains-downloaded-from-url.txt")
End If
End If

End Sub

Sub CreateDomainNameSet()
On Error Resume Next
Dim cDomainNameSets 'FPCDomainNameSets collection.
Dim oDomainNameSet 'FPCDomainNameSet object.

'Set oFPC = CreateObject("FPC.Root")
'Set oIsaArray = oFPC.GetContainingArray
Set cDomainNameSets = oIsaArray.RuleElements.DomainNameSets

Set oDomainNameSet = cDomainNameSets.Add(sDomainNameSetName)

If Err.Number = -2147024713 Then
Err.Clear 'Already exists, so ignore error.
Else
cDomainNameSets.Save
End If

Call CatchAnyErrorsAndQuit("Problems recreating Domain Name Set named " & sDomainNameSetName)
On Error Goto 0
End Sub

Sub EmptyTheDomainNameSet()
'Note: Clear the Domain Name Set instead of deleting it because it may be used in rules already.
Dim cDomainNameSets 'FPCDomainNameSets collection.
Dim cDomainNameSet 'FPCDomainNameSet collection.
Dim sDomain

'Set oFPC = CreateObject("FPC.Root")
'Set oIsaArray = oFPC.GetContainingArray
Set cDomainNameSet = oIsaArray.RuleElements.DomainNameSets.Item(sDomainNameSetName)

For Each sDomain In cDomainNameSet
cDomainNameSet.Remove(sDomain)
Next

cDomainNameSet.Save

Call CatchAnyErrorsAndQuit("Problems emptying Domain Name Set named " & sDomainNameSetName)
End Sub

Sub CreateNewDomains()
On Error Resume Next
Dim cDomains 'FPCURLSets collection.
Dim oDomain 'FPCDomain object.
Dim cDomainNameSet 'FPCDomainNameSet collection.
Dim cDomainNameSets 'FPCDomainNameSets collection.
Dim sIPaddress, sMask, sDomain, sDomainName

Set cDomainNameSet = oIsaArray.RuleElements.DomainNameSets.Item(sDomainNameSetName)

For Each sDomain In aDomainsArray
If (Left(sDomain, 1) "#") And (Left(sDomain, 1) ";") And (Left(sDomain, 1) "<") And (Len(sDomain) 0) And Not IsIpAddress(sDomain) Then
If Right(sDomain,1) = "." Then sDomain = Left(sDomain, Len(sDomain) - 1) 'Trim off a trailing period, if present.
If Left(sDomain,2) "*." Then sDomain = "*." & sDomain 'Prepend "*." if not already there.
sDomain = Replace(sDomain, "..", ".") 'Correct if first char was already a period.
cDomainNameSet.Add(sDomain)
If Err.Number = -2147024713 Then Err.Clear 'Domain already added, so ignore error.

'Comment out the next three lines if you don't want the plain "domain.com" entries added too (the ones without the leading "*.").
sDomain = Trim(Replace(sDomain, "*.", ""))
cDomainNameSet.Add(sDomain)
If Err.Number = -2147024713 Then Err.Clear 'Domain already added, so ignore error.
End If
Next

cDomainNameSet.Save

Call CatchAnyErrorsAndQuit("Problems creating new domain objects in " & sDomainNameSetName)
On Error Goto 0
End Sub

Sub CatchAnyErrorsAndQuit(sMessage)
Dim oStdErr
If Err.Number 0 Then
Set oStdErr = WScript.StdErr 'Write to standard error stream.
oStdErr.WriteLine vbCrLf
oStdErr.WriteLine ">>>>>> ERROR: " & sMessage
oStdErr.WriteLine "Error Number: " & Err.Number
oStdErr.WriteLine " Description: " & Err.Description
oStdErr.WriteLine "Error Source: " & Err.Source
oStdErr.WriteLine " Script Name: " & WScript.ScriptName
oStdErr.WriteLine vbCrLf
WScript.Quit Err.Number
End If
End Sub

Sub ShowHelpAndQuit()
Dim sUsage : sUsage = vbCrLf
sUsage = sUsage & vbCrLf
sUsage = sUsage & "ISA_FILL_DOMAIN_NAME_SET.VBS DomainNameSetName FilePath" & vbCrLf
sUsage = sUsage & vbCrLf
sUsage = sUsage & "Creates or updates an ISA Server Domain Name Set (`DomainNameSet`)" & vbCrLf
sUsage = sUsage & "with the domains from a text file (`FilePath`) obtained from" & vbCrLf
sUsage = sUsage & "either an HTTP URL or a local filesystem path." & vbCrLf
sUsage = sUsage & vbCrLf
sUsage = sUsage & " DomainNameSet Name of Domain Name Set to be created or" & vbCrLf
sUsage = sUsage & " updated with domain entries. Will be" & vbCrLf
sUsage = sUsage & " created in the local ISA Server or" & vbCrLf
sUsage = sUsage & " current ISA Server Array." & vbCrLf
sUsage = sUsage & vbCrLf
sUsage = sUsage & " FilePath A full HTTP URL or local filesystem path" & vbCrLf
sUsage = sUsage & " to a text file containing domains. All" & vbCrLf
sUsage = sUsage & " comments must start with # or ;. Examples" & vbCrLf
sUsage = sUsage & " might be `filename.txt`, `c:\filename.txt`," & vbCrLf
sUsage = sUsage & " or `http://www.fqdn.com/filename.asp`." & vbCrLf
sUsage = sUsage & vbCrLf
sUsage = sUsage & "Note that all domains defined in the Domain Name Set are deleted" & vbCrLf
sUsage = sUsage & "prior to importing the domains from the text file. If necessary," & vbCrLf
sUsage = sUsage & "the Domain Name Set object will be created. Place double-quotes" & vbCrLf
sUsage = sUsage & "around the DomainNameSet and FilePath arguments if they contain" & vbCrLf
sUsage = sUsage & "any space characters. When providing an HTTP URL, the downloaded" & vbCrLf
sUsage = sUsage & "file will be saved as 'domains-downloaded-from-url.txt` in the " & vbCrLf
sUsage = sUsage & "same folder as the script; it will be overwritten whenever a URL" & vbCrLf
sUsage = sUsage & "path is used again. Script must be run on the ISA Server itself." & vbCrLf
sUsage = sUsage & vbCrLf
sUsage = sUsage & "SCRIPT PROVIDED ""AS IS"" AND WITHOUT WARRANTIES OR GUARANTEES OF ANY KIND." & vbCrLf
sUsage = sUsage & "USE AT YOUR OWN RISK. ( www.ISAscripts.org )" & vbCrLf
sUsage = sUsage & vbCrLf

WScript.Echo sUsage
WScript.Quit
End Sub

'*************************************************************************************
' Functions
'*************************************************************************************

Function IsIpAddress(sInput)
'Regular expression would be more accurate, but slower...quick-n-dirty will do since
'having a "*.dottedIPaddress" domain doesn't break anything if an IP address sneaks by...

IsIpAddress = False

Dim sEnd
sInput = LCase(sInput)
sEnd = Right(sInput,1) 'This will catch 98% of cases, so it's faster than RegEx.
If (sEnd = "m") Or (sEnd = "u") Or (sEnd = "l") Or (sEnd = "v") Or (sEnd = "g")_
Or (sEnd = "t") Or (sEnd = "z") Or (sEnd = "o") Or (sEnd = "e") Or (sEnd = "s")_
Or (sEnd = "r") Or (sEnd = "n") Or (sEnd = "c") Or (sEnd = "k") Or (sEnd = "e") Then Exit Function

Dim aArray, x
aArray = Split(sInput,".")
If UBound(aArray) 3 Then Exit Function

If Not (IsNumeric(aArray(0)) And IsNumeric(aArray(1)) And IsNumeric(aArray(2)) And IsNumeric(aArray(3))) Then Exit Function

IsIpAddress = True
End Function

Function HttpGetText(sURL)
On Error Resume Next

If Not IsObject(oHTTP) Then Dim oHTTP : Set oHTTP = WScript.CreateObject("Microsoft.XMLHTTP")

oHTTP.Open "GET", sURL, False 'False = Script waits until the full HTTP response is received.
oHTTP.Send 'Send the HTTP command as defined with the Open method.

If Err.Number = 0 Then
HttpGetText = oHTTP.ResponseText
HttpGetText = Replace(HttpGetText, vbLf, vbCrLf) 'Flip UNIX new lines to DOS, if necessary.
Else
HttpGetText = "GET-Error! Error Number: " & Err.Number
End If
End Function

'*********************************************************************************
' Script Name: Parse_Input_File.vbs
' Version: 1.1
' Author: Jason Fossen
'Last Updated: 29.Mar.2004
' Purpose: Sorts lines of a text file into an array.
' Usage: Function returns true if no problems, false otherwise. Pass global
' variable of an array into second argument of function; this will be
' resized and populated with lines from text file. Blank and empty
' trailing lines from file, if any, are excluded from the array. The
' array global variable must be declared with "ReDim", not just "Dim".
' The file can be passed in with full path or just the file name if
' the file is in the same folder as the script.
' Note: You must declare the global array variable with "ReDim" before
' passing it into the function; make it of size one because it
' will be ReDim-ed without preservation again anyway.
' Legal: Public Domain. Modify and redistribute freely. No rights reserved.
' Use at your own risk. Do not run on networks for which you do not
' have prior written permission to do so. Script provided "AS IS".
'*********************************************************************************

Function ParseInputFile(ByVal sFile, ByRef aArray)
On Error Resume Next
Const ForReading = 1
Const OpenUsingDefault = -2
Dim sCurrentFolder, oFileSystem, oInputFile, i, iCurrentSize
Dim iPreserveCounter, oFile, oTextStream, iLineCount, sLine

'Expand environmental variables, if any.
If InStr(sFile, "%") 0 Then
If Not IsObject(oWshShell) Then Set oWshShell = WScript.CreateObject("WScript.Shell")
sFile = oWshShell.ExpandEnvironmentStrings(sFile)
End If

'Assume input file is in current folder if a full path is not given.
If InStr(sFile, "\") = 0 Then
sCurrentFolder = WScript.ScriptFullName
sCurrentFolder = Left(sCurrentFolder, InstrRev(sCurrentFolder, "\"))
sFile = sCurrentFolder & sFile
End If

'Verify that file exists and is readable, return false if not.
If Not IsObject(oFileSystem) Then Set oFileSystem = WScript.CreateObject("Scripting.FileSystemObject")
Set oFile = oFileSystem.GetFile(sFile)
Set oTextStream = oFile.OpenAsTextStream(ForReading, OpenUsingDefault)
If Err.Number 0 Then
'WScript.Echo "Problem opening " & sFile & " (" & Err.Description & ")"
ParseInputFile = False
Exit Function
End If

'Count the number of lines in file, not including an empty line at the very end (if present).
iLineCount = 0
Do While Not oTextStream.AtEndOfStream
oTextStream.SkipLine
iLineCount = iLineCount + 1
Loop

'ReDim the array to be equal to expected size of the input from file.
If iLineCount 0 Then
ReDim aArray(iLineCount - 1)
oTextStream.Close
Set oTextStream = Nothing
Else 'The input file was empty!
ReDim aArray(0)
'aArray(0) = "" 'Assign default here if desired.
oTextStream.Close
Set oTextStream = Nothing
Set oFile = Nothing
Set oFileSystem = Nothing
If Err.Number = 0 Then
ParseInputFile = True
Else
ParseInputFile = False
End If
Exit Function
End If

'Read each line of file into an element of the array, excluding blank lines.
Set oTextStream = oFile.OpenAsTextStream(ForReading, OpenUsingDefault)
i = 0
iPreserveCounter = 0
Do While Not oTextStream.AtEndOfStream
sLine = Trim(oTextStream.ReadLine) 'Note the trimming here.
If Len(sLine) 0 Then
aArray(i) = sLine
i = i + 1
Else
iPreserveCounter = iPreserveCounter + 1 'Keep track of blank lines.
End If
Loop
oTextStream.Close
Set oTextStream = Nothing

'If there were blank lines in the file, trim the array of empty elements.
If iPreserveCounter 0 Then
iCurrentSize = UBound(aArray)
ReDim Preserve aArray(iCurrentSize - iPreserveCounter)
End If

Set oFile = Nothing
Set oFileSystem = Nothing

If Err.Number = 0 Then
ParseInputFile = True
Else
ParseInputFile = False
End If
End Function

'**********************************************************************************
' Script Name: Append_To_File.vbs
' Version: 1.3
' Author: Jason Fossen
'Last Updated: 28.Jul.2004
' Purpose: Function to append line(s) to the end of a text file.
' If the file does not exist, it will be created. If the full
' path to the file is not supplied, it is assumed to be in the
' same folder as the script. Function returns true if no
' errors, false otherwise.
' Notes: Because this function would repeatedly open and close the file,
' this function is not appropriate for writing many lines to a single
' file one line at a time. Many megs of text can be appended in one shot.
' Legal: Public Domain. Modify and redistribute freely. No rights reserved.
'**********************************************************************************

Function AppendToFile(sData, sFile)
On Error Resume Next

Const ForAppending = 8 'Request NTFS appending permission.
Const ForOverWriting = 2 'Request NTFS writing permission.
Const ForReading = 1 'Request NTFS read permission.
Const OpenAsASCII = 0 'ASCII text format.
Const OpenAsUnicode = -1 'Unicode text format.
Const OpenUsingDefault = -2 'ASCII is default for FAT32, Unicode default for NTFS.

Dim sCurrentFolder, oTextStream

'Create FileSystemObject if it doesn't exist yet.
If Not IsObject(oFileSystem) Then Set oFileSystem = WScript.CreateObject("Scripting.FileSystemObject")

'Expand any environmental variables to their full paths.
If InStr(sFile, "%") 0 Then
If Not IsObject(oWshShell) Then Set oWshShell = WScript.CreateObject("WScript.Shell")
sFile = oWshShell.ExpandEnvironmentStrings(sFile)
End If

'Use current folder of script for output file path, if not path is given.
If InStr(sFile, "\") = 0 Then
sCurrentFolder = WScript.ScriptFullName
sCurrentFolder = Left(sCurrentFolder, InstrRev(sCurrentFolder, "\"))
sFile = sCurrentFolder & sFile
End If

'Get output file if it exists, or create one if it doesn't.
If Not oFileSystem.FileExists(sFile) Then
Set oTextStream = oFileSystem.CreateTextFile(sFile)
Else
Set oFile = oFileSystem.GetFile(sFile)
Set oTextStream = oFile.OpenAsTextStream(ForAppending, OpenUsingDefault)
End If

'Must write data to a new line, so check the column number first.
If oTextStream.Column = 1 Then
oTextStream.Write(sData)
Else
oTextStream.WriteBlankLines(1)
oTextStream.Write(sData)
End If

oTextStream.Close

If Err.Number = 0 Then
AppendToFile = True
Else
AppendToFile = False
End If
End Function

'END OF SCRIPT************************************************************************

4 – Baixar a blacklist shallalist.tar.gz e extrai-la em uma pasta temporária. Mover de dentro desse arquivo toda pasta BL para dentro do diretorio C:\Blacklist ficando assim… C:\Blacklist\BL\adv\domains (por exemplo, aonde adv é uma das tantas categorias)

5 – Finalizando

A bat Execute-Import-In-ISA2006.bat vai chamar dois scripts que vão iportar os dados da Blacklist baixada no site da Shalllist
Basta executa-la e aguardar que todas as blacklists sejam importadas.
Apos finalizar abra o ISA Server e crie as regras com as novas Desination URL_Sets e Domain_Name referentes as categorias que voce deseja bloquear ou liberar

Publicado em Como Fazer?, Interessantes, Soluções Técnicas, Suporte Técnico | 1 Comentário

Select Data Atual

Caso seja necessário realizar a busca por um determinado valor do tipo DATE (DATA) filtrando pelo ano, mes ou dia atual podemos executar o script abaixo.
Supondo que minha tabela se chame ENTRADAS e a coluna contendo todos os dados referente a datas se chame Date
Filtrando pelo Mes atual em ordem Decrescente:
SELECT     TOP (1000) Date
FROM         Entradas
WHERE
(YEAR(Date) = YEAR(GETDATE())) AND (MONTH(Date) = MONTH(GETDATE()))
ORDER BY Date DESC
Filtrando pelo Dia atual em ordem Decrescente:
SELECT TOP (1000) Date
FROM Entradas
WHERE
(YEAR(Date) = YEAR(GETDATE())) AND (MONTH(Date) = MONTH(GETDATE())) AND (DAY(Date) = DAY(GETDATE()))
ORDER BY Date DESC
Publicado em Soluções Técnicas | Deixe um comentário

Instalação do IE 7 no Windows XP SP3

Pra quem pegou um vírus, precisou formatar o pc e só tinha o CD do Windows XP SP3, ou quis, por vontade própria, instalar o Service Pack 3  e depois de tudo tentou instalar sem sucesso oInternet Explorer 7 (IE7), a solução do problema é simples e não requer conhecimento técnico avançado.
A resolução do problema de não poder instalar o Internet Explorer 7 no Windows XP Service Pack 3 é simplesmente seguir os seguintes passos:

1º Abra o prompt de comando do windows (Inicia -> Executar) e digite o seguinte comando:

secedit /configure /cfg %windir%\repair\secsetup.inf /db secsetup.sdb /verbose

2º Após executar o comando uma tela preta do console do windows abrirá e fará automaticamente o reparo de possíveis problemas que impossibilitam a instalação do IE7 no SP3;

3º Agora é só tentar instalar o Internet Explorer 7 (IE7) e correr pro abraço

Publicado em Uncategorized | Deixe um comentário

SQL 2008: Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created.

Sintoma: Ao salvar uma alteração em um campo de uma tabelo no banco de dados ocorre  a seguinte mensagem de erro: ”Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created.”

Solução:

  • Clique no menu Tools > Options
    Agora em Designer basta desmarcar a opção Prevent saving changes that require the table to be re-created.
  • Publicado em Uncategorized | 1 Comentário

    Erro ao anexar arquivo a um work item no TFS

    Sintoma: Ao anexar um arquivo a um WorkItem no servidor team foudation utilizando o Visual Studio nos deparamos a seguinte mensagem de erro ao Salvar o Anexo:

    TF237082: The Attachment could not be uploaded. Verify that you have a network connection and that Team Foundation Server is avaible. If the problem persists, provide the following information to the server administrator.
    The Server returned the following message: The remote server returned an error: (500) Internal Server Error.

    Ao Anexar arquivos ao Work Item utilizando o Tem WebAccess recebemos a mensagem a seguir:

    “Attachment upload failed. Check that you have a network connection and that the Team Foudation Server is availble. If the problem persists, contact your Team Foudation Server Administrator.”

    Ao checar os eventos ocorridos no servidor TFS nos deparamos com o seguinte evento de erro no momento em que tentamos anexar o arquivo no work item:

    O Seguinte log de evento ocorre no meu servidor tfs imediatamente apos o erro gerado no portal ou no Visual Studio:
    Event Type: Error
    Event Source: TFS WorkItem Tracking
    Event Category: None
    Event ID: 3000
    Date:  12/8/2010
    Time:  4:32:57 PM
    User:  N/A
    Computer: %SERVERNAME%
    Description:
    TF53010: The following error has occurred in a Team Foundation component or extension:
    Date (UTC): 12/8/2010 6:32:57 PM
    Machine: %SERVERNAME%
    Application Domain: /LM/W3SVC/322882837/Root/WorkItemTracking-3-129362259372029125
    Assembly: Microsoft.TeamFoundation.Common, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a; v2.0.50727
    Process Details:
      Process Name: w3wp
      Process Id: 6100
      Thread Id: 4312
      Account name: %Domain\User%

    Detailed Message: TF51334: An unknown Web service error occurred: A severe error occurred on the current command.  The results, if any, should be discarded.. Check the Event Log for more information.
    Web Request Details
        Url: http://teamserver.dominio.local:8080/WorkItemTracking/v1.0/AttachFileHandler.ashx [method: POST]
        User Agent: Team Foundation 9.0.21022.8, (WebAccess 9.0.3000)
        Headers: Content-Length=15280&Content-Type=multipart%2fform-data%3b+boundary%3d————————–8cd650cc10fa8fe&Accept-Language=pt-BR&Expect=100-continue&Host=teamserver.perlink.net%3a8080&User-Agent=Team+Foundation+9.0.21022.8%2c+(WebAccess+9.0.3000)&X-TFS-Version=1.0.0.0&X-TFS-Session=a1f46f21-1b5a-4b1a-8b82-b85cd4137581
        Path: /WorkItemTracking/v1.0/AttachFileHandler.ashx
        Local Request: False
        Host Address: %IP Client%
        User: %domain\user% [authentication type: NTLM]

    Exception Message: TF51334: An unknown Web service error occurred: A severe error occurred on the current command.  The results, if any, should be discarded.. Check the Event Log for more information. (type ConfigurationException)

    Exception Stack Trace:

    Inner Exception Details:

    Exception Message: A severe error occurred on the current command.  The results, if any, should be discarded. (type SqlExistingConnectionForciblyClosedException)

    Exception Stack Trace:    at Microsoft.TeamFoundation.WorkItemTracking.Server.SqlAccess.HandleDalError(Exception e)
       at Microsoft.TeamFoundation.WorkItemTracking.Server.SqlAccess.ExecuteBatchPayloadImpl(IRequestContext context, String sqlBatch, List`1 parameterList, Boolean& errorOnBulkUpdate, String connectionString)
       at Microsoft.TeamFoundation.WorkItemTracking.Server.SqlAccess.ExecuteBatchPayload(IRequestContext context, String sqlBatch, List`1 parameterList, Boolean& errorOnBulkUpdate)
       at Microsoft.TeamFoundation.WorkItemTracking.Server.AdoDbBase.ExecuteBatchQuery(IRequestContext context, String sqlBatch, List`1 parameterList)
       at Microsoft.TeamFoundation.WorkItemTracking.Server.SqlBatchBuilder.ExecuteBatchInternal(IRequestContext context, Boolean passInConnectionInfo, String server, String database)
       at Microsoft.TeamFoundation.WorkItemTracking.Server.SqlBatchBuilder.ExecuteBatch()
       at Microsoft.TeamFoundation.WorkItemTracking.Server.DataAccessLayerImpl.AddFileAttachment(String attachmentServerName, String attachmentDatabaseName, String clientUserName, Stream fileInput, String fileGuid, String projectUri)
       at Microsoft.TeamFoundation.WorkItemTracking.Server.AttachmentUploadHandler.ProcessRequest(HttpContext context)

    Inner Exception Details:

    Exception Message: A severe error occurred on the current command.  The results, if any, should be discarded. (type SqlException)
    SQL Exception Class: 11
    SQL Exception Number: 0
    SQL Exception Procedure:
    SQL Exception Line Number: 0
    SQL Exception Server: %SQL SERVER%
    SQL Exception State: 0
    SQL Error(s):

    Exception Data Dictionary:
    HelpLink.ProdName = Microsoft SQL Server
    HelpLink.ProdVer = 10.00.1600
    HelpLink.EvtSrc = MSSQLServer
    HelpLink.EvtID = 0
    HelpLink.BaseHelpUrl = http://go.microsoft.com/fwlink
    HelpLink.LinkId = 20476
    Exception Stack Trace:    at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
       at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
       at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
       at System.Data.SqlClient.SqlDataReader.ConsumeMetaData()
       at System.Data.SqlClient.SqlDataReader.get_MetaData()
       at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
       at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
       at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
       at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
       at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
       at System.Data.SqlClient.SqlCommand.ExecuteReader()
       at Microsoft.TeamFoundation.WorkItemTracking.Server.SqlAccess.ExecuteReaderWithRetry(SqlCommand sqlCommand, SqlConnection sqlConnection, SqlDataReader& dataReader)
       at Microsoft.TeamFoundation.WorkItemTracking.Server.SqlAccess.ExecuteBatchPayloadImpl(IRequestContext context, String sqlBatch, List`1 parameterList, Boolean& errorOnBulkUpdate, String connectionString)

    Solução: Depois de uma longa jornada cheguamos a conclusão de que existia uma tabela corrompida no database TfsWorkItemTrackingAttachments.

    Essa tabela traz todos os anexos do portal TFS e por algum motivo corrompeu… para solucionar esse problema basta recorrer ao bom e velho bkp que não impactará nos outros dados do nosso portal e já que não conseguiamos anexar documentos fazia algum tempo, um restore não trouxe nenhuma perda para nossos projetos (o maximo que se perde aí sao os anexos que foram incluidos nos workitens caso o bkp seja de dias anteriores ao dia do problema ocorrido.

    Recomendo que seja feito os seguinte passsos:
    1 - Backup do banco TfsWorkItemTrackingAttachments
    2 – Detach no banco TfsWorkItemTrackingAttachments
    3 – Rename nos arquivos mdf e ldf para TfsWorkItemTrackingAttachments.mdf.old e TfsWorkItemTrackingAttachments_1.ldf.old
    4 – Restore do banco com o Backup do ultimo dia em que foi utilizada a função de anexo em um work Item pelo Visual Studio ou pelo Team System WebAccess

    Publicado em Suporte Técnico | Deixe um comentário

    Instalação, Configuração e Manutenção do PFSense

    Treinamento
    EficienTI

    Administração de um Firewall PFSense

    Treinamentos

    Versão 1

    Emissão: 15 de Janeiro de 2011

    Validade: Indeterminada

    Conteúdo

    SUMÁRIO EXECUTIVO
    ADMINISTRAÇÃO DO PFSENSE
    1.    OBJETIVO

    2.    SOBRE O PFSENSE

    3.    PRÉ-REQUISITOS

    4.    INTRODUÇÃO À SEGURANÇA EM REDE

    4.1.    Definição

    5.    PRÉ-REQUISITOS PARA INSTALAÇÃO DO PFSENSE

    5.1.    Compatibilidade de Hardware

    5.2.    Mídia do PFSENSE

    5.3.    Requisitos de Hardware

    6.    INSTALAÇÃO DO PFSENSE

    7.    CONFIGURAÇÕES INICIAIS DO PFSENSE

    8.    AUMENTANDO A SEGURANÇA DO PFSENSE
    9.    INSTALAÇÃO DE PACKAGES
    9.1.    Instalando os Packages

    9.2.    Verificando Packages instalados

    10.    RULES: DEFININDO REGRAS DE ACESSO

    11.    PROXY: CONFIGURAÇÕES DO SQUID

    11.1.    Configurações Iniciais do Serviço de Proxy

    11.2.    Métodos de Autenticação

    11.3.    Cache

    11.4.    Access Control

    12.    PROXY: CONFIGURAÇÕES DO SQUIDGUARD
    12.1.    Baixando BlackLists
    12.2.    Gerenciando BlackLists

    12.3.    SquidGuard Logs

    13.    DHCP SERVER

    14.    DHCP RELAY

    15.    NAT PORT FORWARD

    15.1.    Port Forward

    15.2.    NAT 1:1

    16.    BACKUP / RESTORE

    Sumário Executivo

    A EficienTI é uma empresa de prestação de serviços de Infra-Estrutura de TI, originada a partir de uma empresa parceira Gold Microsoft, especializada em Infra-Estrutura de TI.

    Outros serviços oferecidos pela EficienTI incluem soluções de hospedagem, terceirização de serviços de TI e serviços de ServiceDesk.

    A EficienTI se caracteriza pelo compromisso absoluto com a entrega de soluções de alta qualidade, dentro do prazo e custo estimados. Nossos gerentes são especializados na entrega de soluções que melhor atendam a necessidade dos clientes, de maneira eficiente e de acordo com o escopo definido.

    A EficienTI possui profissionais com especialização nas competências Microsoft relativas a NetWorking Infrastructure Solutions, Linux, Gerência, Melhores Práticas e Controle de T.I. Entre as certificações de seus profissionais estão ITILF, COBITF, CSM, LPIC-1, LPIC-2, MCTS, MCSE, MCSA, MCDBA, MCSD e MCAD.

    Administração do PFSENSE

    Objetivo

    Capacitar à instalar, configurar e administrar recursos de Firewall, Proxy, DHCP, NAT Port Forwarding e VPN utilizando o pfSense, um firewall estavel montado sobre a plataforma FreeBSD.

    Sobre o PFSense

    O pfSense é um dos mais conhecidos e provavelmente mais rico, em recursos, entre os sistemas para appliance pré-configurado. Nascido em uma versão customizada do estável FreeBSD, conta com uma interface amigável que facilita a administração. Com gerenciamento via Web, oferece inúmeros recursos, focado para ambiente de roteamento e firewalling, bem como segurança de networking, excelente solução para VPN entre outros diversos recursos.

    Pré-Requisitos

    Conhecimento básico em redes de computadores

    Introdução à Segurança em Rede

    Definição

    Consiste em atuar em uma linha de defesa eficaz em três pontos principais em uma rede:

    • Defesa contra catástrofes
    • Defesa contra falhas previsíveis
    • Defesa contra acesso não autorizado

    Para atacas essas áreas com eficiência, podemos trabalhar com os seguintes recursos de TI:

    • Criptografia
    • Gestão de Chaves Públicas
    • Firewalls
    • Sistema de Detecção de Intrusão
    • Redes Virtuais Privadas (VPN)
    • Segurança em Redes Sem Fio

    Pré-Requisitos para Instalação do PFSense

    Compatibilidade de Hardware

    Antes de iniciar a instalação do PFSense, recomenda-se verificar no centro de compatibilidade do FreeDSD afim de escolher o melhor hardware possível para a instalação: http://www.freebsd.org/releases/7.2R/hardware.html

    Mídia do PFSENSE

    Primeiramente devemos baixar a ultima versão estável do PFSense disponível no site do PFSEnse.org http://www.pfsense.org/mirror.php?section=downloads

    Após realizar o Download da imagem através de um dos mirro’s disponíveis, podemos usar o 7-zip para Descompactar a imagem e finalmente o um gravador de imagem (.ISO), cito por exemplo, o BurnWare Free

    Requisitos de Hardware

    Recomenda-se utilizar um servidor com pelo menos 1.5 Ghz de processador e 512MB de Ram.

    Necessário utilizarmos no mínimo 2 placas de rede

    Instalação do PFSense Passo a Passo

    Passo 1

    O CD baixado no site do PFSense, funciona com um “live cd”, ou seja, todo o sistema pfsense já está previamente carregado e pronto para uso ao iniciarmos o nosso servidor a partir do CD Rom. Isso pode ser muito útil para casos de emergência em que faz-se necessário subir rapidamente o firewall, tendo que apenas iniciar o servidor a partir do cd e importar as configurações que podem ser salvas em um arquivo XML.

    Passo 2

    Ao inicializar o cd será carregado o sistema PFSense até que seja necessário realizar as configurações iniciais de rede conforme print abaixo

    Passo 3

    As interfaces de rede disponíveis serão exibidas, como no exemplo acima, como em0 e em1. Quando for perguntado se você quer configurar uma vlan responda que não digitando N e em seguida enter.

    Você será perguntado agora quais são as suas interfaces LAN e WAN, basta definir de acordo com a sua preferência conforme print abaixo:


    Passo 4

    Após esse processo o PFSense já estará pronto para utilização visto que é um live cd, porem recomenda-se realizar a instalação no próprio disco rígido para maior performance e estabilidade do sistema. Faça isso usando a opção 99

    Passo 5

    Aceite as configurações de console atuais (vídeo, teclado etc…)

    Passo 6

    Quick Install para uma instalação automatizada

    Passo 7

    1. Será exibido um alerta de que seu HD será formatado e o PFSense instalado no disco rigido, clique ok

      Passo 8

      Quando for perguntado da instalação do Kernel, marque a opção que melhor se adequar ao seu processador. Basicamente, se você estiver utilizando um único processador escolha “Uniprocessor Kernel” caso esteja usando mais de um processador marque “Symmetric Multiprocessing Kernel”

      Passo 9

      Quando for exibida a tela abaixo você terá finalizado a instalação do PFSense com sucesso. Será solicitado o Reboot do servidor, lembrando que será necessário retirar o cd da unidade

      Configurações Iniciais do PFSense

      Passo 1

      Após a instalação e reboot do PFSENSE (Boot a partir do HD), estaremos com nosso sistema pronto para ser configurado via Web

      Passo 2

      Caso necessário, podemos alterar o IP da rede interna com a opção 2.

      Obs: Lembre-se de não habilitar o DHCP no seu PFSense caso não seja realmente necessário.

      Após a definição do IP correto da rede interna podemos acessar o PFSense a partir de uma estação na sua rede interna, digitando pelo seu navegador o endereço da LAN do PFSense.

      Digite as credenciais: Usuario: Admin; Password: pfsense, para inicializar o wizard de configuração inicial.

      Passo 3

    Configure o Nome do seu servidor Proxy/firewall, domínio e o DNS apontando para os servidores interno, caso disponível.

    Passo 4

    Altere o timezone para America/São Paulo

    Passo 5

    Configure sua interface WAN de acordo com as configurações da sua prestadora de serviço de internet

    Passo 6

    Confirme as configurações da sua LAN e redefina e documente sua senha de acesso ao PFSENSE. Será solicitado que você recarregue as configurações do PFSense:

    Passo 7

    Com isso o PFSense já esta devidamente configurado com as configurações básicas e apto a navegação de seus clientes.

    Aumentando a Segurança do PFSENSE

    Para uma melhor experiência com o PFSense, devemos deixar a tela do console bloqueada para acesso somente autorizado com senha, para isso basta navegar em System, Advanced e na opção Miscellaneous marque a Check-box Password protect… salve as alterações e reinicie o PFSENSE

    Instalação de Packages

    Instalando os Packages

    Selecionamos alguns dos pacotes mais importantes para nossa estrutura inicial. Abaixo a lista dos Packages que devemos instalar. Para instalá-los navegue em SYSTEM > PACKAGES e clique no botão “+” ao lado da descrição do pacote. Execute a instalação na seguinte ordem:

    1 – squid: Servidor Proxy. Reduz utilização da conexão e melhora tempo de resposta fazendo cachê de suas requisições além de prover um nível básico de controle e segurança no acesso à URL’s potencialmente perigosos

    2 – Lightsquid: Ferramenta responsável pela geração de relatórios de acesso

    3 – squidGuard: Poderosa ferramenta de acesso que integrado ao squid permite controlar a navegação baseado no endereço de origem, destino, URL, Hoário ou combinações desses itens. Conta com blacklists agrupados em categorias de sites e atende 1000.000 solicitações em 10 segundos segundo o site oficial.


    Verificando Packages instalados

    Poderemos consultar os pacotes instalados posteriormente em Installed Packages.

    Rules: Definindo Regras de Acesso

    Firewall > Rules: Podemos editar nossas regras permitindo ou negando o acesso à protocolos e portas de qualquer origem para qualquer destino, defindo conforme política de segurança da TI da empresa ou Grupo.

    Caso você não tenha nenhuma regra de liberação criada o comportamento do PFSense é de bloquear todo trafego de entrada e saída.

    Proxy: Configurações do Squid

    Services > Proxy Server:

    Configurações Iniciais do Serviço de Proxy

    Na aba General do nosso Proxy Server podemos definir as configurações básicas do nosso serviço tais como:

    • Interface
    • Habilitar Proxy Transparente
    • Log
    • Porta
    • Servidores DNS

    Métodos de Autenticação

    Para configuração do Squid como proxy da nossa organização, podemos utilizar basicamente 3 metodos de acesso:

    • Transparent Proxy
    • Autenticação com usuario Local do PFSense
    • Autenticação Integrada com recursos Externos (LDAP – Windows Active Directory)

    Transparent Proxy: A estação de trabalho se conecta ao PFSense como Gateway que se apropria da requisição para sair para internet como Proxy. Para habilitar basta marcar a check box correspondente na aba geral do Proxy Server

    PFSense Local User: Para este método de autenticação deve-se criar um ou mais usuarios na ana Local Users e em seguida em Auth Settings definir o metodo de autenticação como Local.

    Autenticação Integrada com AD (LDAP): Para que os usuarios de um dominio Windows 2003 possam autenticar com seus usuarios do AD no PFSense devemos definir em Auth Setting o método de autenticação LDAP seguindo as configurações abaixo:

    • Versão do LDAP: 3 (para Windows 2003 Server)
    • Authentication Server: IP ou FQDN do Servidor
    • Authentiocation Port: 389
    • User DN (user1 criado no dominio dom1.local por exemplo):
      • cn=user1,cn=Users,dc=dom1,dc=local
    • LDAP Password: Senha do usuarios definido em User DN
    • LDAP Base Domain: dc=dom1,dc=local (conforme exemplo do dominio dom1.local)
    • User DN Attribute: uid
    • Search Filter: sAMAccountName=%s

    Cache

    Na Aba Cache Mgmt podemos configurar as opções de cache do pfsense.

    Recomendações da comunidade PFSense:

    • HardDiskSize 3000 (3GB)
    • Memory: 50% da Capacidade do seu server
    • Minimum object size: 0
    • Maximum object size: opcional
    • Hard disk cache system: aufs (é uma versão alternativa de unionfs que tem como objetivo melhorar a confiabilidade e o desempenho do sistema de armazenamento)

    Access Control

    Na aba access control do Proxy Server temos a opção de configurar um controle básico de acesso definindo por exemplo, uma blascklist básica para o serviço squid

    Proxy: Configurações do SquidGuard

    Services > Proxy Filter

    Baixando BlackLists

    Com a configuração de Blacklists, através do serviço do SQUID Guard, podemos baixar listas organizadas por grupos e categorias para facilitar o bloqueio ou liberação para maquinas, usuários e grupos. Para isto devemos adicionar o seguinte endereço à BLACK LIST URL: http://www.shallalist.de/Downloads/shallalist.tar.gz

    Com esse endereço devidamente adicionado clique em Upload URL e aguarde alguns minutos.

    Obs: Lembre-se de Salvar e aplicar as alterações após a finalização do Upload

    Gerenciando BlackLists

    Você pode gerenciar sua Blacklist por grupos ou simplesmente configurar sua regra default.
    Para isso basta acessar a Aba Default em Proxy Filter e clicando em: Destination Ruleset, gerenciar as listas baixadas, liberando ou bloqueando o s acessos conforme a necessidade e política da empresa.
    A criação e gerenciamento de grupos customizados por maquinas ou usuário (caso você integre o PFSENSE ao Active Directory), pode ser feito na aba
    ACL do Proxy Filter. Lembre-se de sempre salvar as configurações realizadas, clicando em Save no fim da página e aplicar as alterações clicando em Apply na aba General settings.

    SquidGuard Logs

    Na aba Log do ProxyFilter podemos acompanhar uma lista de urls que foram bloqueadas acessando a oção Blocked.

    Outra opção interessante do Log do Sq    uid Guard esta na opção Filter Log, onde você pode acompanhar o funcionamento ou parada do serviço SquidGuard. Essa opção pode ser útil para um troubleshoting aonde podemos verificar se o serviço está iniciado se o último log gerado for uma mensagem semelhante à “squidGuard ready for requests“, ou se o serviço está parado quando também explícito na ultima entrada do Log.

    DHCP Server

    Services > DHCP Server: Para ativação do serviço basta marcar a check box Enable DHCP Server e definir o escopo para sua rede interna.

    DHCP Relay

    Services > DHCP Server: Para recebimento automatico de um IP em uma rede, a estação que faz a solicitação necessita iniciar a negociação com um broadcast na rede afim de encontrado o Servidor DHCP, porem por default a maioria dos roteadores não encaminham tráfego de broadcast. Podem haver casos em que o servidor DHCP está localizado em uma sub-rede que conecta-se a outra sub-rede através de um roteador (no nosso caso o pfsense). Nesse caso devemos configurar o DHCP Relay que se encarregará de pegar os pacotes enviados pelo cliente DHCP e encaminhará para o servidor DHCP

    NAT Port Forward

    Firewall > Port Foward:

    Port Forward

    Consiste em redirecionar uma porta específica de um nó para outro.

    • Por exemplo: O WebSite da minha empresa, configurado em um servidor na minha rede interna, precisa ser publicado para acesso externo. Para que isso seja possível devemos criar um port foward redirecionando todo trafego que chegar na porta 80 da interface wan do PFSense para a porta 80 do meu servidor web interno.

    NAT 1:1

    Destinado a ligar dois nós de redes distintas aonde todo trafego de internet (para o IP publico especificado) é direcionado a um IP especifico da nossa rede interna. Para Permitir o tráfego à partir da internet deve-se criar uma regra do firewall (rules).

    Backup / Restore

    Para importar as configurações do PFSense, Navegue por Diagnostics, Backup/Restore e importe as configurações em XML que contem as configurações desejadas. Você pode editar o arquivo XML com um bloco de notas a fim de realizar os ajustes necessários antes de realizar o import.

    ATENÇÃO!!!!!!!!!!

    No campo “Restore Area” você deve restaurar exatamente a configuração especifica que deseja, por exemplo: Configurações de Rules.. Configuração de TUDO (All)… Caso seja feito algum restore em área incorreta, isto pode fazer com que o pfsense pare de funcionar visto que serão feitas alterações em locais incorretos.

    NOME

    DATA

    HORA

    STATUS

    DESCRIÇÃO DAS ALTERAÇÕES

    Thiago Lima

    15/01/2011

    12:00

    Pendente

    Adição de VPN e Correções

    Publicado em Soluções Técnicas | 10 Comentários

    Erro Acessando o terminal Services do Windows

    Event Viewer:

    Identificação do evento: 50
    Fonte: TermDD
    Descrição: O componente de protocolo RDP X.224 detectou um erro no fluxo do protocolo e desconectou o cliente.

    Esse problema pode ocorrer se um certificado no servidor de terminal estiver corrompido.

    AVISO: O uso incorreto do Editor do Registro pode causar sérios problemas que talvez exijam a reinstalação do sistema operacional. A Microsoft não garante que os problemas resultantes do uso incorreto do Editor do Registro possam ser solucionados. O uso do Editor do Registro é de sua responsabilidade.
    Para resolver esse problema, faça um backup e remova as chaves do Registro X509 Certificate, reinicie o computador e reative o servidor de Licenciamento dos serviços de terminal. Para fazer isso, execute as seguintes etapas:

    OBSERVAÇÃO: Execute o seguinte procedimento em cada um dos servidores de terminal.
    Verifique se o backup do registro do servidor de terminal teve êxito.
    Inicie o Editor do Registro.
    Localize e clique na seguinte subchave do Registro: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\TermServices\Parameters

    Faça um backup deste registro clicando com o botão direito do mouse sobre ele e exportando.
    Se você tiver de restaurar essa subchave do Registro no futuro, clique duas vezes no arquivo exportado

    Na subchave do Registro Parâmetros, clique com o botão direito do mouse em cada um dos seguintes valores, clique em Excluir e em Sim para confirmar a exclusão:
    Certificate
    X509 Certificate
    X509 Certificate ID

    Encerre o Editor do Registro e reinicie o servidor.
    Reative o servidor Licenciamento dos serviços de terminal usando o método de conexão Telefone no Assistente para licenciamento.
    Fonte: Microsoft KB 329896

    Erro ocorrido no Windows em Ingles:

    Event ID: 50
    Source: TermDD
    Version: 5.2
    Symbolic Name: STATUS_RDP_PROTOCOL_ERROR
    Message: The RDP protocol component %2 detected an error in the protocol stream and has disconnected the client.

    Publicado em Suporte Técnico | Deixe um comentário