5 Aralık 2022 Pazartesi

Slack Slash Command to block an IP on AWS

Here is an example of a Slack command that can be used to block an IP address in AWS:

This Slack command can be implemented by creating a custom Slack app and integrating it with AWS using the AWS API and the Slack API. The Slack app can be installed and configured in a Slack workspace, and the command can be used by Slack users who have the appropriate permissions and credentials to access the AWS account and manage the security groups.


To implement the Slack command, the following steps can be followed:


  1. Create a custom Slack app and configure it with a bot user and the appropriate permissions and scopes to access the Slack workspace and interact with Slack users.
  2. Create an AWS IAM user and generate an access key and secret access key to access the AWS API using the AWS CLI or the AWS SDK.
  3. Install and configure the AWS CLI and the Slack CLI on the server where the Slack app is hosted.
  4. Define the Slack command and implement the command handler function that receives the command arguments and executes the required actions.
  5. Use the AWS CLI and the Slack CLI to call the appropriate AWS API and Slack API methods to block the IP address in the specified security group.
  6. Use the Slack API to send a message to the Slack user who invoked the command, and confirm that the IP address was successfully blocked in AWS.
  7. Here is an example of the implementation of the Slack command in Python using the slack-sdk and the awscli libraries:

import os
import slack
import awscli

# Define the Slack command and the command handler function
@slack.command("block-ip", help_text="Block an IP address in AWS")
def block_ip(event, args):
    # Parse the IP address argument
    if len(args) < 1:
        return slack.error("Please specify the IP address to block")
    ip_address = args[0]

    # Set the AWS access key and secret access key
    os.environ["AWS_ACCESS_KEY_ID"] = "<AWS_ACCESS_KEY>"
    os.environ["AWS_SECRET_ACCESS_KEY"] = "<AWS_SECRET_ACCESS_KEY>"

    # Call the AWS API to block the IP address in the specified security group
    result = awscli.aws("ec2", "revoke-security-group-ingress",
                        "--group-id", "<SECURITY_GROUP_ID>",
                        "--ip-permissions", "[{\"IpProtocol\": \"-1\", \"FromPort\": 0, \"ToPort\": 65535, \"IpRanges\": [{\"CidrIp\": \"%s/32\"}]}]" % ip_address)

    # Send a message to the Slack user who invoked the command
    if result.success:
        slack.send("The IP address %s was successfully blocked in AWS" % ip_address, event.channel)
    else:
        slack.send("Failed to block the IP address %s in AWS: %s" % (ip_address, result.stderr), event.channel)
In this script, the Slack command and the command handler function are defined using the @slack.command decorator from the slack-sdk library. The function receives the command. The code is demonstration purpose please do not include secrets in the source code use secret vaults or env variables.

1 Kasım 2021 Pazartesi

Akamai Datastream Logs to ELK Stack via API

 If you are using the security features of Akamai, using web security analytics(WSA) and SIEM log delivery features of Akamai  may be enough for dealing with daily security events. For CDN features there is  traffic and url traffic reports up to 90 days. You can also pull the logs via datastream api  and parse them with a Logstash json filter, output it to a Elasticsearch instance. Finally query, and present the parsed logs in a Kibana  dashboard. 

So to start you should follow the below steps. (Follow the links in the steps)

  • Enable Datastream with the desired fields from Luna Control Center
  • Create api privileged user
  • Test your user with the credential you have created in the above step with an api client like Postman
  • Follow the instructions to become familiar with the datastream api 
  • Now use this python code to fetch logs from a datastream and write the logs to a file that will be parsed via Logstash in the below steps. 
  • Schedule/Cronjob the python script to run in every 5 minutes.
  • Follow the instructions here to install ELK stack but do not configure logstash conf file yet. 
  • Use this logstash config file to parse the datastream pulled json files. 
  • Start all ELK services logstash, elasticsearch, kibana
  • Create Kibana index patttern 
  • Verify that logs are parsed properly and can be seen on Kibana Discovery application
  • Using the Lens app in Kibana create your visualizations to build up a dashboard. 

4 Nisan 2020 Cumartesi

How to automate enumerating base64 encoded parameter to exploit IDOR using python

In this article i want to show you how easy to automate an exploitation of an IDOR vulnerability using Python requests framework, where the IDOR parameter is base64 encoded.

If the parameter is not encoded with base64 you can use Burp intruder tab to create payloads and test the IDOR vulnerability.

