Netgate Discussion Forum
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Search
    • Register
    • Login

    Email Notification - OpenVPN Client Connect (Common Name)

    Scheduled Pinned Locked Moved OpenVPN
    138 Posts 20 Posters 40.7k Views
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • P
      PM_13 @boggie1688
      last edited by

      @boggie1688 I tried MaxMind service a while back but that was almost two years back, you may want to check it out.

      B 1 Reply Last reply Reply Quote 0
      • B
        boggie1688 @PM_13
        last edited by

        @PM_13

        So I don't know PHP at all, I barely can program hello world. However, I did manage this.

        #!/usr/local/bin/php -q
        <?php

        require_once("/etc/inc/notices.inc");
            $queryprefix = "http://api.geoiplookup.net/?query=";
            $ip= getenv('trusted_ip');
            $urlip =($queryprefix.$ip);
            $xml = file_get_contents($urlip);
        $local_connect_value = " \n user_name: " . getenv('common_name') . " \n vpn_client_ip: " . getenv('ifconfig_pool_remote_ip') ." connected from " . getenv('trusted_ip') . " on " . date('F j, Y, g:i a') . $xml;
        if ( strrchr (__FILE__ , 'disconnect') ) {
        $local_connect_value .= ", \n duration : " . round(((getenv('time_duration'))/3600),2) . "  hours, or " . round(((getenv('time_duration'))/60),2) . "  minutes, or " . getenv('time_duration') . "  seconds,\n upload from vpn-client (received) : " . round(((getenv('bytes_received'))/1048576),2) . " MB, \n download to vpn-client (send) : " . round(((getenv('bytes_sent'))/1048576),2) ." MB. \n DISCONNECTED.";
        }
            $user_remote_ip = "VPN User ". getenv('common_name')." connected from " . getenv('trusted_ip');
            send_smtp_message($local_connect_value, $user_remote_ip, 1);
        

        ?>

        It grabs the incoming ip address, and looks it up with geoiplookup.net's xml api. Then prints it into the email.

        I really would like to clean up the way it prints. given it just dumps the results from the page. But this is the end of my coding ability, pretty short huh?

        I can see the XML has tags <IP><HOST><ISP> etc etc, but I don't really know how just print the tags that I want.

        P 1 Reply Last reply Reply Quote 0
        • P
          PM_13 @boggie1688
          last edited by

          @boggie1688 said in Email Notification - OpenVPN Client Connect (Common Name):

          PM_13

          @serbus helped me with php syntax to add additional line of text in the email notification (whether vpn client is connecting or disconnecting in a particular event). I don't know php either but John's recommendations were spot on. John thanks again!!

          1 Reply Last reply Reply Quote 0
          • S
            serbus
            last edited by

            Hello!

            Once you have your $xml response you could try something like:

            $country = 'Unknown';
            if (preg_match ('/<countryname>(.*?)<\/countryname>/', $xml, $match))
               {
               $country = $match [1];
               }
            

            John

            Lex parsimoniae

            B 1 Reply Last reply Reply Quote 1
            • GertjanG
              Gertjan
              last edited by

              To all : Test your VPN notification first !!

              Go outside, de activate the Wifi, activate the VPN , take a big walk, swim, drive or best : take a plane.

              When you get back, you'll be in for a surprise.
              This surprise includes :
              The huge number of mails you received.
              Maybe also the mail from your mail host that states that they detect a spam bomb attack .... and that they stopped treating further mails from this 'source'.
              You used another outside service : Leave your chair, take a big walk, swim, drive or best : take a plane. ? Fine : they will blacklist you, as their server has to be protected.
              Etc.

              It's not only about knowing what PHP is : that's an easy one : you wana drive that car ? => Go for the license (and insurance, maintenance, etc)

              I'll leave this question open for now : Why did you receive hundreds, if not thousands of nearly 'notification' identical mails ?

              The code given as an example above has to be .... worked on.
              For example : the call to "geoiplookup.net" : it should be used wisely :
              When a the VPN connect script is called, the IP obtained should be compared with the content of a file. this file contains all the IPs found in VPN connect messages.
              If the IP is found : do nothing, as the IP is know.
              The IP is not in the file : have it looked up, and send the mail.

              Now you will receive far less mails, and no one will complain.

              And I have a question : Normally, VPN access is given to people that you some how trust.
              Why GEO locate them ?
              Your kids ?
              And then there is the eternal discussion that GEOIP data is quiet useless.
              There are no more free IPv4s, it became a rare resource. The last blocks are sold often, broken up, sold again, from anywhere to anywhere. Their actual location isn't really known any more.
              And take Apple and IBM for example : back then, they bought and entire /8 (or close to that). And all their IP's are in (example) Redmond, although used world wide.
              With IPv6 thinks get better : You can forget the notion of GEOIP as no one can build the database that can hold all the details : there are not enough resources on this planet left to do so. Maintaining and giving access to this database will be even more difficult.

              No "help me" PM's please. Use the forum, the community will thank you.
              Edit : and where are the logs ??

              noplanN B 2 Replies Last reply Reply Quote 1
              • noplanN
                noplan @Gertjan
                last edited by

                WORD !

                1 Reply Last reply Reply Quote 0
                • B
                  boggie1688 @serbus
                  last edited by

                  @serbus Thank you for this, this would have taken me ages to figure out. Specifically the function preg_match. I was googling around and though perhaps XPATH was the right function.

                  1 Reply Last reply Reply Quote 0
                  • B
                    boggie1688 @Gertjan
                    last edited by

                    @gertjan

                    I tested my VPN while moving in a car, and I see what you are saying about multiple emails coming through. As my cell reception dropped and reconnected, the notify and disconnect scripts would run.

                    If I'm honest, the VPN isn't used in a setting with multiple users. There is only one, who isn't very tech savy. Additionally they will only be using it on a desktop. I don't anticipate a crazy amount of emails as I doubt they will login more than once a week.

                    The geo data is just to confirm that my one user is indeed my who I expect it to be. IE coming from roughly the geographical area that I expect. Probably a really weak way to check, but as you can see I'm not that tech savvy.

                    P 1 Reply Last reply Reply Quote 0
                    • P
                      PM_13 @boggie1688
                      last edited by

                      @boggie1688
                      "If I'm honest, the VPN isn't used in a setting with multiple users."

                      VPN are more widely used on larger networks but it is not typical for admins to set up receiving emails for each VPN user connect/disconnect session.

                      The reason being - a VPN user by definition is a trusted user. In addition to having credentials (user name and password), a VPN user also needs a signed certificate.

                      noplanN 1 Reply Last reply Reply Quote 0
                      • noplanN
                        noplan @PM_13
                        last edited by

                        @pm_13 said in Email Notification - OpenVPN Client Connect (Common Name):

                        is not typical for admins to set up receiving emails for each VPN user connect/disconnect session

                        wrong !
                        it was not used to be before COVID

                        now a ton of admins use
                        the exact output of Post 26 from this topic

                        https://forum.netgate.com/topic/151351/email-notification-openvpn-client-connect-common-name/26

                        to get a view of what is goin on in HomeOffice and why, not to mention the information when a
                        contractor is entering the network as a trusted user.

                        dont get me wrong but there is a point of gettin notification via mail
                        but there is no point as @Gertjan mentioned earlier in geoIPlookUps

                        btw it would be nice if someone feels free to write the information from the mail
                        in a csv file to send it once a week via cron and mail to the admin stuff
                        so you get a nice n sweet reporting of your VPN users (it's still on my toDo list but my coding skill isnt good enough ;)

                        brNP

                        1 Reply Last reply Reply Quote 0
                        • bingo600B
                          bingo600
                          last edited by bingo600

                          Fun with ovpn connect/disconnect scripts.

                          Using ssh directly to the firewall , select 8 for shell.

                          NOTE: Don't do this while working via a VPN server that uses these scripts
                          If you FSCK' up the php connect script , and the script returns an error. OpenVPN will reject new connects.

                          I made a /root/ovpn-connect.sh file , and pasted this into it.

                          #!/usr/local/bin/php -q
                          <?php
                          	require_once("/etc/inc/notices.inc");
                          	$local_connect_value = __FILE__ . " \n user_name: " . getenv('common_name') . " \n vpn_client_ip: " . getenv('ifconfig_pool_remote_ip') ." connected from " . getenv('trusted_ip') . " on " . date('F j, Y, g:i a');
                          	if ( strpos (__FILE__ , 'ovpn-disconnect') !== false ) {
                          	$local_connect_value .= ", \n duration : " . round(((getenv('time_duration'))/3600),2) . "  hours, or " . round(((getenv('time_duration'))/60),2) . "  minutes, or " . getenv('time_duration') . "  seconds,\n upload from vpn-client (received) : " . round(((getenv('bytes_received'))/1048576),2) . " MB, \n download to vpn-client (send) : " . round(((getenv('bytes_sent'))/1048576),2) ." MB. \n DISCONNECTED.";
                          	}
                          	notify_all_remote($local_connect_value);
                          ?>
                          

                          Made it executeble:

                          chmod +x /root/ovpn-connect.sh
                          

                          Copied it to /root/ovpn-disconnect.sh

                          cp /root/ovpn-connect.sh  /root/ovpn-disconnect.sh
                          

                          Activated it in the OpenVPN Server -> Advanced Configuration

                          1bbff893-12ff-46a1-aaf2-02a439161c6f-image.png

                          Done !

                          Edit:
                          Im my e-mail client (thunderbird) i made a filter that triggers :
                          If From contains : My Notifications -> From e-mail address
                          And Body Contains : /root/ovpn
                          Move mail to : Ovpn e-mail Connect folder

                          If you find my answer useful - Please give the post a šŸ‘ - "thumbs up"

                          pfSense+ 23.05.1 (ZFS)

                          QOTOM-Q355G4 Quad Lan.
                          CPUĀ  : Core i5 5250U, Ram : 8GB Kingston DDR3LV 1600
                          LANĀ  : 4 x Intel 211, DiskĀ  : 240G SAMSUNG MZ7L3240HCHQ SSD

                          1 Reply Last reply Reply Quote 1
                          • bingo600B
                            bingo600
                            last edited by bingo600

                            What i learned , and did different from the above solutions:

                            1:
                            DON'T symlink the disconnect script to the connect script.
                            As nice (and logical) as this seems to be , your disconnect section won't work.
                            As FILE will resolve symlinks too , and you'll end up with the connect filename for both connect & disconnect.

                            From : https://www.php.net/manual/en/language.constants.predefined.php

                            __FILE__ 	The full path and filename of the file with symlinks resolved. If used inside an include, the name of the included file is returned.
                            

                            I have included the the passed FILE variable in the e-mail body to verify that.

                            2:
                            The use of strrchr funct. here , seems bogus to me.

                            if ( strrchr (__FILE__ , 'disconnect') )
                            

                            From : https://www.php.net/manual/en/function.strrchr.php
                            strrchr — Find the last occurrence of a character in a string

                            I want a full string match , not a character match.

                            I replaced that with strpos()
                            Watch out .. the !== false is not a kludge.

                            if ( strpos (__FILE__ , 'ovpn-disconnect') !== false ) 
                            

                            I could have used different connect & disconnect files , and skipped the file match of "disconnect".
                            But the challenge of detecting & resolve the FILE variable had to be overcomed 😊

                            So even though they are two separate files , the contents are equal.

                            Hope it's usable for someone

                            /Bingo

                            If you find my answer useful - Please give the post a šŸ‘ - "thumbs up"

                            pfSense+ 23.05.1 (ZFS)

                            QOTOM-Q355G4 Quad Lan.
                            CPUĀ  : Core i5 5250U, Ram : 8GB Kingston DDR3LV 1600
                            LANĀ  : 4 x Intel 211, DiskĀ  : 240G SAMSUNG MZ7L3240HCHQ SSD

                            GertjanG 1 Reply Last reply Reply Quote 0
                            • GertjanG
                              Gertjan @bingo600
                              last edited by Gertjan

                              @bingo600 said in Email Notification - OpenVPN Client Connect (Common Name):

                              DON'T symlink the disconnect script to the connect script.

                              That breaks the script.

                              Because this :

                              if ( strrchr (__FILE__ , 'disconnect') )
                              

                              The "disconnect.sh" should contain the word "disconnect" so it knows it's called on a disconnect event.

                              "strrchr " means the word "disconnect" should exist in the file name.

                              You can of course use seperate files for both events.
                              Or choose other file names, but in that case, the _FILE search has to be adapted, if needed.

                              No "help me" PM's please. Use the forum, the community will thank you.
                              Edit : and where are the logs ??

                              bingo600B 2 Replies Last reply Reply Quote 0
                              • bingo600B
                                bingo600 @Gertjan
                                last edited by bingo600

                                @gertjan
                                Nope ...

                                From : https://www.php.net/manual/en/function.strrchr.php
                                strrchr — Find the last occurrence of a character in a string

                                I'we used that functions tonzz of times in "C".

                                Edit: Re: symlink
                                If you prepend the FILE . as below , you'll see how it's resolved in your e-mail body.
                                connect vs disconnect.

                                $local_connect_value = __FILE__ . " \n user_name: " 
                                

                                If you find my answer useful - Please give the post a šŸ‘ - "thumbs up"

                                pfSense+ 23.05.1 (ZFS)

                                QOTOM-Q355G4 Quad Lan.
                                CPUĀ  : Core i5 5250U, Ram : 8GB Kingston DDR3LV 1600
                                LANĀ  : 4 x Intel 211, DiskĀ  : 240G SAMSUNG MZ7L3240HCHQ SSD

                                1 Reply Last reply Reply Quote 0
                                • bingo600B
                                  bingo600 @Gertjan
                                  last edited by

                                  @gertjan said in Email Notification - OpenVPN Client Connect (Common Name):

                                  You can of course use seperate files for both events.
                                  Or choose other file names, but in that case, the _FILE search has to be adapted, if needed.

                                  I totally agree here ... Match the __FILE with the filename used for disconnect

                                  /Bingo

                                  If you find my answer useful - Please give the post a šŸ‘ - "thumbs up"

                                  pfSense+ 23.05.1 (ZFS)

                                  QOTOM-Q355G4 Quad Lan.
                                  CPUĀ  : Core i5 5250U, Ram : 8GB Kingston DDR3LV 1600
                                  LANĀ  : 4 x Intel 211, DiskĀ  : 240G SAMSUNG MZ7L3240HCHQ SSD

                                  noplanN 1 Reply Last reply Reply Quote 0
                                  • noplanN
                                    noplan @bingo600
                                    last edited by noplan

                                    @bingo600

                                    and what does the output look like ?

                                    something like that, and this txt file will
                                    a) be mailed to admin via cron each Sunday morining 09:00
                                    b) will be cleared each Sunday morning 09:05 after file was mailed
                                    (storing a backup of this file would be pretty cool ) just in case the mail isnt workin ;)

                                    54c343a9-5df0-4e73-a80d-b8ec8884330a-grafik.png

                                    Then the rest is up to som fancy XLS reporting stuff ;)
                                    550a064b-dc72-467b-9ee7-88cff26905c5-grafik.png

                                    e65129ca-8903-4b6f-809e-bd6a45dad0ac-grafik.png

                                    helps you out comparing the billed hours on your system with the real hours they spend on it.

                                    bingo600B ArmstrongA 2 Replies Last reply Reply Quote 0
                                    • bingo600B
                                      bingo600 @noplan
                                      last edited by bingo600

                                      @noplan said in Email Notification - OpenVPN Client Connect (Common Name):

                                      @bingo600

                                      and what does the output look like ?

                                      I just added the called filename to the output.
                                      And fixed the "stringcompare"

                                      Rest is the same.

                                      Credit for the script & decoding the env vars , should go to the original authors.

                                      /Bingo

                                      If you find my answer useful - Please give the post a šŸ‘ - "thumbs up"

                                      pfSense+ 23.05.1 (ZFS)

                                      QOTOM-Q355G4 Quad Lan.
                                      CPUĀ  : Core i5 5250U, Ram : 8GB Kingston DDR3LV 1600
                                      LANĀ  : 4 x Intel 211, DiskĀ  : 240G SAMSUNG MZ7L3240HCHQ SSD

                                      1 Reply Last reply Reply Quote 0
                                      • ArmstrongA
                                        Armstrong @noplan
                                        last edited by Armstrong

                                        This post is deleted!
                                        1 Reply Last reply Reply Quote 0
                                        • N
                                          newnub
                                          last edited by

                                          Apparently there is a bug with FreeRADIUS and Assigned IPv4 Address for your OpenVPN if you use the email script by adding it to:
                                          OpenVPN Server -> Advanced Configuration > Custom Options

                                          If you invoke script from Custom Options under OpenVPN Server -> Advanced Configuration, then FreeRADIUS will no longer assign your static IPv4 for OpenVPN. I don't know how to get around this but just FYI if suddenly your OpenVPN IP is no longer your defined static address.

                                          1 Reply Last reply Reply Quote 0
                                          • S
                                            Stewart
                                            last edited by

                                            I know this thread is kinda old but I don't know that starting a new topic is the best course of action. I'm trying to implement this but there is a delay of a couple of minutes on the disconnect script and the connect script won't log if it's waiting for the disconnect script.

                                            In the Advanced Configuration -> Custom Options I have:
                                            4903d91c-ea9c-4230-aabb-06cf015d6a80-image.png

                                            I've modified the scripts to both send an email and output to a log file when run. When a client connects, I see the log file updated immediately and the email comes very quickly. When a client disconnects it takes 2 -2.5 minutes before the log file is updated and the email is sent. During that window of time if I reconnect it doesn't log or send an email. There is very little difference in the two scripts at this point as I try to narrow down the issue.

                                            Does anyone have any idea what this delay is and what's going on?

                                            GertjanG 1 Reply Last reply Reply Quote 0
                                            • First post
                                              Last post
                                            Copyright 2025 Rubicon Communications LLC (Netgate). All rights reserved.