Search This Blog

Thursday, October 1, 2020

Windows 10 Firewall Ports

From time to time I have to open a port to do something and close it back up when I'm done. As I do this fairly often (but not often enough to memorize) I created this recipe. There is an example using Docker below.


ugh! an error! what to do?



Background Information...


How to do this by the Windows user Interface (UI)

https://www.google.com/search?q=windows+10+firewall+enable+localhost%3A80+traffic

How to do this with Powershell

https://www.google.com/search?q=powershell+TCP+Port+80+in+Windows+Firewall 

https://docs.microsoft.com/en-us/powershell/module/netsecurity/new-netfirewallrule?view=win10-ps

https://serverfault.com/questions/883266/powershell-how-open-a-windows-firewall-port


 

Powershell 


Open the port


New-NetFirewallRule -DisplayName "Allow inbound TCP port 81" -Direction inbound -LocalPort 81 -Protocol TCP -Action Allow
Name                  : {af16f2f3-3221-4191-8c5a-f44a5f60ca58}
DisplayName           : Allow inbound TCP port 81


Test (while something is listening on the port)


 Get-NetFirewallRule -Name '{af16f2f3-3221-4191-8c5a-f44a5f60ca58}'

    ** You can also see this in the Windows firewall inbound rules

$tcp = New-Object System.Net.Sockets.TcpClient
$tcp.Connect("localhost","81")
$tcp.Connected
True


Close the port back up


Remove-NetFirewallRule -Name '{af16f2f3-3221-4191-8c5a-f44a5f60ca58}'

** If you test again, you should get a failure (or, your listening port was not blocked already). And, the control panel, on refresh, will show the rule is missing.

You're done! 



Example


As a semi-practical example, Start a Docker container, test and clean up. For this to be a real example, you would have to imagine that port 81 was the blocked port. On port 80, I got stuff running there already. So, I did this on port 81.


Open the Port


New-NetFirewallRule -DisplayName "Allow inbound TCP port 81" -Direction inbound -LocalPort 81 -

Start the getting-started container


docker run -d -p 81:80 docker/getting-started
6d44c9240e688b69a212fe24e58d2302b658bfcbcee787030943b04f12cde38b

Test that the container is running and on the proper port.


docker ps
CONTAINER ID        IMAGE                    COMMAND                  CREATED             STATUS              PORTS                NAMES
6d44c9240e68        docker/getting-started   "/docker-entrypoint.…"   6 seconds ago       Up 4 seconds        0.0.0.0:81->80/tcp   goofy_elion

Test the port via Powershell


(New-Object System.Net.Sockets.TCPClient –Argument "localhost","81").Connected
True

Open page in local browser http://localhost:81

 

Hooray! It works!   : ) 


Clean up the container


docker stop 6d44c9240e68
6d44c9240e68

Remove the firewall rule by Powershell


Remove-NetFirewallRule -Name '{af16f2f3-3221-4191-8c5a-f44a5f60ca58}'



You're done again!




Thursday, September 10, 2020

SMTP Telnet

 I was working an issue with a Microsoft Edge Transport server where the content of the email was getting truncated after 6 lines. I was able to create a test and get show the delivery of the message through the Edge server to the destination mailboxes. But My test did not include the attached file of the messages that were failing. as the file was a really small csv I took up the challenge of generating the email with an attachment through a telnet session.

Steps: 

Get the csv attachment.

Generate the mime for the attachment

Modify the text of the telnet session to generate the message

Check the results.


I created a small csv using a text editor 

Company,Address,City,State,Zip

CareWorks Technologies,,Dublin,Ohio,43016

CTG,55 Public Square,Cleveland,Ohio,44113

"State Industrial Products, Inc.",3100 Hamilton Avenue,Cleveland,Ohio,44114

"Finast Supermarkets, Inc.",17000 Rockside Road,Maple Heights,Ohio,44137

Saved it as C:\Users\Lesley\Downloads\Companies.csv