First we should find the IDOR parameter to enumerate. Assume that you have the following url that you can download a report.

http://www.example.com/Download.ashx?RprtTkn=MTExMjIyfGZpeHBhcmFtZXRlcnxhbm90aGVyX2ZpeGVkX3BhcmFtZXRlcnw==
Look at the token carefully and try to base64 decode it. Keep in mind wherever and whenever you see such a string first try to base64 decode. You can use Burp decoder  tab or any other online tool to decode . After decoding the base64 encoded string we get the following decoded string
111222|fixparameter|another_fixed_parameter|
We are not interested with the fixed parameters So let's focus on the first bold part of the string where we can enumerate and find out whether it is exploitable or not.

To do this ;

  1. We should start a loop to change the bold part of the string which will be our IDOR enumeration value
  2. Then construct and base64 encode  
  3. Then send the request
Before starting to write our python code you can easily copy the authenticated request as cURL from chrome and convert it to python requests code using an online service . Because you will need to add authentication cookie and other headers before you made a request to the url. 

Combining all of the above explanations we have the following python code to enumerate the parameter.  








22 Aralık 2019 Pazar

Solving Palo Alto User-IP Mapping issue while connecting via Pulse Secure VPN

     In Palo Alto firewalls you can create username based rules. But TCP connections do not rely on usernames, they are based on source ip address, destination ip address, source port, destination port etc. So there should be mapping that will tell firewall which ip is mapped to the username. Palo Alto has various methods to collect and populate user-ip mappings table.
   
     In a Windows environment firewall admins used to integrate User-ID agent with Active Directory to listen logon events. So when a user logins to his/her PC in a domain, user-ip mapping is created from the logon event that is generated on the DC.

    After this brief introduction about user-ip mapping lets come to the issue, If  two users get same ip in a sequence.

   When users get connected to the corporate network via Pulse Secure VPN they are assigned an ip from the pool of a DHCP server. After this assignment, Palo Alto user id agent creates the user-ip mapping. When that specific user disconnected from the VPN, Pulse Secure sends DHCP release and the IP address sent back to the available ip pool. But the user-ip mapping is not cleared on the user-id agent side. So when another user gets connected and gets the same ip, all rules will be also valid for this user. But this is a really serious security issue.

   To solve this issue you can configure user-id agent as a syslog server and configure Pulse Secure VPN to forward auth events to this server. ,

   First you should define login-event regex to create user-ip mapping and logout regex  to clear user-ip mapping.





     Then you should add Pulse Secure VPN ip as a syslog sender and add above event filters to the profile.



    After these settings user-ip mappings will updated as expected. And no wrong user-ip mapping will occur.



21 Haziran 2018 Perşembe

Zimbra Visual Log Analysis with ELK Stack

For log analysis ELK(ElasticSearch-LogStash-Kibana) stack  is a powerful tool for Zimbra Mail Server logs, you can search logs and easliy create visually appealing graphics with Kibana interface.

In this post we will analyze the logs to find out which ip addresses abusing logins or brute forcing to Zimbra mail server.

So we first assume that if a single ip interacts with at least 5 different accounts we will count it as malicious usage. You should baseline your system accordingly otherwise there will be false positive decisions.

Now let's create the pie chart that will tell us these IP addresses visually



Then choose the following index



Now we will see whole number of logs to divide pie click Split Slices
Then
  1. Choose Terms as for the Aggregation 
  2. Choose src_ip for the Field
  3. Write top number of ip addresses you want to see in the Size section
Now you should see a pie chart as below.



Now we should add sub-bucket to see how many accounts these ip addresses interact.
So click Add sub-buckets, click  Split-Slices and configure the sub-bucket as below



Now you should see the following pie chart where the inner slices shows the source ip addresses and outer slices shows usernames that individual ip addresses interact.


Now lets describe what the pie chart tells us.

If you see an  inner slice sweeping one outer slice in 1 day or 1 hour period that is we can safely assume that this is not a malicious ip address.

But if you see an inner slice sweeping more than 5 outer slice than we can conclude that there is a malicious activity either brute force or logged in with multiple accounts from one ip addresses.




So to find out a brute-force we should add a filter with the string "invalid credentials".

19 Nisan 2018 Perşembe

Security Auditing with InSpec

InSpec is a tool from CHEF. With InSpec you can ,

  • Audit Policies
  • Check security requirements
  • Conduct compliance checks

