Tuesday, August 5, 2014

Syntactical Conflict

Syntactical conflicts are never fun but it happens and we have to deal with it. I wanted to open firewall ports on servers, in this case, hosting Doom. To manage my server, I am want to use Chef. An issue I ran across was that my command, in Snippet 1, would work when run from PowerShell but not in Chef.

Snippet 1
netsh advfirewall firewall add rule dir=in name="Doom" program=%systemroot%\system32\svchost.exe service=doom action=allow protocol=TCP localport=666

It did not work when the command was run using Chef on the same Windows Server. Snippet 2 shows the code that did not work when run in Chef after copying directly into an execute block.

Snippet 2
# Firewall rule addition to enable a firewall port
execute "Doom TCP 666" do
  command "netsh advfirewall firewall add rule dir=in name="Doom" program=%systemroot%\system32\svchost.exe service=doom action=allow protocol=TCP localport=666"
end

The issue can be seen more clearly in the error, seen below in Figure 1.

Figure 1

As we can see, the value of "program" and "name" are distorted. We need to ensure that we are using literal " and literal \. The fix to this problem is simple if we add an additional \ in front of the characters that we want to take literally. The fix is seen in Snippet 3.

Snippet 3
# Firewall rule addition to enable a firewall port
execute "Doom TCP 666" do
  command "netsh advfirewall firewall add rule dir=in name=\"Doom\" program=\"%systemroot%\\system32\\svchost.exe\" service=doom action=allow protocol=TCP localport=666"
end

Our path will no longer be distorted and our name will be accepted. This can apply directly to the firewall port problem or more broadly in scenarios where Chef will be running PowerShell with the execute command.