Using Poswershell,

[Convert]::ToBase64String([IO.File]::ReadAllBytes('C:\Users\Lesley\Downloads\Companies.csv'))

I generated the following mime blob...
Q29tcGFueSxBZGRyZXNzLENpdHksU3RhdGUsWmlwDQpDYXJlV29ya3MgVGVjaG5vbG9naWVzLCxEdWJsaW4sT2hpbyw0MzAxNg0KQ1RHLDU1IFB1YmxpYyBTcXVhcmUsQ2xldmVsYW5kLE9oaW8sNDQx
MTMNCiJTdGF0ZSBJbmR1c3RyaWFsIFByb2R1Y3RzLCBJbmMuIiwzMTAwIEhhbWlsdG9uIEF2ZW51ZSxDbGV2ZWxhbmQsT2hpbyw0NDExNA0KIkZpbmFzdCBTdXBlcm1hcmtldHMsIEluYy4iLDE3MDAw
IFJvY2tzaWRlIFJvYWQsTWFwbGUgSGVpZ2h0cyxPaGlvLDQ0MTM3DQo=
I then added that to a telnet session like this...
telnet 10.0.0.10 25
HELO lesley.mycompany.com
MAIL FROM: <lesley@mycompany.com>
RCPT To: <lesleyphillips@yahoo.com>
DATA
subject: TLX21MLC1 : PCC LOADER JOB COMPLETED
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=border
--border
Content-Type: text/plain
 
A short list of companies I've worked at

-Lesley

--border
Content-Type: application/octet-stream
Content-Transfer-Encoding: base64;
Content-Disposition: attachment;
        filename="Companies.CSV"

Q29tcGFueSxBZGRyZXNzLENpdHksU3RhdGUsWmlwDQpDYXJlV29ya3MgVGVjaG5vbG9naWVzLCxEdWJsaW4sT2hpbyw0MzAxNg0KQ1RHLDU1IFB1YmxpYyBTcXVhcmUsQ2xldmVsYW5kLE9oaW8sNDQx
MTMNCiJTdGF0ZSBJbmR1c3RyaWFsIFByb2R1Y3RzLCBJbmMuIiwzMTAwIEhhbWlsdG9uIEF2ZW51ZSxDbGV2ZWxhbmQsT2hpbyw0NDExNA0KIkZpbmFzdCBTdXBlcm1hcmtldHMsIEluYy4iLDE3MDAw
IFJvY2tzaWRlIFJvYWQsTWFwbGUgSGVpZ2h0cyxPaGlvLDQ0MTM3DQo=
--border--
 
.
 
quit

And, the result...




Friday, July 24, 2020

Python - Has Your Password Been Pwned?

I was reading the Spring 2020 edition of 2600 and ran into this little article on page 18, titled "Has Your Password Been Pwned?" by Jan Markowski. It was originally written in Bash so I used it as a little exercise for Python.


#!/usr/bin/python

#
# Has Your Password Been Pwned?
# This code is based on published code published in 2600, Spring 2020, page 18
# by Jan Markowski, livetrue@pm.me
#


import getpass
import hashlib
import re
import sys
import urllib.request

def Check_PW_Pwanage(password):

    fGotAPassword = False
    try:
        PW_hash = hashlib.sha1(password)
        PW_hash_digest = PW_hash.hexdigest()
        PW_hash_digest_a = PW_hash_digest[0:5].upper()
        PW_hash_digest_b = PW_hash_digest[5:40].upper()
        fGotAPassword = True
    except:
        e = sys.exc_info()[0]
        print("Error: %s" % e)

    PW_occurances = 0

    if fGotAPassword == True:
        try:
            with urllib.request.urlopen("https://api.pwnedpasswords.com/range/%s" % PW_hash_digest_a) as response:
                sh1_res = response.read().decode()
            sh1_res_lines = sh1_res.split('\r\n')
            print("pwnedpasswords.com returned %s lines matching the beginning of your hash." % len(sh1_res_lines))
            regex = re.compile('^'+PW_hash_digest_b)
            idxs = [i for i, item in enumerate(sh1_res_lines) if re.search(regex, item)]
            sh1_res_line = sh1_res_lines[idxs[0]]
            PW_occurances = sh1_res_line[sh1_res_line.rfind(':')+1:]
        except:
            pass

    return PW_occurances
      
       
       