InSpec can be installed on Linux, Mac or Windows. InSpec rules are written in ruby files.

I will give you some examples from the github repo about this amazing tool.



describe package('telnetd') do
  it { should_not be_installed }
end

describe inetd_conf do
  its("telnet") { should eq nil }
end


This rule will check the system against the installation of telnet and disallow this insecure service.

To run inspec save the above code snippet to a test.rb fie and in the command prompt run the following command to conduct the test.


inspec exec test.rb
you can also test this requirements against to remote systems.

on your linux servers using ssh ,

inspec exec test.rb -t ssh://user@hostname

or on windows through WinRM

inspec exec test.rb -t winrm://Administrator@windowshost --password 'your-password'

if you are familiar with CHEF compliance check, you can also make compliance check with the following syntax


  inspec compliance SUBCOMMAND ...   # Chef Compliance commands



For example this code uses the sshd_config resource to ensure that only enterprise-compliant ciphers are used for SSH servers.

describe sshd_config do
  its('Ciphers') { should cmp('chacha20-poly1305@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr') }
end

You can see detailed tutorials in the following link 





13 Nisan 2018 Cuma

Moodle Quiz Activity with 500 Concurrent User

We have experienced a Quiz Activity with 500 concurrent user and i want share this experience with you. Because these insights are really valuable for system administrators, that i could not find any suggestion before this Quiz Activity.  Let me write the details about the system and the quiz activity.
We have installed moodle on a virtual machine VMWare with the following configuration.

We set the vm cpu to 16 shared vcpu,  and 24GB shared RAM
Running Centos 7.0 Minimal with php5.X, apache and mariadb with 700 max_connection setting.
Quiz activity with 20 Question and 30 Minute timespan and 17 Minute attempt time limit. 2 Question per page. Question order and choices were shuffled. Auto submit open attempt setting was on.




CPU and RAM usage was crucial for us. We see maximum 12 GB ram usage which is roughly 1 GB per 50 User
We see %95 CPU usage when the quiz started.

Before quiz started i stopped cron jobs and automated course backups.


3 Nisan 2017 Pazartesi

Email to user when a role is assigned

When an admin/teacher assigns a role to a user in course or category context you can send an email to the user which the role has been assigned by modifying the following moodle lib file.

/var/www/html/moodle/admin/roles/assign.php

In the file around the lines 103-111 by adding email_to_user() moodle lib function you can send the email to the user from the moodle support user. Be careful that email_to_user() function accepts from and to users as moodle user objects so you can not write simply emails and send.         

   foreach ($userstoassign as $adduser) {
                $allow = true;
 

                if ($allow) {
   
                    role_assign($roleid, $adduser->id, $context->id);


                    email_to_user($adduser, $supportuser, "Your role has been assigned in Moodle", "You have been assigned as a ".$assignableroles[$roleid]." in the ".$contextname ); 
                }
            }


After you add this the user will receive an email with subject "Your role has been assigned in Moodle" and message ie. "You have been assigned as a Course creator in the Category: Mathematics"

21 Şubat 2017 Salı

Ansible And Vmware

Do you know that you can manage your VMWARE virtual infrastructure with ansible. If you are a devops admin you can also use vRealize Orchestrator to provision test, product or beta stage servers for your developers. But if you do not need such an enterprise solution you also use Ansible to manage your vMWare infrastructure. As stated in Ansible web page you can use ansible for

  • Managing vSphere datacenters, clusters, hosts and guests
  • VM template and snapshot management
  • vSwitches, DNS settings, firewall rules and NAT gateway rules 
You can find the modules for vmware in the following link.

http://docs.ansible.com/ansible/list_of_cloud_modules.html#vmware

To be able to run vm modules you have the install the following python libraries.

pysphere
PyVmomi



14 Şubat 2017 Salı

Linkedin Job Search Tricks

Trick 1: You cannot find direct links to Linkedin Jobs page but if you visit http://www.linkedin.com/jobs You can search jobs even you are not authenticated with your Linkedin account.

Trick 2: If you search a keyword in the unauthenticated Linkedin Jobs page http://www.linkedin.com/jobs The location will be default USA. The last but the trick i love most is

 Trick 3: If you make a search for a keyword when you logged in to your linkedin account. It will first search the jobs listed in your country if there is no result for the keyword, then you will see a link to search the keyword in the worldwide. Again there is no direct checkbox or setting for this. But if you use the following URL you can search your keyword worldwide.

