commit 235c284d30fb8a73bc2f06ce15407c280aed9941 Author: arahman Date: Thu Apr 24 07:47:49 2025 +0530 Added Radius Config diff --git a/README.md b/README.md new file mode 100644 index 0000000..b756526 --- /dev/null +++ b/README.md @@ -0,0 +1,92 @@ +# radius + + + +## Getting started + +To make it easy for you to get started with GitLab, here's a list of recommended next steps. + +Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! + +## Add your files + +- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files +- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: + +``` +cd existing_repo +git remote add origin https://gitlablex.ibasis.net/simfony/adrian_transition/qa-ops/radius.git +git branch -M production +git push -uf origin production +``` + +## Integrate with your tools + +- [ ] [Set up project integrations](https://gitlablex.ibasis.net/simfony/adrian_transition/qa-ops/radius/-/settings/integrations) + +## Collaborate with your team + +- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) +- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) +- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) +- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) +- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) + +## Test and Deploy + +Use the built-in continuous integration in GitLab. + +- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) +- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) +- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) +- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) +- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) + +*** + +# Editing this README + +When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template. + +## Suggestions for a good README +Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. + +## Name +Choose a self-explaining name for your project. + +## Description +Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. + +## Badges +On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. + +## Visuals +Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. + +## Installation +Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. + +## Usage +Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. + +## Support +Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. + +## Roadmap +If you have ideas for releases in the future, it is a good idea to list them in the README. + +## Contributing +State if you are open to contributions and what your requirements are for accepting them. + +For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. + +You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. + +## Authors and acknowledgment +Show your appreciation to those who have contributed to the project. + +## License +For open source projects, say how it is licensed. + +## Project status +If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. diff --git a/clients.conf b/clients.conf new file mode 100644 index 0000000..f6baad6 --- /dev/null +++ b/clients.conf @@ -0,0 +1,389 @@ +# -*- text -*- +## +## clients.conf -- client configuration directives +## +## $Id: 76b300d3c55f1c5c052289b76bf28ac3a370bbb2 $ + +####################################################################### +# +# Define RADIUS clients (usually a NAS, Access Point, etc.). + +# +# Defines a RADIUS client. +# +# '127.0.0.1' is another name for 'localhost'. It is enabled by default, +# to allow testing of the server after an initial installation. If you +# are not going to be permitting RADIUS queries from localhost, we suggest +# that you delete, or comment out, this entry. +# +# + +# +# Each client has a "short name" that is used to distinguish it from +# other clients. +# +# In version 1.x, the string after the word "client" was the IP +# address of the client. In 2.0, the IP address is configured via +# the "ipaddr" or "ipv6addr" fields. For compatibility, the 1.x +# format is still accepted. +# +client localhost { + # Only *one* of ipaddr, ipv4addr, ipv6addr may be specified for + # a client. + # + # ipaddr will accept IPv4 or IPv6 addresses with optional CIDR + # notation '/' to specify ranges. + # + # ipaddr will accept domain names e.g. example.org resolving + # them via DNS. + # + # If both A and AAAA records are found, A records will be + # used in preference to AAAA. + ipaddr = 127.0.0.1 + + # Same as ipaddr but allows v4 addresses only. Requires A + # record for domain names. +# ipv4addr = * # any. 127.0.0.1 == localhost + + # Same as ipaddr but allows v6 addresses only. Requires AAAA + # record for domain names. +# ipv6addr = :: # any. ::1 == localhost + + # + # A note on DNS: We STRONGLY recommend using IP addresses + # rather than host names. Using host names means that the + # server will do DNS lookups when it starts, making it + # dependent on DNS. i.e. If anything goes wrong with DNS, + # the server won't start! + # + # The server also looks up the IP address from DNS once, and + # only once, when it starts. If the DNS record is later + # updated, the server WILL NOT see that update. + # + + # + # The transport protocol. + # + # If unspecified, defaults to "udp", which is the traditional + # RADIUS transport. It may also be "tcp", in which case the + # server will accept connections from this client ONLY over TCP. + # + proto = * + + # + # The shared secret use to "encrypt" and "sign" packets between + # the NAS and FreeRADIUS. You MUST change this secret from the + # default, otherwise it's not a secret any more! + # + # The secret can be any string, up to 8k characters in length. + # + # Control codes can be entered vi octal encoding, + # e.g. "\101\102" == "AB" + # Quotation marks can be entered by escaping them, + # e.g. "foo\"bar" + # + # A note on security: The security of the RADIUS protocol + # depends COMPLETELY on this secret! We recommend using a + # shared secret that is composed of: + # + # upper case letters + # lower case letters + # numbers + # + # And is at LEAST 8 characters long, preferably 16 characters in + # length. The secret MUST be random, and should not be words, + # phrase, or anything else that is recognisable. + # + # The default secret below is only for testing, and should + # not be used in any real environment. + # + secret = testing123 + + # + # Old-style clients do not send a Message-Authenticator + # in an Access-Request. RFC 5080 suggests that all clients + # SHOULD include it in an Access-Request. The configuration + # item below allows the server to require it. If a client + # is required to include a Message-Authenticator and it does + # not, then the packet will be silently discarded. + # + # allowed values: yes, no + require_message_authenticator = no + + # + # The short name is used as an alias for the fully qualified + # domain name, or the IP address. + # + # It is accepted for compatibility with 1.x, but it is no + # longer necessary in >= 2.0 + # +# shortname = localhost + + # + # the following three fields are optional, but may be used by + # checkrad.pl for simultaneous use checks + # + + # + # The nas_type tells 'checkrad.pl' which NAS-specific method to + # use to query the NAS for simultaneous use. + # + # Permitted NAS types are: + # + # cisco + # computone + # livingston + # juniper + # max40xx + # multitech + # netserver + # pathras + # patton + # portslave + # tc + # usrhiper + # other # for all other types + + # + nas_type = other # localhost isn't usually a NAS... + + # + # The following two configurations are for future use. + # The 'naspasswd' file is currently used to store the NAS + # login name and password, which is used by checkrad.pl + # when querying the NAS for simultaneous use. + # +# login = !root +# password = someadminpas + + # + # As of 2.0, clients can also be tied to a virtual server. + # This is done by setting the "virtual_server" configuration + # item, as in the example below. + # +# virtual_server = home1 + + # + # A pointer to the "home_server_pool" OR a "home_server" + # section that contains the CoA configuration for this + # client. For an example of a coa home server or pool, + # see raddb/sites-available/originate-coa +# coa_server = coa + + # + # Response window for proxied packets. If non-zero, + # then the lower of (home, client) response_window + # will be used. + # + # i.e. it can be used to lower the response_window + # packets from one client to a home server. It cannot + # be used to raise the response_window. + # +# response_window = 10.0 + + # + # Connection limiting for clients using "proto = tcp". + # + # This section is ignored for clients sending UDP traffic + # + limit { + # + # Limit the number of simultaneous TCP connections from a client + # + # The default is 16. + # Setting this to 0 means "no limit" + max_connections = 16 + + # The per-socket "max_requests" option does not exist. + + # + # The lifetime, in seconds, of a TCP connection. After + # this lifetime, the connection will be closed. + # + # Setting this to 0 means "forever". + lifetime = 0 + + # + # The idle timeout, in seconds, of a TCP connection. + # If no packets have been received over the connection for + # this time, the connection will be closed. + # + # Setting this to 0 means "no timeout". + # + # We STRONGLY RECOMMEND that you set an idle timeout. + # + idle_timeout = 30 + } +} + +# IPv6 Client +client localhost_ipv6 { + ipv6addr = ::1 + secret = testing123 +} + +# All IPv6 Site-local clients +#client sitelocal_ipv6 { +# ipv6addr = fe80::/16 +# secret = testing123 +#} + +#client example.org { +# ipaddr = radius.example.org +# secret = testing123 +#} + +# +# You can now specify one secret for a network of clients. +# When a client request comes in, the BEST match is chosen. +# i.e. The entry from the smallest possible network. +# +#client private-network-1 { +# ipaddr = 192.0.2.0/24 +# secret = testing123-1 +#} + +#client private-network-2 { +# ipaddr = 198.51.100.0/24 +# secret = testing123-2 +#} + +####################################################################### +# +# Per-socket client lists. The configuration entries are exactly +# the same as above, but they are nested inside of a section. +# +# You can have as many per-socket client lists as you have "listen" +# sections, or you can re-use a list among multiple "listen" sections. +# +# Un-comment this section, and edit a "listen" section to add: +# "clients = per_socket_clients". That IP address/port combination +# will then accept ONLY the clients listed in this section. +# +#clients per_socket_clients { +# client socket_client { +# ipaddr = 192.0.2.4 +# secret = testing123 +# } +#} + +client monitoring { + ipaddr = 10.12.174.200 + proto = * + secret = secret + require_message_authenticator = no + nas_type = other + limit { + max_connections = 16 + lifetime = 0 + idle_timeout = 30 + } +} + +client ibasis { + ipaddr = 10.5.146.35 + proto = * + secret = s1mf0ny + require_message_authenticator = no + nas_type = other + limit { + max_connections = 16 + lifetime = 0 + idle_timeout = 30 + } +} + + +client test_home { + + ipaddr = 10.0.1.3 + proto = * + secret = s1mf0ny + require_message_authenticator = no + nas_type = other + limit { + max_connections = 16 + lifetime = 0 + idle_timeout = 30 + } +} + +client 172.29.1.20/32 { + ipaddr = 172.29.1.20 + secret = s1mf0ny + require_message_authenticator = no + nastype = other +} + +client 216.168.191.33/32 { + ipaddr = 216.168.191.33 + secret = s1mf0ny + require_message_authenticator = no + nastype = other + limit { + max_connections = 16 + lifetime = 0 + idle_timeout = 30 + } +} + +client 216.168.191.35/32 { + ipaddr = 216.168.191.35 + secret = s1mf0ny + require_message_authenticator = no + nastype = other + limit { + max_connections = 16 + lifetime = 0 + idle_timeout = 30 + } +} + +client test-simfony-pgw { + ipaddr = 172.22.40.122 + secret = s1mf0ny + require_message_authenticator = no + nastype = other + limit { + max_connections = 16 + lifetime = 0 + idle_timeout = 30 + } + dp = 3799 +} + +client test-stefan { + ipaddr = 10.0.1.5 + secret = s1mf0ny + require_message_authenticator = no + nastype = other + limit { + max_connections = 16 + lifetime = 0 + idle_timeout = 30 + } +} + +client test-adi { + ipaddr = 10.0.1.2 + secret = s1mf0ny + require_message_authenticator = no + nastype = other + limit { + max_connections = 16 + lifetime = 0 + idle_timeout = 30 + } +} + +client lab-test-ibasis-pgw { + ipaddr = 10.7.10.213 + secret = s1mf0ny + require_message_authenticator = no + nastype = other + limit { + max_connections = 16 + lifetime = 0 + idle_timeout = 30 + } +} diff --git a/default b/default new file mode 100644 index 0000000..7edc90d --- /dev/null +++ b/default @@ -0,0 +1,51 @@ +server default { +listen { + type = auth + ipaddr = 0.0.0.0 + port = 0 + limit { + max_connections = 16 + lifetime = 0 + idle_timeout = 30 + } +} +listen { + ipaddr = 0.0.0.0 + port = 0 + type = acct + limit { + } +} +authorize { + perl + if (ok || updated) { + update control { + Auth-Type := Perl + } + } +} +authenticate { +Auth-Type Perl { + perl +} +} +preacct { +} +accounting { + detail + perl + if (ok || updated) { + update control { + Auth-Type := Perl + } + } +} +session { +} +post-auth { +} +pre-proxy { +} +post-proxy { +} +} diff --git a/radiusd.conf b/radiusd.conf new file mode 100644 index 0000000..df7d75d --- /dev/null +++ b/radiusd.conf @@ -0,0 +1,63 @@ +prefix = /usr +exec_prefix = /usr +sysconfdir = /etc +localstatedir = /var +sbindir = /usr/sbin +logdir = ${localstatedir}/log/radius +raddbdir = ${sysconfdir}/raddb +radacctdir = ${logdir}/radacct +name = radiusd +confdir = ${raddbdir} +modconfdir = ${confdir}/mods-config +certdir = ${confdir}/certs +cadir = ${confdir}/certs +run_dir = ${localstatedir}/run/${name} +db_dir = ${localstatedir}/lib/radiusd +libdir = /usr/lib64/freeradius +pidfile = ${run_dir}/${name}.pid +correct_escapes = true +max_request_time = 30 +cleanup_delay = 5 +max_requests = 16384 +hostname_lookups = no +log { + destination = files + colourise = yes + file = ${logdir}/radius.log + syslog_facility = daemon + stripped_names = no + auth = no + auth_badpass = no + auth_goodpass = no + msg_denied = "You are already logged in - access denied" +} +checkrad = ${sbindir}/checkrad +ENV { +} +security { + user = radiusd + group = radiusd + allow_core_dumps = no + max_attributes = 200 + reject_delay = 0 + status_server = yes +} +proxy_requests = no +$INCLUDE clients.conf +thread pool { + start_servers = 5 + max_servers = 32 + min_spare_servers = 3 + max_spare_servers = 10 + max_requests_per_server = 0 + auto_limit_acct = no +} +modules { + $INCLUDE mods-enabled/ +} +instantiate { +} +policy { + $INCLUDE policy.d/ +} +$INCLUDE sites-enabled/ diff --git a/simfony.pl b/simfony.pl new file mode 100644 index 0000000..3944baa --- /dev/null +++ b/simfony.pl @@ -0,0 +1,768 @@ +use warnings; +use DBI; +use REST::Client; +use JSON; +use threads; +use Sys::Hostname; +use Switch; +use Data::Dumper; +use Math::BigInt; +use feature qw(switch); +use Smart::Match; +use constant false => 0; +use constant true => 1; +use Data::Dumper; +use Sys::Hostname; +use Data::Validate::IP qw(is_ipv4 is_ipv6); +use Time::HiRes qw(gettimeofday); + +use constant RLM_MODULE_REJECT => 0; # /* immediately reject the request */ +use constant RLM_MODULE_FAIL => 1; # /* module failed, don't reply */ +use constant RLM_MODULE_OK => 2; # /* the module is OK, continue */ +use constant RLM_MODULE_HANDLED => 3; # /* the module handled the request, so stop. */ +use constant RLM_MODULE_INVALID => 4; # /* the module considers the request invalid. */ +use constant RLM_MODULE_USERLOCK => 5; # /* reject the request (user is locked out) */ +use constant RLM_MODULE_NOTFOUND => 6; # /* user not found */ +use constant RLM_MODULE_NOOP => 7; # /* module succeeded without doing anything */ +use constant RLM_MODULE_UPDATED => 8; # /* OK (pairs modified) */ +use constant RLM_MODULE_NUMCODES => 9; # /* How many return codes there are */ +use constant RAD_LOG_DEBUG => 0; +use constant RAD_LOG_AUTH => 1; +use constant RAD_LOG_PROXY => 2; +use constant RAD_LOG_INFO => 3; +use constant RAD_LOG_ERROR => 4; + +use vars qw(%RAD_REQUEST %RAD_REPLY %RAD_CHECK + $databaseConnection + $subscriberProfileSelector $subscriberProfileSelectorMultiIMSI $subscriberQuery $subscriberMultiIMSIQuery $updatedHlrPsInfoQuery $hlrZoneLookupQuery $hlrZoneLookupSgsnQuery $hlrRoamingSteeringQuery + $hlrZoneLookupProfileQuery $hlrZoneLookupProfileQueryV2 $updatedHlrPsInfoCustomZoneQuery $checkIpAvailability $temporaryMultiImsiInsert $updateSessionId $restClient $technical_imsi $multi_imsi $test_data $donor $country $operatorName + $conn_valid %conf); + +sub read_conf { + $conf{'db_name'} = "mobility"; + $conf{'db_user'} = "root"; + $conf{'db_host'} = "10.5.48.28"; + $conf{'db_port'} = "3307"; + $conf{'db_passwd'} = "xM9A4!exJbQNhqJ"; + $conf{'hook_host'} = "http://notification-v1.simfony:5200/api/notification/"; +} + +sub conn_db { + &read_conf; + $databaseConnection->disconnect() if defined $databaseConnection; + $databaseConnection = DBI->connect("DBI:mysql:database=$conf{'db_name'};host=$conf{'db_host'};port=$conf{'db_port'}", $conf{'db_user'}, $conf{'db_passwd'}) or die ({ &radiusd::radlog(RAD_LOG_ERROR, "key: AAA-MobDB, status: 0, type: SEVERE, message: AAA->MobDB service is down: $conf{'db_host'}:$conf{'db_port'} $conf{'db_name'}")}); + + #$databaseConnection = DBI->connect("DBI:mysql:database=$conf{'db_name'};host=$conf{'db_host'}", $conf{'db_user'}, $conf{'db_passwd'}); + if ($DBI::err) {&radiusd::radlog(RAD_LOG_ERROR, "DB Connect Error. $DBI::errstr");} + else { + + $subscriberQuery = $databaseConnection->prepare("SELECT s.subscriber_id, s.service_allowed, aaa.AccessPointName, aaa.FramedIPAddress, aaa.FramedIPNetmask, aaa.PrimaryDNS, aaa.SecondaryDNS, ent.ENTITLEMENT_VALUE AS SVC_DATA_BLOCKED, saaaprof.Username, saaaprof.`Password`, s.ICCID, ent2.ENTITLEMENT_VALUE AS SVC_DATA_AUTHENTICATE_CREDENTIALS, hps.OPERATOR_NAME, hps.OPERATOR_COUNTRY, s.core_account_id, s.core_seller_id, s.ccs_profile_id, ccsprofile.type, d.code FROM subscriber s + LEFT JOIN aaa_addresspool aaa ON s.subscriber_id = aaa.subscriber_id + LEFT JOIN hlr_ps_roaming_info hps ON hps.IMSI = s.IMSI + LEFT JOIN subscriber_entitlements ent ON s.subscriber_id = ent.subscriber_id AND ent.ENTITLEMENT_NAME = 'SVC_DATA_BLOCKED' + LEFT JOIN subscriber_entitlements ent2 ON s.subscriber_id = ent2.subscriber_id AND ent2.ENTITLEMENT_NAME = 'SVC_DATA_AUTHENTICATE_CREDENTIALS' + LEFT JOIN subscriber_aaa_profile saaaprof ON s.subscriber_id = saaaprof.subscriber_id + LEFT JOIN ccs_profile ccsprofile ON s.ccs_profile_id = ccsprofile.id + LEFT JOIN donor d on s.donor_id = d.id + WHERE s.IMSI LIKE ?"); + + $subscriberMultiIMSIQuery = $databaseConnection->prepare("SELECT s.subscriber_id, s.service_allowed, aaa.AccessPointName, aaa.FramedIPAddress, aaa.FramedIPNetmask, aaa.PrimaryDNS, aaa.SecondaryDNS, ent.ENTITLEMENT_VALUE AS SVC_DATA_BLOCKED, saaaprof.Username, saaaprof.`Password`, s.ICCID, ent2.ENTITLEMENT_VALUE AS SVC_DATA_AUTHENTICATE_CREDENTIALS, hps.OPERATOR_NAME, hps.OPERATOR_COUNTRY, s.core_account_id, s.core_seller_id, s.ccs_profile_id, ccsprofile.type, d.code FROM mobility.subscriber s + LEFT JOIN subscriber_has_multi_imsi shmi on s.SUBSCRIBER_ID = shmi.subscriber_id + LEFT JOIN aaa_addresspool aaa ON s.subscriber_id = aaa.subscriber_id + LEFT JOIN hlr_ps_roaming_info hps ON hps.IMSI = s.IMSI + LEFT JOIN subscriber_entitlements ent ON s.subscriber_id = ent.subscriber_id AND ent.ENTITLEMENT_NAME = 'SVC_DATA_BLOCKED' + LEFT JOIN subscriber_entitlements ent2 ON s.subscriber_id = ent2.subscriber_id AND ent2.ENTITLEMENT_NAME = 'SVC_DATA_AUTHENTICATE_CREDENTIALS' + LEFT JOIN subscriber_aaa_profile saaaprof ON s.subscriber_id = saaaprof.subscriber_id + LEFT JOIN ccs_profile ccsprofile ON s.ccs_profile_id = ccsprofile.id + LEFT JOIN donor d on s.donor_id = d.id + WHERE shmi.IMSI LIKE ?"); + + $hlrZoneLookupSgsnQuery = $databaseConnection->prepare("SELECT * FROM hlr_zone_lookup_by_sgsn + WHERE inet_aton(?) between inet_aton(SUBNET_START) and inet_aton(SUBNET_END) limit 1;"); + + $hlrZoneLookupProfileQuery = $databaseConnection->prepare("SELECT hzl.TADIG, hzl.OPERATOR_COUNTRY, hzl.OPERATOR_NAME, IF(po.allow, 1, 0), IF(po.ZONE IS NULL,hzl.zone,po.ZONE), po.id FROM profile_operators po + LEFT JOIN hlr_zone_lookup hzl ON hzl.ID = po.hlr_zone_lookup_id WHERE CONCAT(hzl.mcc, hzl.mnc) = ? + AND po.profile_id = (select s.PROFILE_ID from subscriber s where imsi = ?) limit 1;"); + + $hlrZoneLookupQuery = $databaseConnection->prepare("select OPERATOR_COUNTRY, OPERATOR_NAME,ROAMING_ENABLED from hlr_zone_lookup where concat(mcc,mnc) like ? limit 1;"); + + $hlrRoamingSteeringQuery = $databaseConnection->prepare("SELECT hzl.OPERATOR_COUNTRY, hzl.OPERATOR_NAME, hzl.ROAMING_ENABLED FROM hlr_roaming_steering hrs + left join hlr_zone_lookup hzl on hzl.GTPREFIX like concat(hrs.GTPREFIX,'%') + where hrs.IMSI = ? and concat(hzl.mcc,hzl.mnc) like ? limit 1;"); + + $updatedHlrPsInfoQuery = $databaseConnection->prepare("UPDATE hlr_ps_roaming_info AS ps_profile, + (SELECT TADIG, OPERATOR_COUNTRY, OPERATOR_NAME, ZONE FROM hlr_zone_lookup WHERE concat (mcc,mnc) like ? limit 1 ) AS src SET + ps_profile.LAST_UPDATE = NOW(), + ps_profile.TADIG = src.TADIG, + ps_profile.OPERATOR_COUNTRY = src.OPERATOR_COUNTRY, + ps_profile.OPERATOR_NAME = src.OPERATOR_NAME, ps_profile.ZONE = src.ZONE + WHERE ps_profile.IMSI = ?"); + + $updatedHlrPsInfoCustomZoneQuery = $databaseConnection->prepare("UPDATE hlr_ps_roaming_info AS ps_profile, + (SELECT TADIG, OPERATOR_COUNTRY, OPERATOR_NAME FROM hlr_zone_lookup WHERE concat (mcc,mnc) like ? limit 1 ) AS src SET + ps_profile.LAST_UPDATE = NOW(), + ps_profile.TADIG = src.TADIG, + ps_profile.OPERATOR_COUNTRY = + src.OPERATOR_COUNTRY, + ps_profile.OPERATOR_NAME = src.OPERATOR_NAME, + ps_profile.ZONE = ? + WHERE ps_profile.IMSI = ?"); + + $subscriberProfileSelector = $databaseConnection->prepare("SELECT s.iccid, s.profile_id, p.code, s.core_account_id, s.core_seller_id FROM SUBSCRIBER s LEFT JOIN provider p on s.provider_id = p.id WHERE IMSI LIKE ? LIMIT 1;"); + + $subscriberProfileSelectorMultiIMSI = $databaseConnection->prepare("SELECT s.iccid, s.profile_id, p.code, s.core_account_id, s.core_seller_id, s.eid, s.eid_32, s.imsi FROM SUBSCRIBER s LEFT JOIN provider p on s.provider_id = p.id LEFT JOIN subscriber_has_multi_imsi shmi on s.SUBSCRIBER_ID = shmi.subscriber_id WHERE shmi.IMSI LIKE ? LIMIT 1;"); + + $checkIpAvailability = $databaseConnection->prepare("SELECT COUNT(imsi) FROM temporary_multi_imsi_session WHERE ip_address = ?;"); + + $temporaryMultiImsiInsert = $databaseConnection->prepare("INSERT INTO temporary_multi_imsi_session(imsi, ip_address, start_date, source_system) VALUE (?, ?, NOW(), ?) ON DUPLICATE KEY UPDATE ip_address = ?, start_date= NOW(), source_system = ?;"); + + $updateSessionId = $databaseConnection->prepare("UPDATE temporary_multi_imsi_session SET session_id = ? WHERE imsi = ?;"); + + $hlrZoneLookupProfileQueryV2 = $databaseConnection->prepare("select hzl.TADIG, hzl.OPERATOR_COUNTRY, hzl.OPERATOR_NAME, IF(hzl.ROAMING_ENABLED, 0, 1), IF(phz.custom_zone IS NULL,z.code,phz.custom_zone), p.id + from hlr_zone_lookup hzl + left join zone_has_hlr_zone_lookup zhhzl on hzl.ID = zhhzl.hlr_zone_lookup_id and CONCAT(hzl.mcc, hzl.mnc) = ? + left join zone z on zhhzl.zone_id = z.id + left join profile_has_zone phz on z.id = phz.zone_id + left join profile p on p.id = phz.profile_id + where p.id = (select s.PROFILE_ID from subscriber s where imsi = ?) limit 1;"); + } + $conn_valid = (!$DBI::err); + &radiusd::radlog(RAD_LOG_INFO, "key: AAA-MobDB, status: 1, type: CLEAR, message: AAA->MobDB service is up: $conf{'db_host'}:$conf{'db_port'} $conf{'db_name'}") + +} + +sub sendPlatformNotification { + my ($imsi, $apn, $username, $outcome, $reason, $operatorName, $country, $iccid, $rat_type, $provider, + $accountId, $sellerId, $decodedUserLocationInfo, $technical_imsi, $multi_imsi) = @_; + + + # my $actualResponse = {}; + # for my $key (keys %RAD_REPLY) { + # $actualResponse->{$key} = $RAD_REPLY{$key}; + # } + + # # TODO filter out passwords for PAP / CHAP authentication @Tudor + # my $actualRequest = {}; + # for my $key (keys %RAD_REQUEST) { + # $actualRequest->{$key} = $RAD_REQUEST{$key}; + # } + + my $eventJson = { + eventTimestamp => int(gettimeofday() * 1000), + sourceSystem => hostname, + accountId => $accountId, + sellerId => $sellerId, + # radiusRequest => $actualRequest, + # radiusResponse => $actualResponse, + + simCardCharacteristicCollection => [ + { + simCardCharacteristicName => 'IMSI', + simCardCharacteristicValue => $imsi + }, + { + simCardCharacteristicName => 'APN_NAME', + simCardCharacteristicValue => $apn + }, + { + simCardCharacteristicName => 'APN_USERNAME', + simCardCharacteristicValue => $username + }, + { + simCardCharacteristicName => 'OUTCOME', + simCardCharacteristicValue => $outcome + }, + { + simCardCharacteristicName => 'REASON', + simCardCharacteristicValue => $reason + }, + { + simCardCharacteristicName => 'OPERATOR_NAME', + simCardCharacteristicValue => $operatorName + }, + { + simCardCharacteristicName => 'COUNTRY', + simCardCharacteristicValue => $country + }, + { + simCardCharacteristicName => 'RAT_TYPE', + simCardCharacteristicValue => $rat_type + }, + { + simCardCharacteristicName => 'TECHNICAL_IMSI', + simCardCharacteristicValue => $technical_imsi + }, + { + simCardCharacteristicName => 'MULTI_IMSI', + simCardCharacteristicValue => $multi_imsi + }, + { + simCardCharacteristicName => 'LOCATION_INFO', + simCardCharacteristicValue => encode_json($decodedUserLocationInfo) + } + ], + eventName => 'DATA_SESSION_AUTHORIZATION', + provider => $provider, + }; + + if ($sellerId ne "") { + if (!defined($restClient)) { + $restClient = REST::Client->new(); + } + &radiusd::radlog(RAD_LOG_INFO, $conf{'hook_host'} . $iccid . " -> " . encode_json($eventJson)); + #$restClient->POST($conf{'hook_host'} . $iccid, encode_json($eventJson), { 'Content-type' => 'application/json' }); + } + undef $imsi, $apn, $username, $outcome, $reason, $operatorName, $country, $iccid, $rat_type, $provider, $accountId, $sellerId, $decodedUserLocationInfo, $technical_imsi, $multi_imsi, $test_data, $eventJson; +} + +sub authorize { + &log_request_attributes; + + # my $congestion = int(rand(9))+1; + my $congestion = 1; + # + #congestion > 1, only 10% is being accepted, rest of 90% rejected + # + if ($congestion > 4) { + &radiusd::radlog(RAD_LOG_ERROR, "$RAD_REQUEST{'3GPP-IMSI'} -> CONGESTION REACHED ${congestion}"); + undef $congestion; + return RLM_MODULE_REJECT; + } + + if (!$conn_valid) { + &radiusd::radlog(RAD_LOG_INFO, "$RAD_REQUEST{'3GPP-IMSI'} -> NEW DB CONNECTION"); + &conn_db; + } + + unless ($databaseConnection->ping) { + &radiusd::radlog(RAD_LOG_INFO, "$RAD_REQUEST{'3GPP-IMSI'} -> NEW DB CONNECTION ON PING"); + &conn_db; + } + + my $visitedMccMnc = $RAD_REQUEST{'3GPP-SGSN-MCC-MNC'}; + my $imsi = $RAD_REQUEST{'3GPP-IMSI'}; + my $technical_imsi = $RAD_REQUEST{'3GPP-IMSI'}; + my $multi_imsi = false; + my $test_data = false; + my $userLocationInfo = $RAD_REQUEST{'3GPP-User-Location-Info'}; + my $decodedUserLocationInfo; + + # check if mcc mnc is pressent in request + if ($visitedMccMnc eq "") { + #if mcc mnc is missing start query by sgsn address + my $visitedIp = $RAD_REQUEST{'3GPP-SGSN-Address'}; + &radiusd::radlog(RAD_LOG_INFO, "$imsi -> no 3GPP-SGSN-MCC-MNC -> check by ip addr ${visitedIp}"); + $hlrZoneLookupSgsnQuery->execute($visitedIp); + my @hlrsgsn = $hlrZoneLookupSgsnQuery->fetchrow_array; + + if (scalar(@hlrsgsn) != 0) { + # set visitedMccMnc to value from hlr_zone_lookup_by_sgsn table + $visitedMccMnc = @hlrsgsn[4]; + &radiusd::radlog(RAD_LOG_INFO, "$imsi -> ${visitedIp} -> ${visitedMccMnc}"); + } + undef $visitedIp, @hlrsgsn; + } + + if ($userLocationInfo) { + $decodedUserLocationInfo = getDecodedLocationInfo($userLocationInfo); + $decodedUserLocationInfo->{MCC} = substr($visitedMccMnc, 0, 3); + $decodedUserLocationInfo->{MNC} = substr($visitedMccMnc, 3, length($visitedMccMnc) - 3); + } + + # check if subscriber has a custom profile + $subscriberProfileSelector->execute($imsi); + my @iccidAndProfileId = $subscriberProfileSelector->fetchrow_array; + + if (scalar(@iccidAndProfileId) == 0) { + $subscriberProfileSelectorMultiIMSI->execute($imsi); + @iccidAndProfileId = $subscriberProfileSelectorMultiIMSI->fetchrow_array; + &radiusd::radlog(RAD_LOG_INFO, "$imsi -> MAPPED TO @iccidAndProfileId[7], CONTINUING WITH @iccidAndProfileId[7]"); + &radiusd::radlog(RAD_LOG_INFO, "$imsi -> MAPPED TO ALL: " . join(", ", @iccidAndProfileId)); + + $imsi = @iccidAndProfileId[7]; + $multi_imsi = true; + } + + my $customZone = ''; + my $isZonedDeny; + if ((index(@iccidAndProfileId[2], 'v2_') == 0) or (index(@iccidAndProfileId[2], 'dev') == 0)) { + &radiusd::radlog(RAD_LOG_INFO, "$imsi -> v2 engine check"); + $hlrZoneLookupProfileQueryV2->execute($visitedMccMnc, $imsi); + my @profileZone = $hlrZoneLookupProfileQueryV2->fetchrow_array; + if (scalar(@profileZone) != 0) { + &radiusd::radlog(RAD_LOG_INFO, "$imsi -> {@profileZone}"); + &radiusd::radlog(RAD_LOG_INFO, "$imsi -> CUSTOM PROFILE OPERATOR: TADIG: {@profileZone[0]} COUNTRY: {@profileZone[1]} OPERATOR: {@profileZone[2]} IS_ALLOW: {@profileZone[3]} ZONE: {@profileZone[4]}"); + $customZone = @profileZone[4]; + $isZonedDeny = @profileZone[3] == 1 ? 0 : 1; + &radiusd::radlog(RAD_LOG_INFO, "$imsi -> CUSTOM PROFILE OPERATOR: TADIG: {@profileZone[0]} COUNTRY: {@profileZone[1]} OPERATOR: {@profileZone[2]} IS_DENY: ${isZonedDeny} ZONE: ${customZone}"); + $country = @profileZone[1]; + $operatorName = @profileZone[2]; + undef @profileZone; + } + else { + + #maybe do another select here to actually show the country and operator where the session was denied + &radiusd::radlog(RAD_LOG_ERROR, "$imsi -> NO PROFILE OPERATOR FOUND: IMSI= $imsi, PROFILE_ID = {@iccidAndProfileId[1]} MCC-MNC ${visitedMccMnc} "); + &sendPlatformNotification($imsi, $RAD_REQUEST{'Called-Station-Id'}, $RAD_REQUEST{'User-Name'}, 'REJECT', 'Data session not allowed by current profile', "N/A", "N/A", @iccidAndProfileId[0], $RAD_REQUEST{'3GPP-RAT-Type'}, @iccidAndProfileId[2], @iccidAndProfileId[3], @iccidAndProfileId[4], $decodedUserLocationInfo); + &radiusd::radlog(RAD_LOG_ERROR, "$imsi -> REJECTED "); + undef $visitedMccMnc, $imsi, @iccidAndProfileId, $customZone, $isZonedDeny, $decodedUserLocationInfo, $operatorName, $country, $donor; + return RLM_MODULE_REJECT; + } + } + else { + if (@iccidAndProfileId[1] != "") { + &radiusd::radlog(RAD_LOG_INFO, "$imsi has custom profile: {@iccidAndProfileId[1]} for MccMnc $visitedMccMnc"); + $hlrZoneLookupProfileQuery->execute($visitedMccMnc, $imsi); + my @profileZone = $hlrZoneLookupProfileQuery->fetchrow_array; + # if custom profile is find for request mcc mnc set if is allowed and custom zone + if (scalar(@profileZone) != 0) { + &radiusd::radlog(RAD_LOG_INFO, "$imsi -> {@profileZone}"); + &radiusd::radlog(RAD_LOG_INFO, "$imsi -> CUSTOM PROFILE OPERATOR: TADIG: {@profileZone[0]} COUNTRY: {@profileZone[1]} OPERATOR: {@profileZone[2]} IS_ALLOW: {@profileZone[3]} ZONE: {@profileZone[4]}"); + $customZone = @profileZone[4]; + $isZonedDeny = @profileZone[3] == 1 ? 0 : 1; + &radiusd::radlog(RAD_LOG_INFO, "$imsi -> CUSTOM PROFILE OPERATOR: TADIG: {@profileZone[0]} COUNTRY: {@profileZone[1]} OPERATOR: {@profileZone[2]} IS_DENY: ${isZonedDeny} ZONE: ${customZone}"); + $country = @profileZone[1]; + $operatorName = @profileZone[2]; + undef @profileZone; + } + else { + &radiusd::radlog(RAD_LOG_ERROR, "$imsi -> NO PROFILE OPERATOR FOUND: PROFILE_ID = {@iccidAndProfileId[1]} MCC-MNC ${visitedMccMnc} "); + #TODO FIX THIS + &sendPlatformNotification($imsi, $RAD_REQUEST{'Called-Station-Id'}, $RAD_REQUEST{'User-Name'}, 'REJECT', 'Data session not allowed by current profile', "N/A", "N/A", @iccidAndProfileId[0], $RAD_REQUEST{'3GPP-RAT-Type'}, @iccidAndProfileId[2], @iccidAndProfileId[3], @iccidAndProfileId[4], $decodedUserLocationInfo); + &radiusd::radlog(RAD_LOG_ERROR, "$imsi -> REJECTED "); + undef $visitedMccMnc, $imsi, $multi_imsi, $technical_imsi, $test_data, $donor, @iccidAndProfileId, $customZone, $isZonedDeny, $decodedUserLocationInfo, $operatorName, $country; + return RLM_MODULE_REJECT; + } + } + } + + + #find subscriber + $subscriberQuery->execute($imsi); + my @ref = $subscriberQuery->fetchrow_array; + + if (scalar(@ref) == 0) { + $subscriberMultiIMSIQuery->execute($imsi); + @ref = $subscriberMultiIMSIQuery->fetchrow_array; + } + + my $nasIP = $RAD_REQUEST{'NAS-IP-Address'}; + + if (scalar(@ref) == 0 && $nasIP != '172.29.1.20') { + $imsi = $RAD_REQUEST{'3GPP-IMSI'}; + + &radiusd::radlog(RAD_LOG_ERROR, "IMSI = ${imsi} NOT_FOUND TRYING TO FALLBACK TO MULTI IMSI SCENARIO"); + my $randomIp = generateRandomIP($nasIP); + $checkIpAvailability->execute($randomIp); + my $counter = $checkIpAvailability->fetchrow_array; + + + while ($counter != 0) { + $randomIp = generateRandomIP($nasIP); + $checkIpAvailability->execute($randomIp); + $counter = $checkIpAvailability->fetchrow_array; + } + + if ($counter == 0 && is_ipv4($randomIp)) { + &radiusd::radlog(RAD_LOG_INFO, "MULTI IMSI $imsi ASSIGN TEMPORARY IP $randomIp"); + $temporaryMultiImsiInsert->bind_param(1, $imsi); + $temporaryMultiImsiInsert->bind_param(2, $randomIp); + $temporaryMultiImsiInsert->bind_param(3, $nasIP); + $temporaryMultiImsiInsert->bind_param(4, $randomIp); + $temporaryMultiImsiInsert->bind_param(5, $nasIP); + + $temporaryMultiImsiInsert->execute(); + + $RAD_REPLY{'Framed-IP-Address'} = $randomIp; + $RAD_REPLY{'Framed-IP-Netmask'} = '255.255.192.0'; + $RAD_REPLY{'MS-Primary-DNS-Server'} = '8.8.8.8'; + $RAD_REPLY{'MS-Secondary-DNS-Server'} = '8.8.4.4'; + $RAD_REPLY{'Session-Timeout'} = '604800'; + + &radiusd::radlog(RAD_LOG_INFO, "IMSI = ${imsi} SUCCESS"); + undef $visitedMccMnc, $imsi, @iccidAndProfileId, $customZone, $isZonedDeny, @ref, $randomIp, $counter; + &log_response_success($imsi, ""); + return RLM_MODULE_OK; + } + + undef $visitedMccMnc, $imsi, @iccidAndProfileId, $customZone, $isZonedDeny, @ref, $counter, $randomIp; + &radiusd::radlog(RAD_LOG_ERROR, "IMSI = ${imsi} MULTI IMSI SCENARIO: IP COULD NOT BE GENERATED BASED ON NAS-IP-Address"); + + return RLM_MODULE_REJECT; + } + + my $donor = @ref[18]; + #how can we change the @ref entry as it contains the old stuff, or do we just change the notification + # update ps roaming info for subscriber without ss7 signaling for now only iBasis SIM s + if (index($donor, 'IBasis') == 0) { + &radiusd::radlog(RAD_LOG_INFO, "$imsi -> DONOR IS ${donor}"); + + if (length($customZone) == 0) { + &radiusd::radlog(RAD_LOG_INFO, "$imsi -> UPDATE PS PROFILE ${visitedMccMnc}"); + $updatedHlrPsInfoQuery->bind_param(1, $visitedMccMnc); + $updatedHlrPsInfoQuery->bind_param(2, $imsi); + $updatedHlrPsInfoQuery->execute(); + } + else { + &radiusd::radlog(RAD_LOG_INFO, "$imsi -> UPDATE PS PROFILE ${visitedMccMnc} CUSTOM ZONE ${customZone}"); + #if custom zone is not empty make a custom update with values from hlr_zone_lookup and $customZone + $updatedHlrPsInfoCustomZoneQuery->bind_param(1, $visitedMccMnc); + $updatedHlrPsInfoCustomZoneQuery->bind_param(2, $customZone); + $updatedHlrPsInfoCustomZoneQuery->bind_param(3, $imsi); + $updatedHlrPsInfoCustomZoneQuery->execute(); + } + } + + my $iccid = @ref[10]; + + #if $isZonedDeny is empty profile dosen't contains values for this mcc mcn so get value from hlr_zone_lookup + if (!defined $isZonedDeny) { + &radiusd::radlog(RAD_LOG_DEBUG, "ICCID = ${iccid} IMSI = ${imsi} ZONE IS DENIAL IS NOT DEFINED CHECK IN HLR ZONE LOOKUP"); + $hlrZoneLookupQuery->execute($visitedMccMnc); + my @hlr = $hlrZoneLookupQuery->fetchrow_array; + $isZonedDeny = @hlr[2]; + undef @hlr; + } + + if ($isZonedDeny != 0) { + #TODO FIX THIS + &radiusd::radlog(RAD_LOG_ERROR, "ICCID = ${iccid} IMSI = ${imsi} DATA_SESSION_NOT_ALLOWED - ZONE DENIAL"); + &sendPlatformNotification($imsi, $RAD_REQUEST{'Called-Station-Id'}, $RAD_REQUEST{'User-Name'}, 'REJECT', 'Data session not allowed', ($operatorName ? $operatorName : @ref[12]), ($country ? $country : @ref[13]), $iccid, $RAD_REQUEST{'3GPP-RAT-Type'}, @iccidAndProfileId[2], @ref[14], @ref[15], $decodedUserLocationInfo, $technical_imsi, $multi_imsi); + &radiusd::radlog(RAD_LOG_ERROR, "$imsi -> REJECTED "); + undef $visitedMccMnc, $imsi, $iccid, @iccidAndProfileId, $customZone, $isZonedDeny, @ref, $decodedUserLocationInfo; + return RLM_MODULE_REJECT; + } + + $hlrRoamingSteeringQuery->execute($imsi, $visitedMccMnc); + my @hrs = $hlrRoamingSteeringQuery->fetchrow_array; + + if (scalar(@hrs) != 0) { + &radiusd::radlog(RAD_LOG_ERROR, "ICCID = ${iccid} IMSI = ${imsi} DATA_SESSION_BLOCKED_BY_USER"); + &sendPlatformNotification($imsi, $RAD_REQUEST{'Called-Station-Id'}, $RAD_REQUEST{'User-Name'}, 'REJECT', 'Mobile Data blocked by user for ' . @hrs[1], @hrs[1], @hrs[0], $iccid, $RAD_REQUEST{'3GPP-RAT-Type'}, @iccidAndProfileId[2], @ref[14], @ref[15], $decodedUserLocationInfo, $technical_imsi, $multi_imsi); + &radiusd::radlog(RAD_LOG_ERROR, "$imsi -> REJECTED "); + undef $visitedMccMnc, $imsi, $iccid, @iccidAndProfileId, $customZone, $isZonedDeny, @ref, @hrs, $decodedUserLocationInfo; + return RLM_MODULE_REJECT; + } + + # check if subscriber is suspended + if (@ref[1] == 1) { + # check if subscriber is suspended and has access to test data + # if (@ref[1] == 1) + my $ccs_profile_id = @ref[16]; + my $ccs_profile_type = @ref[17]; + &radiusd::radlog(RAD_LOG_ERROR, "ccs_profile_id = ${ccs_profile_id}, ccs_profile_type = ${ccs_profile_type}"); + + if ($ccs_profile_type eq 'TEST_DATA') { + + &radiusd::radlog(RAD_LOG_ERROR, "ICCID = ${iccid} IMSI = ${imsi} SUBSCRIBER_SUSPENDED BUT ALLOWING TEST DATA"); + $test_data = true; #continue + } + else { + + &radiusd::radlog(RAD_LOG_ERROR, "ICCID = ${iccid} IMSI = ${imsi} SUBSCRIBER_SUSPENDED"); + &sendPlatformNotification($imsi, $RAD_REQUEST{'Called-Station-Id'}, $RAD_REQUEST{'User-Name'}, 'REJECT', 'Subscriber is suspended', ($operatorName ? $operatorName : @ref[12]), ($country ? $country : @ref[13]), $iccid, $RAD_REQUEST{'3GPP-RAT-Type'}, @iccidAndProfileId[2], @ref[14], @ref[15], $decodedUserLocationInfo, $technical_imsi, $multi_imsi); + &radiusd::radlog(RAD_LOG_ERROR, "$imsi -> REJECTED "); + undef $visitedMccMnc, $imsi, $iccid, @iccidAndProfileId, $customZone, $isZonedDeny, @ref, @hrs, $decodedUserLocationInfo, $ccs_profile_id, $ccs_profile_type; + return RLM_MODULE_REJECT; + } + + } + + # check if mobile data is blocked by user + if (@ref[7] eq 'true') { + &radiusd::radlog(RAD_LOG_ERROR, "ICCID = ${iccid} IMSI = ${imsi} MOBILE_DATA_BLOCKED_BY_USER"); + &sendPlatformNotification($imsi, $RAD_REQUEST{'Called-Station-Id'}, $RAD_REQUEST{'User-Name'}, 'REJECT', 'Mobile Data blocked by user', ($operatorName ? $operatorName : @ref[12]), ($country ? $country : @ref[13]), $iccid, $RAD_REQUEST{'3GPP-RAT-Type'}, @iccidAndProfileId[2], @ref[14], @ref[15], $decodedUserLocationInfo, $technical_imsi, $multi_imsi); + &radiusd::radlog(RAD_LOG_ERROR, "$imsi -> REJECTED "); + undef $visitedMccMnc, $imsi, $iccid, @iccidAndProfileId, $customZone, $isZonedDeny, @ref, @hrs, $decodedUserLocationInfo; + return RLM_MODULE_REJECT; + } + + # check if apn credentials match + if ((@ref[8] ne $RAD_REQUEST{'User-Name'} || @ref[9] ne $RAD_REQUEST{'User-Password'}) && @ref[11] eq 'true') { + &radiusd::radlog(RAD_LOG_ERROR, "ICCID = ${iccid} IMSI = ${imsi} INVALID_APN_CREDENTIALS"); + &sendPlatformNotification($imsi, $RAD_REQUEST{'Called-Station-Id'}, $RAD_REQUEST{'User-Name'}, 'REJECT', 'APN Authentication failed', ($operatorName ? $operatorName : @ref[12]), ($country ? $country : @ref[13]), $iccid, $RAD_REQUEST{'3GPP-RAT-Type'}, @iccidAndProfileId[2], @ref[14], @ref[15], $decodedUserLocationInfo, $technical_imsi, $multi_imsi); + &radiusd::radlog(RAD_LOG_ERROR, "$imsi -> REJECTED "); + undef $visitedMccMnc, $imsi, $iccid, @iccidAndProfileId, $customZone, $isZonedDeny, @ref, @hrs, $decodedUserLocationInfo; + return RLM_MODULE_REJECT; + } + + # check if apn match +# if (not lc($RAD_REQUEST{'Called-Station-Id'}) eq lc($ref[2])) { + #if (index(lc $RAD_REQUEST{'Called-Station-Id'}, lc @ref[2]) != 0) + my @apns = split(/,/, lc @ref[2]); + my $found = 0; + + foreach my $apn (@apns) { + $apn =~ s/^\s+|\s+$//g; # trimming whitespace from start and end + if (index(lc $RAD_REQUEST{'Called-Station-Id'}, $apn) != -1) { + $found = 1; + last; + } + } + + unless ($found) { + &radiusd::radlog(RAD_LOG_ERROR, "ICCID = ${iccid} IMSI = ${imsi} INVALID_APN {@ref[2]} REQUESTED {$RAD_REQUEST{'Called-Station-Id'}}"); + &sendPlatformNotification($imsi, $RAD_REQUEST{'Called-Station-Id'}, $RAD_REQUEST{'User-Name'}, 'REJECT', 'Invalid APN', ($operatorName ? $operatorName : @ref[12]), ($country ? $country : @ref[13]), $iccid, $RAD_REQUEST{'3GPP-RAT-Type'}, @iccidAndProfileId[2], @ref[14], @ref[15], $decodedUserLocationInfo, $technical_imsi, $multi_imsi); + &radiusd::radlog(RAD_LOG_ERROR, "$imsi -> REJECTED "); + undef $visitedMccMnc, $imsi, $iccid, @iccidAndProfileId, $customZone, $isZonedDeny, @ref, @hrs, $decodedUserLocationInfo; + return RLM_MODULE_REJECT; + } + + # success + &radiusd::radlog(RAD_LOG_INFO, "!!!!!!!!{@ref[12]} ICCID = ${iccid} IMSI = ${imsi} SUCCESS 0"); + + + + my $ip = parallelIPProcedure($imsi, $RAD_REQUEST{'NAS-IP-Address'}, @ref[3]); + $RAD_REPLY{'Framed-IP-Address'} = $ip; + $RAD_REPLY{'Framed-IP-Netmask'} = @ref[4]; + $RAD_REPLY{'MS-Primary-DNS-Server'} = @ref[5]; + $RAD_REPLY{'MS-Secondary-DNS-Server'} = @ref[6]; + $RAD_REPLY{'Session-Timeout'} = '604800'; + #$RAD_REPLY{'Framed-Route'} = '45.148.166.176/29 45.148.166.161 1 2 -1 3 400'; + + &log_response_success($imsi, $iccid); + + &sendPlatformNotification( + $imsi, + $RAD_REQUEST{'Called-Station-Id'}, + $RAD_REQUEST{'User-Name'}, + 'ACCEPT', + 'Mobile Data Session Authorized', + ($operatorName ? $operatorName : @ref[12]), + ($country ? $country : @ref[13]), + $iccid, + $RAD_REQUEST{'3GPP-RAT-Type'}, + @iccidAndProfileId[2], + @ref[14], + @ref[15], + $decodedUserLocationInfo, + $technical_imsi, + $multi_imsi, + $RAD_REPLY); + + undef $visitedMccMnc, $imsi, $test_data, $donor, $multi_imsi, $technical_imsi, @iccidAndProfileId, $customZone, $isZonedDeny, @ref, $iccid, @hrs, $decodedUserLocationInfo, $ip, $operatorName, $country; + return RLM_MODULE_OK; +} + +# Function to handle authenticate +sub authenticate { + return RLM_MODULE_OK; + +} + +# Function to handle preacct +sub preacct { + # For debugging purposes only + # &log_request_attributes; + return RLM_MODULE_OK; +} + +# Function to handle accounting +sub accounting { + &log_request_attributes; + my $sessionId = $RAD_REQUEST{'Acct-Session-Id'}; + my $imsi = $RAD_REQUEST{'3GPP-IMSI'}; + + $updateSessionId->bind_param(1, $sessionId); + $updateSessionId->bind_param(2, $imsi); + $updateSessionId->execute(); + + undef $sessionId, $imsi; + return RLM_MODULE_OK; +} + +# Function to handle checksimul +sub checksimul { + # For debugging purposes only + # &log_request_attributes; + return RLM_MODULE_OK; +} + +# Function to handle pre_proxy +sub pre_proxy { + # For debugging purposes only + # &log_request_attributes; + return RLM_MODULE_OK; +} + +# Function to handle post_proxy +sub post_proxy { + # For debugging purposes only + # &log_request_attributes; + return RLM_MODULE_OK; +} + +# Function to handle post_auth +sub post_auth { + # For debugging purposes only + # &log_request_attributes; + return RLM_MODULE_OK; +} + +# Function to handle detach +sub detach { + # For debugging purposes only + # &log_request_attributes; + # Do some logging. + &radiusd::radlog(0, "rlm_perl::Detaching. Reloading. Done."); +} + +sub log_request_attributes { + my $logJson = {}; + for my $key (keys %RAD_REQUEST) { + $logJson->{$key} = $RAD_REQUEST{$key}; + } + &radiusd::radlog(RAD_LOG_INFO, 'REQUEST: ' . encode_json($logJson)); + + undef $logJson; +} + +sub log_response_success { + my ($imsi, $iccid) = @_; + my $logJson = {}; + for my $key (keys %RAD_REPLY) { + $logJson->{$key} = $RAD_REPLY{$key}; + } + &radiusd::radlog(RAD_LOG_INFO, "ICCID = ${iccid} IMSI = ${imsi} RESPONSE: " . encode_json($logJson)); + + undef $logJson; +} + +sub getDecodedLocationInfo { + my $type = 'not_set'; + my $decodedLocationInfo = {}; + my @hex = ($_[0] =~ /(..)/g); + my @dec = map {hex($_)} @hex; + my @bytes = map {pack('C', $_)} @dec; + my $intType = $dec[1]; + given ($intType) { + when (0) { + $type = "CGI"; + $decodedLocationInfo->{type} = $type; + $decodedLocationInfo->{LAC} = Math::BigInt->new('0x' . join('', map sprintf('%.2x', $_), @dec[5 .. 6]))->{value}[0]; + $decodedLocationInfo->{CI} = Math::BigInt->new('0x' . join('', map sprintf('%.2x', $_), @dec[7 .. 8]))->{value}[0] + } + when (1) { + $type = "SAI"; + $decodedLocationInfo->{type} = $type; + $decodedLocationInfo->{LAC} = Math::BigInt->new('0x' . join('', map sprintf('%.2x', $_), @dec[5 .. 6]))->{value}[0]; + $decodedLocationInfo->{SAC} = Math::BigInt->new('0x' . join('', map sprintf('%.2x', $_), @dec[7 .. 8]))->{value}[0] + } + when (2) { + $type = "RAI"; + $decodedLocationInfo->{type} = $type; + $decodedLocationInfo->{LAC} = Math::BigInt->new('0x' . join('', map sprintf('%.2x', $_), @dec[5 .. 6]))->{value}[0]; + $decodedLocationInfo->{RAC} = Math::BigInt->new('0x' . join('', map sprintf('%.2x', $_), @dec[7 .. 7]))->{value}[0] + } + when (128) { + $type = "TAI"; + $decodedLocationInfo->{type} = $type; + $decodedLocationInfo->{LAC} = "NOT IMPLEMENTED"; + $decodedLocationInfo->{CI} = "NOT IMPLEMENTED" + } + when (129) { + $type = "ECGI"; + $decodedLocationInfo->{type} = $type; + $decodedLocationInfo->{LAC} = "NOT IMPLEMENTED"; + $decodedLocationInfo->{CI} = "NOT IMPLEMENTED" + } + when (130) { + $type = "TAI & ECGI"; + $decodedLocationInfo->{type} = $type; + $decodedLocationInfo->{TAC} = Math::BigInt->new('0x' . join('', map sprintf('%.2x', $_), @dec[5 .. 6]))->{value}[0]; + $decodedLocationInfo->{ECI} = Math::BigInt->new('0x' . join('', map sprintf('%.2x', $_), @dec[10 .. 13]))->{value}[0] + } + } + return $decodedLocationInfo; +} + +sub generateRandomIP { + &radiusd::radlog(0, "rlm_perl::generateRandomIP start"); + my ($nasIP) = @_; + my @digits = ""; + + if ($nasIP eq "216.168.191.35") { + @digits = "10.192.0"; + } + + if ($nasIP eq "216.168.191.33") { + @digits = "10.193.0"; + } + + if ($nasIP eq "10.5.146.35") { + @digits = "10.187.0"; + } + + if ($nasIP eq "202.63.22.8") { + @digits = "10.192.0"; + } + + push @digits, int(rand(253)) + 1; + &radiusd::radlog(0, "rlm_perl::generateRandomIP stop"); + + return join '.', @digits; +} + + +sub parallelIPProcedure() { + &radiusd::radlog(0, "rlm_perl::parallelIPProcedure start"); + my ($imsi, $nasIP, $ip) = @_; + &radiusd::radlog(RAD_LOG_INFO, "$imsi -> $nasIP -> $ip"); + my @spl = split('\.', $ip); + my $ipMask = @spl[0] . "." . @spl[1]; + my $ipTermination = @spl[2] . "." . @spl[3]; + my $query = ""; + if ($nasIP eq "216.168.191.33") { + $query = "SELECT SUBSTRING_INDEX(DAL, '.', 2), SUBSTRING_INDEX(AMS, '.', 2) FROM aaa_parallel_ranges WHERE SUBSTRING_INDEX(AMS, '.', 2) = " . $ipMask . " OR SUBSTRING_INDEX(DAL, '.', 2) = " . $ipMask . ";"; + my $aaaIP = $databaseConnection->prepare($query); + $aaaIP->execute; + my @result = $aaaIP->fetchrow_array; + if (scalar(@result) == 0) { + &radiusd::radlog(RAD_LOG_ERROR, "NO RESULT FOUND FOR $ipMask IN AMS"); + } + else { + if (@result[0] ne $ipMask) { + &radiusd::radlog(RAD_LOG_INFO, "$imsi -> $ip will change into @result[0].$ipTermination"); + $ip = @result[0] . "." . $ipTermination + } + } + undef $query, $aaaIP, $ipTermination, $ipMask, @spl, $imsi, $nasIP; + } + + if ($nasIP eq "216.168.191.35") { + $query = "SELECT SUBSTRING_INDEX(DAL, '.', 2), SUBSTRING_INDEX(AMS, '.', 2) FROM aaa_parallel_ranges WHERE SUBSTRING_INDEX(AMS, '.', 2) = " . $ipMask . " OR SUBSTRING_INDEX(DAL, '.', 2) = " . $ipMask . ";"; + my $aaaIP = $databaseConnection->prepare($query); + $aaaIP->execute; + my @result = $aaaIP->fetchrow_array; + if (scalar(@result) == 0) { + &radiusd::radlog(RAD_LOG_ERROR, "NO RESULT FOUND FOR $ipMask IN AMS"); + } + else { + if (@result[1] ne $ipMask) { + &radiusd::radlog(RAD_LOG_INFO, "$imsi -> $ip will change into @result[1].$ipTermination"); + $ip = @result[1] . "." . $ipTermination + } + } + undef $query, $aaaIP, $ipTermination, $ipMask, @spl, $imsi, $nasIP; + } + + if($nasIP eq "202.63.22.8"){ + $query = "SELECT SUBSTRING_INDEX(DAL, '.', 2), SUBSTRING_INDEX(AMS, '.', 2) FROM aaa_parallel_ranges WHERE SUBSTRING_INDEX(AMS, '.', 2) = " . $ipMask . " OR SUBSTRING_INDEX(DAL, '.', 2) = " . $ipMask . ";"; + my $aaaIP = $databaseConnection->prepare($query); + $aaaIP->execute; + my @result = $aaaIP->fetchrow_array; + if (scalar(@result) == 0) { + &radiusd::radlog(RAD_LOG_ERROR, "NO RESULT FOUND FOR $ipMask IN AMS"); + } else { + if(@result[1] ne $ipMask){ + &radiusd::radlog(RAD_LOG_INFO, "$imsi -> $ip will change into @result[ 1].$ipTermination"); + $ip = @result[1] . "." . $ipTermination + } + } + undef $query, $aaaIP, $ipTermination, $ipMask, @spl, $imsi, $nasIP; + } + &radiusd::radlog(0, "rlm_perl::parallelIPProcedure stop"); + + return $ip; +}