def main():
    password = getpass.getpass("Type your password and press enter: ")
    ret = int(Check_PW_Pwanage(password.encode()))
    if ret > 0:
        print('Your password has been pwned %s times!' % ret)
    else:
        print ('but, none of them matched your full hash.')
        print('Your Password is safe!')


if __name__ == "__main__": main()






Here is what it looks like when you run it...

This examples is using the password of '12345'.


And, when you use a password 'R\Ts)-f]'



Here's what is happening...

Putting in the password of '12345' generates the following hash...
'8CB2237D0679CA88DB6464EAC60DA96345513964'

Breaking that in to two parts get me a query part: '8CB22'
And, a search part: '37D0679CA88DB6464EAC60DA96345513964'

I get the results from https://api.pwnedpasswords.com/range/8cb22  (notice the query part at the end) and scan for the search part which points me to line 121. You should go to that page and look at the results.
'37D0679CA88DB6464EAC60DA96345513964:2389787'
From which I get the number of hits at the end as: 2389787



The front end of the pwned passwords web site is: https://haveibeenpwned.com/Passwords

If you are looking for good passwords, try the folks at Gibson Research. They have some good information on what makes a good password.

Lastly, 2600 is available at https://2600.com



Sunday, June 28, 2020

Python Gmail BCC SMPT

I was lacking personal examples for a Python SMTP sender and ran into the puzzle of BCC without listing the recipients in the header. It started with a discussion of timeouts of governing connections against a default receive connector on a Microsoft Edge Transport server, so there's a sleep in there too.

It's not perfect, but it is a good starting place....

#!/usr/bin/python

#
# gmail maximum message recipients in 24 hours: 500
#

import smtplib, getpass, time, sys

def Send_BCC_gmail(username, password, bcc):
    message_subject = "bcc only test"
    message_text = "this is \r\nonly \r\na test"

    flServerConnect = False
    try:
        SMTPServer = smtplib.SMTP_SSL('smtp.gmail.com', 465)
        SMTPServer.set_debuglevel(1)
        SMTPServer.login(username,password)
        flServerConnect = True
    except:
        e = sys.exc_info()[0]
        print("Error: %s" % e)

    if flServerConnect == True:
        try:
            for toaddr in bcc:
                message = "From: %s\r\n" % username \
                    + "To: %s\r\n" % toaddr \
                    + "Subject: %s\r\n" % message_subject \
                    + "\r\n" \
                    + message_text
                SMTPServer.sendmail(username, toaddr, message)
                time.sleep(.002)
        except:
            print("Error: %s" % sys.exc_info()[0])
            print("Error: %s" % sys.exc_info()[1])
            print("Error: %s" % sys.exc_info()[2].tb_lineno)
            print ('\r\nNot sent...   : (\r\n')
        finally:
            SMTPServer.quit()
            print ('Sent...   : )')

       
       
def main():
    username = input("Type your username and press enter: ")
    password = getpass.getpass("Type your password and press enter: ")
    bcc=[]
    bccpart = "."
    while bccpart > "" :
        bccpart = input("Additional Name. end list with an empty line by itself: ")
        if bccpart > "":
            bcc.append(bccpart)
    print(bcc)
    ## bcc = ['lesleyphillipsii@yahoo.com','lesleyphillipsii@gmail.com']
    Send_BCC_gmail(username, password, bcc)

if __name__ == "__main__": main()






When you run it it produces the following output...



And here is the important part of the header...