https://www.linkedin.com/jobs/search?keywords=PUT_YOUR_KEYWORD_HERE&locationType=Y&orig=MDYS 

for example if you want to search the jobs includes keyword "linux" in worlwide you can use the following url

https://www.linkedin.com/jobs/search?keywords=linux&locationType=Y&orig=MDYS

29 Kasım 2016 Salı

Office 365 Account Creation and Bulk Email User Details with Powershell

If you have purchased office365 to be used in your organization, your first duty is to open accounts in office 365 after configuring related DNS settings in your DNS server.

To open these accounts in bulk you can use  office365 admin panel import pane. But without going to admin panel you can manage this tedious work using powershell.

The following powershell script will help you to

  • Create  Accounts
  • Assign Office365 License Pack you have
  • Export Created Account  details including assigned temproary passwords in NewAccountResults.csv file.  


Beforehand you should have  list of your staffs details in users.csv file.



#Pop-up will appear and wait you to enter administrator account credentials
$credential = get-credential

#Imports the installed Azure Active Directory module.
Import-Module MSOnline

#Establishes Online Services connection to Office 365 Management Layer.
Connect-MsolService -Credential $credential

#Create Users
Import-Csv .\users.csv | ForEach-Object {
#Generate Random Password
$office_365_password = ([char[]]([char]33..[char]95) + ([char[]]([char]97..[char]126)) + 0..9 | sort {Get-Random})[0..8] -join ''
#Create User
New-MsolUser -UserPrincipalName $_.UserPrincipalName -DisplayName $_.DisplayName -Password $office_365_password -UsageLocation $_.UsageLocation
}|Export-Csv -Path ".\NewAccountResults.csv"

#Assing License Pack to the unlicensed users
Get-MsolUser -All -UnlicensedUsersOnly  | Set-MsolUserLicense  -AddLicenses "yourdomain365:OFFICESUBSCRIPTION_PACKNAME"

Then you should send the temproary passwords created  to the personal email acounts of your staff by using the following powershell script.


#From : Sender Email Account 
$EmailFrom = "Name Surname <sender@domain.com>"
 
# Reporting: Report on Success and Failure (optional)
$EmailDeliveryNotificationOption = "onSuccess, onFailure"
 
# Server: Your Email SMTP server
$EmailSMTPserver = "mail.example.com"


# Users: csv file path, file includes  Name, PersonelEmail, Office365Account, Password
$SourcePath = ".\mail_merge_powerdshell.csv"
 
# Import csv file
$Users = Import-Csv  -Path $SourcePath
 
# ####################
# END Variables
# ####################
 
# Begin Loop: Do the following with each row of the file you imported, referencing columns by their header
foreach ($User in $Users) {
 
# To: User's email address
$EmailTo = $User.PersonelEmail
 
# Subject: Email subject (may merge variables)
$EmailSubject = "About Your Office365 Account " + $User.Name + "."
 
# Body: Email body, with HTML formatting
$EmailBody = "<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"">"
$EmailBody += "<html xmlns=""http://www.w3.org/1999/xhtml""><head>"
$EmailBody += "<meta http-equiv=""Content-Type"" content=""text/html; charset=UTF-8"" />"
$EmailBody += "<meta name=""viewport"" content=""width=device-width, initial-scale=1.0""/>"
$EmailBody += "<title>" + $EmailSubject + "</title>"
$EmailBody += "</head><body bgcolor=""#FFFFFF"" style=""font-family: sans-serif; color: #000000"">"
$EmailBody += "<p>Dear " + $User.Name + ":</p>"
$EmailBody += "<p>Our Organization has purchased Office365 subscription for 1 Year</p>"
$EmailBody += "<li>Your Office365 Account: <strong>" + $User.Office365Account + "</strong></li></ul></p>"
$EmailBody += "<li>Your Office365 Account Password: <strong>" + $User.Password + "</strong></li></ul></p>"
$EmailBody += "<li>You can Access Office Login to your office 365 using <a href='https://login.microsoftonline.com/'>This Link </a>"
$EmailBody += "</body></html>"
 
echo $EmailBody
echo $Users
# Merge: Conduct the email merge, sending emails (remove -WhatIf)
Send-MailMessage -To $EmailTo -From $EmailFrom -Subject $EmailSubject -Body $EmailBody -BodyAsHTML -SmtpServer $EmailSmtpServer -DeliveryNotificationOption $EmailDeliveryNotificationOption

28 Ekim 2016 Cuma

Dspace and Piwik Integration

Piwik definition from the FAQ of piwik.org is as below.
Piwik is a downloadable, Free (GPL licensed) web analytics software platform. It provides detailed reports on your website and its visitors, including the search engines and keywords they used, the language they speak, which pages they like, the files they download and so much more. Piwik aims to be an open source alternative to Google Analytics. Piwik is PHP MySQL software which you download and install on your own webserver. At the end of the 5-minute installation process you will be given a JavaScript tag. Simply copy and paste this tag on websites you wish to track (or use an existing plugin to do it automatically for you).
 After installation and configuration of piwik you can track  visitors analytics of your institutional repo. If you want to embed these analytics into Dspace you can use the widgets of Piwik.  There are three places that you can embed the analytics.

1-)By adding iframe widget code into Community/Collection introductory, news html sections
2-)By adding iframe  widget code into page-structure.xsl
3-)By adding iframe widgt code into item-view.xsl

