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 41.4k 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
      psp @Stewart
      last edited by psp

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

      @psp

      Have you had a chance to test out the scripts? Any feedback?

      Sure! I only changed the timestamp to use H24 notation. No issues so far:

      2021-10-12_225319.png

      1 Reply Last reply Reply Quote 0
      • W
        WVA @Stewart
        last edited by

        @stewart Thank you for this script, works like a charm !

        Regarding the log file limiting you mention, I can't seem to find this in your code ?
        I think it would be good to set a maximum filesize (and/or even truncate files) ? What would be best practice in implementing this ?

        And what if one has multiple OpenVPN servers, would grouping by server be possible ? Maybe in the same manner as usernames are being propped in an array and end user can choose from by dropdown list ?

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

          Sorry, I didn't see a message that someone had posted in here.

          Regarding the log file limiting you mention, I can't seem to find this in your code ?
          I think it would be good to set a maximum filesize (and/or even truncate files) ? What would be best practice in implementing this ?

          Very good question and one I don't have an answer to. I haven't really looked at it other than to know it needs to be done, otherwise the file will just continue to grow. At that point, it may be a cron job but I'd assume it would be need to be handled like the rest of the system logs and I have no idea how to do that.

          I can tell you that the site I developed this on has several VPN users that connect and disconnect frequently throughout the day. Their /var/log/OpenVPN_Users.log file appears to be growing at about 10K / week or roughly 1 MB every other year. Over the expected 7 year lifecycle I suppose it will only be about 3.5MB - 4MB in size. Hardly a concern for this system but for systems with many users constantly going in and out it could get larger, faster.

          And what if one has multiple OpenVPN servers, would grouping by server be possible ? Maybe in the same manner as usernames are being propped in an array and end user can choose from by dropdown list ?

          Another good question. I'm not sure if that is a variable that can be extracted. Since the script files are unique to the server you could theoretically just rename the connect.sh, disconnect.sh, OpenVPN_Users.log, and vpn_openvpn_userlogging.php files and then update the pointers in the files to the new locations. That would cause you to have a second page that tracks the second server. Off the top of my head it seems fairly simple for you to do manually, but not automatically by the script if you can't pull the name of the server from the $local_connect_value.

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

            I had an issue with a user where the case changed between login and logout. No idea why but it created some oddities in the logs so I've updated the connect.sh and disconnect.sh files with a minor strtolower change.

            connect.sh

            #!/usr/local/bin/php -q
            
            <?php
            //      Gather Info
                    $date = date('Y-m-d');
                    $time = date('g:i a');
                    require_once("/etc/inc/notices.inc");
            
            //      Compile Info String to Send
                    $local_connect_value = "USER: " . strtolower(getenv('common_name')) . "; CONNECTED; " . $date . "; at " .$time . "; IP CONNECTED FROM: " . getenv('trusted_ip') . " INTERNAL IP ASSIGNED: " . getenv('ifconfig_pool_remote_ip') . "\n";
            
            //      Send Email Notification of Event
            //      notify_all_remote($local_connect_value);
            
            $filename="/var/log/OpenVPN_Users.log";
            $fp = fopen($filename, 'a');
            fwrite($fp,$local_connect_value);
            fclose($fp);
            
            ?>
            

            disconnect.sh

            #!/usr/local/bin/php -q
            <?php
            //      Gather Info
                    require_once("/etc/inc/notices.inc");
                    $date = date('Y-m-d');
                    $time = date('g:i a');
                    $durationSeconds = getenv('time_duration');
            
            //      Function to calculate time from seconds to human readable format
                    function seconds2human($ss) {
                            $s = $ss%60;
                            $m = floor(($ss%3600)/60);
                            $h = floor(($ss%86400)/3600);
                            $d = floor(($ss%2592000)/86400);
                            $M = floor($ss/2592000);
                            return "$d days $h hours $m minutes $s seconds";
                    }
            
            //      Compile Info String to Send
                    $local_connect_value .= "USER: " . strtolower(getenv('common_name')) . "; DISCONNECTED; " . $date . "; at " . $time . "; DURATION: " . $durationSeconds . " seconds or " . seconds2human($durationSeconds) . " DATA UPLOADED (RECEIVED): ". round(((getenv('bytes_received'))/1048576),2) . " MB DATA DOWNLOADED (SENT): " . round(((getenv('bytes_sent'))/1048576),2) ." MB\n";
            
            //      Send Email Notification of Event
            //      notify_all_remote($local_connect_value);
            
            
            //      Output to Log File
                    $filename="/var/log/OpenVPN_Users.log";
                    $fp = fopen($filename, 'a');
                    fwrite($fp,$local_connect_value);
                    fclose($fp);
            
            ?>
            
            1 Reply Last reply Reply Quote 1
            • johnpozJ johnpoz referenced this topic on
            • johnpozJ johnpoz referenced this topic on
            • GertjanG Gertjan referenced this topic on
            • GertjanG Gertjan referenced this topic on
            • S
              Stewart
              last edited by

              It's been working in our environment but there's no real integration into the GUI and I need to manually type in the page each time. Is there a way to integrate it or get it integrated? I know if I go mucking around in the interface it's just going to get overwritten with the next update.

              Also, 4 months later and the log file is roughly 169K in size so it will grow to about .5MB after a year, depending on usage. That keeps it in line with my estimate of 3.5MB-4MB after the 7 year lifecycle.

              1 Reply Last reply Reply Quote 0
              • A
                aasimenator
                last edited by aasimenator

                Our OpenVPN is using Radius Server synced with Windows Active Directory Domain server for logon. Is there any way this email notification will work in such a scenario?

                because currently we only get the following information, username field is blank
                c8d61c03-c13c-4025-97c4-3894b1a855b7-image.png

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

                  @aasimenator

                  "user_name" ?
                  "vpn_client_ip" ?

                  Show the script you are using.

                  See the example "connect.sh" file above.
                  The scripts file is called with a bunch of pre defined environment variable set.
                  Ask Google how to print all the environment variables when it starts. Normally, if known, a variable like "common_name" should contain the name.

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

                  A 1 Reply Last reply Reply Quote 0
                  • A
                    aasimenator @Gertjan
                    last edited by

                    @gertjan

                    my connect.sh is exactly what you mentioned in the post above 1646309481558

                    i just changed the name from notify.sh to connect.sh and left disconnect.sh as is.

                    /root/connect.sh file:

                    #!/usr/local/bin/php -q
                    <?php
                    	require_once("/etc/inc/notices.inc");
                    	$local_connect_value = " user_name: " . getenv('common_name') . " vpn_client_ip: " . getenv('ifconfig_pool_remote_ip') . " on " . date('F j, Y, g:i a');
                    	log_error("About to send a mail : Connecting");
                    	notify_all_remote($local_connect_value);
                    ?>
                    

                    /root/disconnect.sh file:

                    #!/usr/local/bin/php -q
                    <?php
                    	require_once("/etc/inc/notices.inc");
                    	$local_connect_value .= ", during : " . getenv('time_duration') . " seconds, received : " . getenv('bytes_received') . " bytes, send : " . getenv('bytes_sent') ." bytes. DISCONNRECTED.";
                    	log_error("About to send a mail : Disconnecting");
                    	notify_all_remote($local_connect_value);
                    ?>
                    
                    GertjanG 1 Reply Last reply Reply Quote 0
                    • A aasimenator referenced this topic on
                    • GertjanG
                      Gertjan @aasimenator
                      last edited by Gertjan

                      @aasimenator

                      Looks ok.
                      What happens - I think - is that when LDAP is used, the common_name environment isn't set as it isn't known. So getenv('common_name') return 'nothing' or an empty string.

                      I've never used LDAP, so I can't be sure.

                      edit : again : have all the env variables printed, and see what's in there.

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

                      A 1 Reply Last reply Reply Quote 0
                      • A
                        aasimenator @Gertjan
                        last edited by

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

                        have all the env variables printed, and see what's in there.

                        How do you do that?

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

                          @aasimenator

                          PHP getenv()

                          I created a small test file /root/test.php :

                          #!/usr/local/bin/php -q
                          <?php
                          print_r(getenv(), $output);
                          echo $output;
                          ?>
                          

                          Now (made it executable) :
                          ./test.php

                          works for me.

                          Array
                          (
                              [SSH_CLIENT] => 192.168.1.2 59841 22
                              [LOGNAME] => root
                              [MAIL] => /var/mail/root
                              [PATH] => /sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin:/root/bin
                              [PWD] => /root
                              [TERM] => xterm
                              [SSH_TTY] => /dev/pts/0
                              [USER] => root
                              [HOME] => /root
                              [SSH_CONNECTION] => 192.168.1.2 59841 192.168.1.1 22
                              [SHELL] => /bin/sh
                              [BLOCKSIZE] => K
                              [HOSTTYPE] => FreeBSD
                              [VENDOR] => amd
                              [OSTYPE] => FreeBSD
                              [MACHTYPE] => x86_64
                              [SHLVL] => 1
                              [GROUP] => wheel
                              [HOST] => pfsense.munetwork.net
                              [REMOTEHOST] => 192.168.1.2
                              [CLICOLOR] => true
                              [LSCOLORS] => exfxcxdxbxegedabagacad
                          )
                          

                          This was just a test - my script file

                          Add $output to the $local_connect_value string, and have it mailed to you.
                          Or log it :

                          #!/usr/local/bin/php -q
                          <?php
                          	require_once("/etc/inc/notices.inc");
                          	$local_connect_value = " user_name: " . getenv('common_name') . " vpn_client_ip: " . getenv('ifconfig_pool_remote_ip') . " on " . date('F j, Y, g:i a');
                          	print_r(getenv(), $output);
                          	log_error($output);
                          	log_error("About to send a mail : Connecting");
                          	notify_all_remote($local_connect_value);
                          ?>
                          

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

                          A 1 Reply Last reply Reply Quote 0
                          • A
                            aasimenator @Gertjan
                            last edited by aasimenator

                            @gertjan
                            after changing the connect.sh file to your updated example i am not getting any new information in the email.
                            e7cfb0bf-01c2-46d0-b331-e8c9f19897eb-image.png

                            And this is what i see in the status of the VPN connection
                            0ddfcd78-eb88-43ef-904b-d8c61ac1e4e3-image.png

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

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

                              i am not getting any new information in the email.

                              Because the variable $output was send to the local log, the most important screens in pfSense are the logs.
                              At the same place you will also have this line : Status > System Logs > System > General

                              About to send a mail : Connecting
                              

                              That's what

                              log_error("About to send a mail : Connecting");
                              

                              is all about.
                              It logs an 'error' which is actually just an incontinent text message.to the logs.

                              Same thing for the variables your looking for : check the logs.

                              The output string $output can be added to $local_connect_value string, why not.

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

                              A 1 Reply Last reply Reply Quote 0
                              • A
                                aasimenator @Gertjan
                                last edited by

                                @gertjan 1f7f56cc-75e1-422a-8381-24b308ac9963-image.png
                                No information in the logs near the Connecting message

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

                                  @aasimenator

                                  There it is :

                                  46baf718-5061-45b7-8cb3-a46ab61d85b4-image.png

                                  Never the less : nothing.
                                  Unbelievable but I had to Google it up.

                                  Change

                                  	print_r(getenv(), $output);
                                  

                                  to

                                          $output = print_r(getenv(), true);
                                  

                                  I've tested it.
                                  It shows a lot of info.
                                  One of them is the :

                                  08b356fe-95fe-46ac-bfc2-803b5204bdc8-image.png

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

                                  A 1 Reply Last reply Reply Quote 0
                                  • A
                                    aasimenator @Gertjan
                                    last edited by

                                    @gertjan Thank you so much for that. It seems to have worked and I could get all the information needed to get the data out in an email.

                                    The only difference when using LDAP / Radius server in the getenv was changing ('common_name') to ('username')

                                    In hindsight, I think maybe having the following option enabled in the OpenVPN config might have done the trick.
                                    35dc686c-6483-4f73-879f-a23000a8884d-image.png

                                    I do have a follow-up question, is there any way we can format the email better? e.g. newlines instead of everything in 1 line, I already tried \n or \r\n and even /n but none of them seem to work.

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

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

                                      is there any way we can format the email better?

                                      The small script file, see above, used by OpenVPN on a 'connect' event is written using PHP.
                                      You can also use bash / sh / python / lua / or any high level copiled C or whatever ......

                                      Use any language you like.

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

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

                                        Anyone's scripts just stop working?

                                        I noticed sometime after August these scripts stopped working on my pfsense box. Not sure what is going on.

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

                                          @boggie1688
                                          There is a boatload of info present - above, to debug.
                                          Can you say more as :

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

                                          scripts stopped

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

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

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

                                            @boggie1688
                                            There is a boatload of info present - above, to debug.
                                            Can you say more as :

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

                                            scripts stopped

                                            Not sure where to start.

                                            I've been using the same script for year or two and suddenly I stopped getting emails when I connect or disconnect. I haven't changed the scripts so I'm not entirely sure what would cause the lack of emails.

                                            Given I changed nothing, I wondering if anyone experienced the same.

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