First method is the easiest method. You go the widgets menu through the admin panel of Piwik and get the iframe embed code.


Then you go to a collection/community and edit which you want to add the widget as below.

Then update the collection/community and that's it.  You will see the analytics in the community/collection page. But one more point is missing the widget will show whole analytics of your DSpace repo. You should segment  analytics that will only reflect the analytics  of the collection/community you want. To do that you can use page-url parameter with the url of the community/collection. Let's assume that your collection url is
                  
http://dspace.university.edu/handle/11111/23 

Then you should add the following code to the widget code

segment=pageUrl%3D%3Dhttp%253A%252F%252Fdspace.university.edu%252Fhandle%252F11111%252F23

You should add this after the yesterday keyword of the embed code then the iframe code will become as below



The second and third method are nearly same but the places are different. If you want to add analytics to all pages you should use page-structure.xsl. But if you want to only add an analytic to item pages you should use the item-view.xsl. Now let's pass to the method. Open page-structure.xsl or item-view.xsl with your favorite editor (mine is nano) and add the following template codes to the xsl file. Lets add an realtime map to all pages in the header part of Dspace.


nano /dspace/webapps/xmlui/themes/Mirage2/xsl/core/page-structure.xsl

We add the template call code after the following lines




offcanvas
row-offcanvas-right">

 <xsl:call-template name ="realtimemap"/>


then in the bottom of the page we will define the template. 


 
Attention you should all change & characters with & in xsl files in the iframe embed code!
You have noticed that there is variable {$piwik-uri} in the embed code segmentation part. This is the url variable that you should define in the global-variables.xsl as below ,




Then you will see the realtime on all pages of your Dspace.








21 Eylül 2016 Çarşamba

Linux için 2-Aşamalı Kimliklendirme

Eğer siz de benim gibi güvenlik alanında paranoyaklık seviyesini 1 tık arttırdıysanız iş ve ev bilgisayarı olarak bir linux dağıtımı kullanmaya başlamışınızdır çoktan. Kullanıcı girişlerinde ve sudo ile işlem yaparken sadece şifre yerine önce tek kullanımlık OTP sonrada şifre kullanmak istiyorsanız yani iki aşamalı kullanıcı kimliklendirme metodunu kullanmak istiyorsanız ubuntu repolarında google authenticator ile beraber çalışan bir pam modülü mevcut. Bunu aktif edip cep telefonu uygulamasını da ayarladıktan sonra sudo ile işlem yaparken cep telefonunuzda oluşan OTP güvenlik kodunu ve şifrenizi girerek kullanmanız yeterli olacaktır. Gelelim bu dediklerimi nasıl yaptığımıza ;

1-) Öncelikle bilgisayarımıza pam modülünü kuruyoruz. Cep telefonumuza da marketten Google Authenticator uygulamasını kuruyoruz.

sudo apt-get install libpam-google-authenticator

2-) Daha sonra kurduğumuz bu pam modülünü ayarlardan aktif ediyoruz.
Bunun için  /etc/pam.d/common-auth dosyasında aşağıdaki satırı buluyoruz.

auth    [success=1 default=ignore]      pam_unix.so nullok_secure

ve hemen bu satırın üzerindeki satıra aşağıdaki satırı ekliyoruz.

auth required pam_google_authenticator.so

Böylelikle pam modülümüzü aktif etmiş oluyoruz. Şimdi sıra geldi her bir kullanıcı için pam modülünün ayarlarını yapmaya.Sistemimizde varolan her kullanıcı için aşağıdaki işlemleri yapmamız gerekmektedir.

3-) Hali hazırda girilmiş kullanıcı terminalinde iken aşağıdaki komutu çalıştırıyoruz cep telefonumuzdan da google-authenticator uygulamızı açmış şekilde bekliyoruz.


 ~$ google-authenticator


 

İlk soruyu y ile geçtikten sonra ekrana çıkan barkodu google-authenticator uygulamasından sağ üst köşeden Set up account --> Scan a barcode diyerek tarıyoruz. bu aşamadan sonra cep telefonumuzda hesap eklenmiş ve dakikada
bir OTP güvenlik kodu üretiyor olacaktır.  Your emergency Codes are diye çıkan 5 satırlık acil durum kodunu da güvenli bir yere kaydetmeyi sakın unutmayın. Bu kodlar telefonunuzu çaldırırsanız veya kaybederseniz hesabınıza giriş yapabilmenizi sağlayacaktır.
 Diğer gelen sorulara da y diyerek sonlandırın.
Artık sistemden logout olduktan sonra bilgisayarınız sizden önce verification code isteyecek sonra şifrenizi isteyecektir. Verification code yerine telefonda beliren kodu yazın ve enter a basın daha sonra şifrenizi girin ve enter a basın ve sisteme giriş yapın.


22 Haziran 2016 Çarşamba

ScienceDirect Live Import to DSpace

Entering all the metadata is really tedious work so Sciencedirect and Atmire has developed a plugin for dspace which ingest Sciencedirect articles into DSpace easily.
After you apply the patch which is sent from Sciencedirect integration support. get API KEY from the link http://dev.elsevier.com/myapikey.htmlwrite this api key into the configuration file ${dspace.dir}/config/modules/elsevier-sciencedirect.cfg like this elsevier-sciencedirect.api.key =a2e3feffgd3542345gsdf
 then  mvn and fresh install your DSpace if you successfully build and deploy DSpace you will have Elsevier Import menu both in the submission steps and Global Import menu. You can watch it below.


 
 This feature will be readily available in upcoming  DSpace 6.0


10 Mayıs 2016 Salı

Creating proxy pac files automatically from Squid Conf file.

Pac files are automatic proxy configuration files written in js format that browsers can interpret and route clients to the proxy according to the domain name they visit. This pac file should be published through a web server or can be manually downloaded and the browser should be configured to the downloaded pac file. Squid is an open source proxy server which can be configured to be used by libraries for out off campus access to the academic database subscriptions . When someone add/delete/update an entry in the squid conf file, pac files should also be updated properly. This is a tedious task for large numbers of urls. Python script which automates this task with per minute cron entry

The script pushes syslogs to the syslog of the system on every execution. If any changes made to the squid file, the pac file is updated by checking the hash of the old and new states of the file. Also the squid proceess is restarted if any change has been made.



import hashlib
import os
import syslog
import datetime
import shutil
import subprocess
squid_config_file_path="/etc/squid/kutuphane_veritabanlari.squid"
squid_config_file = open(squid_config_file_path)
readFile = squid_config_file.read()
pac_file_root="/var/www/html"
hash_file="%s/hash_file"%pac_file_root
old_pac_file="%s/proxy.pac"%pac_file_root
date_=datetime.datetime.now() 
backup_file="%s/pac_backup_file_%s.pac"%(pac_file_root,date_)
new_pac_filee="%s/new_pac_file.pac"%pac_file_root
sha1Hash = hashlib.sha1(readFile)
sha1Hashed = sha1Hash.hexdigest()
if os.path.exists(hash_file):
   hash_filee = open(hash_file,'r')
   readHash = hash_filee.readline()
   hash_filee.close()
   if not readHash==sha1Hashed:
 syslog.syslog(syslog.LOG_WARNING,"Hashes are different  kutuphane_veritabanlari.squid config file has been modified the old hash :%s new hash:%s "%(readHash,sha1Hashed))
 shutil.copyfile(old_pac_file,backup_file) 
 new_pac_file = open(new_pac_filee,"w+")
    new_pac_file.write("function FindProxyForURL(url, host) {\n")
 new_pac_file.write("var proxyserver = 'proxy2.iyte.edu.tr:8080';\n")    
 new_pac_file.write("var proxylist = new Array(\n")
    with open(squid_config_file_path) as openfileobject:
           for line in openfileobject:
          if (line[0].isalpha() or line.startswith(".")):
   new_pac_file.write('"%s",\n' % (line.rstrip()))
        new_pac_file.write('"dummy.com"\n);\n')
    new_pac_file.write("for(var i=0; i<proxylist.length; i++) {\n")
    new_pac_file.write("\tvar value = proxylist[i];\n")
    new_pac_file.write("\t\tif (dnsDomainIs(host, value) ) {\n")
    new_pac_file.write("\t\treturn 'PROXY '+proxyserver;\n")
    new_pac_file.write("\t}\n")
    new_pac_file.write("}\n")
    new_pac_file.write("return 'DIRECT';\n")
    new_pac_file.write("}")
 new_pac_file.close()
 os.remove(hash_file) 
 hash_file_create=open(hash_file,'w')
     hash_file_create.write(sha1Hashed)
     hash_file_create.close() 
 shutil.copyfile(new_pac_filee,old_pac_file)
 subprocess.call("%s %s %s" % ('service', 'squid', 'reload'),shell=True)
   else:
 syslog.syslog(syslog.LOG_WARNING,"Hashes are same kutuphane_veritabanlari.squid config file hasn't been changed.")
else:
    hash_file_create=open(hash_file,'w')
    hash_file_create.write(sha1Hashed)
    hash_file_create.close()
squid_config_file.close()


30 Ekim 2015 Cuma

Moodle Adding Event Monitor Rules in Bulk to all of the Courses

Event Monitor Rules feature is a new and a missing feature which has arrived to moodle in version 2.8. This feature help students to be informed by email if a course material added updated or deleted etc. So they do not need to login to check whether a content has been added to the course or not. It also informs teachers and admins about  a specific event occurred (a course has been added, a content has been viewed etc.).

But if you are administering a moodle with 150+ courses it is real heavy duty task to add rules one by one to every course created in moodle.

So with the following php code you can add a rule to the every course created in moodle.

$link = mysql_connect('moodle_host_name_or_ip', 'database_username', 'database_password');
//if connection is not successful you will see text error
if (!$link) {
             die('Could not connect: ' . mysql_error());
}
//if connection is successfuly you will see message bellow
echo 'Connected successfully\n';

$type="\\core\\event\\course_module_created";
$content="Course content has been added.
";
$content2="Link : {rulename}
Description: {description}
Event Name: {eventname}
";

$type=mysql_real_escape_string($type);
$content=mysql_real_escape_string($content);
$content2=mysql_real_escape_string($content2);

mysql_select_db('moodle');


//This query finds the courses in moodle
$query_id= "select id from mdl_course";
$result_id = mysql_query($query_id);
echo $result_id;
while($row = mysql_fetch_row($result_id)) {
    echo $row[0];
    echo "\n";
//This below query adds the event monitor rules into he courses.
$query="INSERT INTO mdl_tool_monitor_rules (userid,courseid,name,plugin,eventname,description,
descriptionformat,frequency,timewindow,template,templateformat,timecreated,timemodified) VALUES('2','".$row[0]."',
'Course Content has been added','core','".$type."','".$content."','1','1','60','".$content2."','1','1445596840','1445596840')";
mysql_query($query);
    }
mysql_close($link);

?>
By changing the $type variable you can add any kind of event rules to the moodle.

7 Nisan 2014 Pazartesi

Dspace <-> LDAP Entegrasyonu

Bu yazıda Dspace kurumsal dijital arşiv yazılımının kurumunuzda hali hazırda başka hizmetler(Email,yazılım kimliklendirme(authentication), vb.) için kullanılan LDAP dizin hizmeti ile entegrasyonunu anlatacağım.

Bu entegrasyon sayesinde kurumunuzdaki kullanıcılara dspace üzerinde tekrardan kullanıcı adı ve şifre oluşturup gönderme işinden kurtulmuş olacaksınız ayrıca tek şifre olduğu için kullanıcılar ayrı bir şifre hatırlamak zorunda kalmayacaklar.

DSpace çoklu ve aşamalı kimliklendirmeyi(authentication) desteklediği için hem el ile oluşturulan kullanıcılar hem de LDAP da bulunan kullanıcılar aynı anda sisteme giriş yapabilmektedirler.

DSpace yazılımında varsayılan olarak el ile oluşturularan kullanıcılar giriş yapabilmektedirler. Biz buna ek olarak LDAP kimliklendirme modülünün ayarlarını yapıp aktif edeceğiz.

 Ayarları DSpace 4.x için ve Linux tabanlı sistemler için yapacağız. Ayarları yaparken İngilizce bilenler DSpace Authentication Plugins sayfasından adımları takip edebilirler.

 DSpace de değişiklik yapacağımız dosyalar aşağıda listelenmiştir.
/dspace/config/modules/authentication.cfg - Ldap kimlendirmenin aktif edildiği dosya
/dspace/config/modules/authentication-ldap.cfg - Ldap sunucu ayarlarının yapıldığı dosya

Linux komut satırında metin editörü olarak nanoyu kullanmaktayım isteyenler pico veya vi kullanabilirler.

Öncelikle authentication-ldap.cfg dosyasında LDAP sunucumuzun ayarlarını yapacağız. bize gerekli olan alanları LDAP  sistem yöneticimizden temin edebiliriz. Linux terminalinde komut satırına aşağıdaki komutu girererek authentication-ldap.cfg dosyasındaki gerekli değişiklikleri yapıyoruz.


nano /dspace/config/modules/authentication-ldap.cfg
 
Dosya içerisinde belirtilen ayarları yapıyoruz. 

enable = true #LDAP kimliklendirmeyi aktif hale getirmek için
autoregister = true # Dspace içinde Otomatik kullanıcı kaydı oluşturmak için

provider_url = ldap://ldapsunucuadi.okuladi.edu.tr/ #ldap sunucusunun adresi eğer güvenli (ssl) ldap protokolü ise ldaps://  kullanılacaktır.
id_field = uid # kullanıcı adının tekil olarak saklandığı alan genelde uid dir bu ayar.
object_context = ou=iyteusers,dc=iyte,dc=edu,dc=tr #kullancıların LDAP ağacında nerde tutulduklarını gösterir
search_context =  ou=iyteusers,dc=iyte,dc=edu,dc=tr #object_context ile genelde aynı ayar yapılır.

email_field = mail #kullanıcı email adresinin  LDAP da hangi alanda tutulduğunu gösterir
surname_field = sn #kullanıcı soyadının LDAP da hangi alanda tutulduğunu gösterir.
givenname_field = givenName #kullanıcı adının LDAP da hangi alanda tutulduğunu gösterir
phone_field = r-ilk-telefon #kullanıcı telefon numarasının LDAP da hangi alanda tutulduğunu gösterir

#login.specialgroup = group-name #bu ayar grouplara göre role atama işi için kullanılacak fakat bu yazıda bundan bahsedilmeyecek.

search_scope = 2 #LDAP ağacında hangi derinliğe kadar arama yapılacağını belirten ayar bu 2 olsun.

search.anonymous = false #kullanıcıları LDAP sunucusundan sorgularken anonim sorgulama yapılıp yapılmayacağını belirten ayar
search.user =  cn=ldap_yonetici_kullanici_adi,dc=okuladi,dc=edu,dc=tr
search.password = ldap_yonetici_sifresi

#netid_email_domain = @example.com #LDAP sunucuda tam email adresleri yoksa domain adını buraya yazınız.



Gerekli değişiklikleri yaptıktan sonra kaydedip çıkıyoruz ve sıra geldi ayarlarını yaptığımız LDAP kimliklendirme modülünü aktif etmeye. Bunun için ayar yapmamız gereken dosya ise authentication.cfg dosyası demiştik. Bu dosyada gerekli değişiklikleri yapmak için linux terminalinde aşağıdaki komutu çalıştırıyoruz.

nano /dspace/config/modules/authentication.cfg

Dosya içerisinde LDAP satırını ekliyoruz,

plugin.sequence.org.dspace.authenticate.AuthenticationMethod = \
        org.dspace.authenticate.PasswordAuthentication,\
        org.dspace.authenticate.LDAPAuthentication

Bu değişikliğide yaptıktan sonra uygulama sunucumuzu(biz tomcati kullanıyoruz) tekrardan başlatıyoruz.

service tomcat7 restart

Her şey yolunda gittiyse web arayüzünden giriş yapmak istediğinizde karşınıza iki seçenek çıkacaktır birisi el ile oluşturulmuş kullanıcılar için  password kimliklendirme diğeri ise ldap seçeneği.






İzleyiciler